forked from Ayaan-Govil/TournaBot
-
Notifications
You must be signed in to change notification settings - Fork 2
/
remind_loop.js
163 lines (146 loc) · 7.4 KB
/
remind_loop.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Dependencies
const Discord = require('discord.js');
const Vibrant = require('node-vibrant');
const accurateInterval = require('accurate-interval');
const setAccurateTimeout = require('set-accurate-timeout');
const { convertEpoch, convertEpochToClock, queryAPI } = require('./functions');
// MongoDB Models
const accountModel = require('./database/models/account');
// Map used for tracking reminders
// Cannot ping two tournaments within the same hour for a person, but that shouldn't be an issue
const reminderMap = new Map();
async function remindLoop(client) {
const loop = accurateInterval(setReminders, 3600000, { immediate: true });
let loopTracker = 0;
function setReminders() {
loopTracker++;
console.log(`Iterating through reminder loop ${loopTracker} at ${convertEpochToClock(Date.now() / 1000, 'America/Los_Angeles', true)}`);
accountModel.find({
reminder: true
}, function (err, result) {
if (err) throw err;
// Will add delay for one second per iteration or ask for rate limit upgrade if rate limit is reached
for (let user of result) {
//console.log(`Iterating through ${user.discordtag}`);
let discordID = user.discordid;
var slug = user.profileslug;
var query = `query UserUpcomingTournaments($slug: String) {
user(slug: $slug) {
tournaments(query: {filter: {
upcoming: true,
past: false
}}) {
nodes {
id
name
slug
numAttendees
startAt
isOnline
images {
height
width
url
}
events {
id
name
numEntrants
startAt
checkInEnabled
checkInBuffer
checkInDuration
}
streams {
streamSource
streamName
}
}
}
}
}`;
queryAPI(query, { slug }).then(data => {
if (data.data) {
let upcomingTournaments = data.data.user.tournaments.nodes
if (upcomingTournaments) {
upcomingTournaments.reverse();
for (let tournament of upcomingTournaments) {
if (!reminderMap.has(discordID)) {
let timeDiff = tournament.startAt - Date.now() / 1000;
//console.log(`Time Difference: ${timeDiff / 3600} Hours`);
if (timeDiff <= 7200 && timeDiff >= 3600) {
console.log(`Tournament found that is within 1-2 hour constraint at ${convertEpoch(Date.now() / 1000, 'America/Los_Angeles')}. Setting reminder...`);
let offset = tournament.startAt * 1000 - Date.now() - 3600000;
reminderMap.set(discordID, setAccurateTimeout(function () { reminder(discordID, tournament) }, offset));
function reminder(id, tournament) {
let imageurl = ['', ''];
if (tournament.images) {
for (let image of tournament.images) {
if (image) image.height === image.width ? imageurl[0] = image.url : imageurl[1] = image.url;
}
}
if (imageurl[0].length) {
let v = new Vibrant(imageurl[0]);
v.getPalette(function (err, palette) {
if (err) throw err;
sendReminder(palette.Vibrant._rgb);
}).catch(err => console.log(err));
} else sendReminder('#222326');
function sendReminder(sideColor) {
let tournamentOnline = 'Offline';
if (tournament.isOnline) tournamentOnline = 'Online';
let events = [];
for (e = 0; e < tournament.events.length; e++) {
if (e < 3) {
events.push(`\`${tournament.events[e].name}\``);
events.push(`${tournament.events[e].numEntrants} Entrants`);
events.push(`*${convertEpoch(tournament.events[e].startAt, 'America/Los_Angeles')}*`);
if (tournament.events[e].checkInEnabled) events.push(`__Check-in opens at ${convertEpochToClock(tournament.events[e].startAt - tournament.events[e].checkInBuffer - tournament.events[e].checkInDuration, 'America/Los_Angeles', false)} and closes at ${convertEpochToClock(tournament.events[e].startAt - tournament.events[e].checkInBuffer, 'America/Los_Angeles', false)}.__`);
} else {
events.push('\`And more...\`');
e = tournament.events.length;
}
}
let streams = [];
if (tournament.streams) {
for (let stream of tournament.streams) {
if (stream.streamSource === 'TWITCH') {
streams.push(`https://twitch.tv/${stream.streamName}`);
}
}
}
const reminderEmbed = new Discord.MessageEmbed()
.setColor(sideColor)
.setTitle(tournament.name)
.setURL(`https://smash.gg/${tournament.slug}`)
.setThumbnail(imageurl[0])
.setImage(imageurl[1])
.addFields(
{
name: 'Tournament Info', value: `
${tournament.numAttendees} Attendees
*${tournamentOnline} Tournament*c
*${convertEpoch(tournament.startAt, 'America/Los_Angeles')}*`, inline: true
},
{ name: 'Events', value: events.join('\n'), inline: true },
)
.setTimestamp()
.setFooter('TournaBot', 'https://cdn.discordapp.com/attachments/719461475848028201/777094320531439636/image.png');
if (streams.length) reminderEmbed.addField('Streams', streams.join('\n'));
reminderMap.delete(id) ? console.log('Removed reminder from list.') : console.log('Could not remove reminder from list');
console.log(`Executing a reminder at ${convertEpoch(Date.now() / 1000, 'America/Los_Angeles')}`);
let DMChannel = client.users.cache.get(id.toString());
DMChannel.send('**REMINDER:** You have signed up for the following tournament, which begins in an hour:').then(() => DMChannel.send(reminderEmbed)).catch(err => console.log(err));
}
}
}
}
}
} //else console.log(`No upcoming tournaments for ${user.discordtag}`);
}
}).catch(err => console.log(err));
}
}).catch(err => console.log(err));
}
}
module.exports = remindLoop;