loader

Logic square is a leading custom web & mobile app development company that offers its services to small businesses in the USA at an affordable cost.

Building a Simple Bot for Discord

Before Starting to Code

Coding

				
					const moment = require('moment') 
const Agenda = require('agenda')
const agenda = new Agenda({
	db: {address: process.env.MONGO_CONNECTION_STRING},
	processEvery: '30 minutes'
});

const Discord = require('discord.io');
const bot = new Discord.Client({
	autorun: true,
	token: process.env.BOT_TOKEN
});

agenda.on('ready', function() {
	agenda.start();
});

function graceful() {
	agenda.stop(function() {
		process.exit(0);
	});
}

process.on('SIGTERM', graceful);

process.on('SIGINT' , graceful);
				
			
				
					let sendBirthdayMsg = function(user, channelID) {
	bot.sendMessage({
	to: channelID,
	message: `@${user} Happy Birthday to You!!!`
	});
}

agenda.define('send birthday wish', function(job, done) {
	let data = job.attrs.data; 
	sendBirthdayMsg(data.whoseBirthday, data.channelID)
	done()
});

let scheduleWish = function(whoseBirthday, whenBirthday, channelID) {
	agenda
		.create('send birthday wish', {whoseBirthday, channelID}) 
		.schedule(whenBirthday)
		.repeatEvery('1 year')
		.save()
}
				
			
				
					bot.on('message', function(user, userID, channelID, message, event) {

	if (!message.includes(`<@${bot.id}>`)) return

	let botSays = "
	let cleanedMsg = message.replace(`<@${bot.id}>`,").replace(/ +(?= )/g,").trim()
	let whoseBirthday = cleanedMsg.split(' ')[0]
	let whenBirthday = cleanedMsg.split(' ')[1]
	let whenBirthdayMoment = moment(whenBirthday, ['MM-DD','DD/MM']) 

	if ( !whenBirthdayMoment.isValid() ) {
		botSays = `@${user} Sorry Boss, I dint get what you just said!`
	} else {
		if ( whenBirthdayMoment.isBefore(moment(), 'days') ) {
			whenBirthdayMoment.add(1, 'year') 
		}
		scheduleWish(whoseBirthday, whenBirthdayMoment.toDate(), channelID)
		botSays = `@${user} OK Boss! I'll wish "${whoseBirthday}" every year on ${whenBirthdayMoment.format("Do MMMM")}!`
	}

	bot.sendMessage({
		to: userID,
		message: botSays
	})
});
				
			

WE DESIGN, DEVELOP AND MARKET BEAUTIFUL WEB & MOBILE APPS

Author

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *