· 5 years ago · Jan 08, 2021, 01:08 AM
1const fs = require('fs');
2const http = require('http');
3const Discord = require('discord.js');
4
5// For the API request
6const httpOptions = {
7 host: 'worldtimeapi.org',
8 port: 80,
9 path: '/api/timezone/Europe/London',
10 method: 'GET',
11 headers: {
12 "Content-Type": "application/json"
13 },
14};
15
16// The subscribed channels
17var channels = [];
18
19// If the phrase has been said this week (resets after 24 hours so as not to post twice on the same day)
20var saidThisWeek = false;
21
22// Check for channels list and create it if it does not exist.
23if(fs.existsSync("channels.json"))
24{
25 channels = JSON.parse(fs.readFileSync("channels.json"))["channels"];
26 console.log("Channel list loaded. Found " + channels.length + " channels.");
27}
28else
29{
30 fs.writeFileSync("channels.json", JSON.stringify({"channels": []}));
31 console.log("No channel list found. Creating empty file.")
32}
33
34// Discord client
35var client = new Discord.Client();
36
37client.on('ready', () => {
38 console.log("Bot connected.");
39
40 // Check the time every minute
41 setInterval(() => {
42 var req = http.request(httpOptions, res => {
43 console.log('Status code: ' + res.statusCode);
44
45 res.on('data', d => {
46 // If it is Tuesday, say the phrase
47 if(JSON.parse(d)["day_of_week"] == 2 && !saidThisWeek)
48 {
49 for(var i = 0; i < channels.length; i++)
50 {
51 client.channels.get(channels[i]).send("is chewsday innit?");
52 }
53
54 // Make sure it isn't said more than once
55 saidThisWeek = true;
56
57 // Reset saidThisWeek after 24 hours
58 setTimeout(() => {
59 saidThisWeek = false;
60 }, 86400000);
61 }
62 });
63 });
64
65 // Error handler
66 req.on('error', err => {
67 console.error(err);
68 });
69
70 // End request (needed for some reason)
71 req.end();
72 }, 60000);
73});
74
75client.on('message', msg => {
76 // If message starts with "!tuesdayChannel", add the following channel ID to the list and write to the file.
77 if(msg.content.startsWith("!tuesdaychannel"))
78 {
79 var strArray = msg.content.split(' ');
80 if(/[0-9]{18}/.test(strArray[1]))
81 {
82 channels.push(strArray[1]);
83 fs.writeFileSync("channels.json", JSON.stringify({"channels": channels}))
84 msg.reply("Channel set");
85 }
86 else
87 {
88 msg.reply("Invalid channel ID. Please specify an 18 character number.");
89 }
90 }
91});
92
93client.login("Your bot key here");