-
Notifications
You must be signed in to change notification settings - Fork 10
/
bot.js
90 lines (76 loc) · 2.66 KB
/
bot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require('dotenv').config();
const Discord = require('discord.js');
const cron = require('node-cron');
const { TOKEN, VOICE_CHANNEL_ID, GUILD_ID, TEXT_CHANNEL_ID, MATCH_DINGS_WITH_HOUR } = process.env;
const Client = new Discord.Client();
let guild, voiceChannel, textChannel ;
// When bot comes online check the guild and voice channel are valid
// if they are not found the program will exit
Client.on('ready', async () => {
try {
guild = await Client.guilds.fetch(GUILD_ID);
voiceChannel = guild.channels.cache.get(VOICE_CHANNEL_ID);
} catch (error) {
console.log(error);
process.exit(1);
}
textChannel = guild.channels.cache.get(TEXT_CHANNEL_ID);
console.log('Big Ben Ready...');
Client.user.setPresence({ activity: { name: 'the hour', type: 'WATCHING' }, status: 'idle' });
});
// use node-cron to create a job to run every hour
const task = cron.schedule('0 0 */1 * * *', async () => {
let { hour, amPm, timezoneOffsetString } = getTimeInfo();
// if text channel was defined send message in chat
if (textChannel) {
const messageEmbed = new Discord.MessageEmbed()
.setColor('#FFD700')
.setTitle(`The time is now ${hour}:00 ${amPm} GMT${timezoneOffsetString}`)
textChannel.send(messageEmbed);
}
// check if VC defined in config is empty
if (voiceChannel.members.size >= 1) {
try {
Client.user.setPresence({ activity: { name: 'the big bell', type: 'PLAYING' }, status: 'available' });
// connect to voice channel
const connection = await voiceChannel.join();
// counter for looping
let count = 1;
// immediately invoked function that loops to play the bell sound
(function play(Client) {
connection.play('bigben.mp3')
.on('finish', () => {
count += 1;
if (count <= hour && MATCH_DINGS_WITH_HOUR == 'true') {
play(Client);
} else {
connection.disconnect();
Client.user.setPresence({ activity: { name: 'the hour', type: 'WATCHING' }, status: 'idle' });
}
})
})();
} catch(error) {
console.log(error);
}
}
});
// function to get current time and return object containing
// hour and if it is am or pm
const getTimeInfo = () => {
let time = new Date();
let hour = time.getHours() >= 12 ? time.getHours() - 12 : time.getHours();
hour = hour === 0 ? 12 : hour;
let amPm = time.getHours() >= 12 ? 'PM' : 'AM';
// get gmt offset in minutes and convert to hours
let gmtOffset = time.getTimezoneOffset() / 60
// turn gmt offset into a string representing the timezone in its + or - gmt offset
let timezoneOffsetString = `${gmtOffset > 0 ? '-':'+'} ${Math.abs(gmtOffset)}`;
return {
hour,
amPm,
timezoneOffsetString
}
}
// start the cron job
task.start();
Client.login(TOKEN);