-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitch.js
377 lines (350 loc) · 13.8 KB
/
twitch.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
const tmi = require('tmi.js');
const Discord = require('discord.js')
const client2 = new Discord.Client()
const Sequelize = require('sequelize');
const { GoogleSpreadsheet } = require('google-spreadsheet');
const creds = require('./creds.json');
const doc = new GoogleSpreadsheet('1Hex1F3awJ1A99-kcqy62twZ-WFd__q9uUUjDlVi57Ro');
const sequelize = new Sequelize('database', 'user', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: 'database.sqlite',
});
const twitch_names = sequelize.define('twitch', {
twitchName: {
type: Sequelize.STRING,
unique: true,
},
discordName: Sequelize.STRING,
});
const views = sequelize.define('views', {
twitchName: Sequelize.STRING,
channel: Sequelize.STRING,
startTime: Sequelize.DATE,
chats: Sequelize.INTEGER
});
// Define configuration options
const opts = {
identity: {
username: "SBD_Bartender",
password: "OAuth_Password_Here"
},
connection: {
reconnect: true
},
channels: [
"HunBurry",
"jackedupjonesy",
'liiguardlii',
'clerkgames',
'inline_1',
'theocratical',
'BestNinjaNW',
'Acemo74',
'kinggummylive',
'jbmatty25',
'futureishere',
'unciad',
'ghostscout_ben',
'Verumiii',
'Mwmissile',
'cptncr3d1ble',
'Sp1der05',
'wokeology',
'blackbuc911',
'marcolepsy120',
'CrankyGuardian',
'pooopsy',
'lipidquadcab',
'huttyj',
'Ninjarabi1',
'saintlxix',
'KineticRandy',
'Lazychronic',
'Dirtyhyperion',
'Evi1_Abed',
'pennington56',
'Map_bot',
'mwmissile',
'blitzred1',
'casual_blue',
'drmac1',
'exi_gent',
'kotogotoku',
'alaskalostcauze',
'm9aviator1',
'riotkittens',
'Sunnyontherocks',
'thunderapollyon',
'the_11_atheists',
'w0rmyy'
]
};
const client = new tmi.client(opts);
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
client.on("join", onJoin);
client.on("part", onPart);
async function onJoin(channel, username, self) {
target = channel;
const view = await views.findOne({
where: {
twitchName: username,
channel: target
}
})
if (view) {
return;
}
else {
const newView = await views.create({
twitchName: username,
channel: target,
startTime: new Date(),
chats: 0
});
console.log(username + " has joined " + channel + ".");
console.log("Channel initilized.")
}
}
async function onPart(channel, username, self) {
target = channel;
const userIsReg = await twitch_names.findOne({
where: {
twitchName: username
}
});
const view = await views.findOne({
where: {
twitchName: username,
channel: target
}
})
if (userIsReg) {
if (view) {
console.log("Successfully located " + username + "'s entry into " + target + ".")
let current = new Date();
let diff = (current.getTime() - view['startTime'].getTime()) / 1000
diff /= 60;
num = Math.abs(Math.round(diff));
chats = view['chats'];
bottlecaps_earned = (Math.floor(num/10) * .25) + (.05 * chats)
console.log("By watching for " + diff + " minutes, and chatting " + chats + " times, " + username + " earned " + bottlecaps_earned + " bottlecaps.");
///client.say(target, "By watching for " + diff + " minutes, and chatting " + chats + " times, " + username + " earned " + bottlecaps_earned + " bottlecaps.")
await doc.useServiceAccountAuth(creds);
await doc.loadInfo();
const sheet = doc.sheetsByIndex[1];
const rows = await sheet.getRows({offset: 0, limit: 650});
await sheet.loadCells('A1:S660');
disName = userIsReg['discordName'];
for (let i = 0; i < rows.length; i++) {
name = await sheet.getCellByA1("A" + rows[i].rowNumber).value;
if (name.toLowerCase() == disName.toLowerCase()) {
console.log('Located ' + username + ' on spreadsheet...')
const points = await sheet.getCellByA1("P" + rows[i].rowNumber)
val = points.value;
const wagers = await sheet.getCellByA1("Q" + rows[i].rowNumber)
hold = await sheet.getCellByA1("S" + rows[i].rowNumber)
hold.value = parseFloat(hold.value) + bottlecaps_earned;
await sheet.saveUpdatedCells();
///client.say(target, "Points have been updated for " + username + ". They had " + val + " and now have " + (parseFloat(val) + bottlecaps_earned).toFixed(2).toString() + ".");
console.log("Updated " + username + "'s points successfully.")
console.log("--------------------------------------------------------")
await view.destroy();
return;
}
}
///client.say(target, "Unable to locate " + username + " on spreadsheet. Please ensure your registration is correct, or contact a Bartender.")
console.log("Unable to locate " + username + " on spreadsheet in onPart.")
console.log("--------------------------------------------------------")
}
else {
///client.say(target, "Could not locate log of user logging into this channel.")
console.log("Could not locate log of " + username + " logging into this channel in onPart.")
}
}
else {
///client.say(target, "Could not locate user's registration. Please ensure you've used the -register command.")
console.log("Could not locate registration for " + username + " in onPart.")
}
}
// Called every time a message comes in
async function onMessageHandler (target, context, msg, self) {
if (self) {
return; // Ignore messages from the bot
}
commandName = msg.trim();
commandName = commandName.split(" ")[0]
username = context['username']
if (commandName === '-register') {
await register(target, context, msg, self);
}
else if (commandName === '-bottlecaps') {
await ePoints(target, context, msg, self);
}
else if (commandName === '-join') {
const view = await views.create({
twitchName: username,
channel: target,
startTime: new Date(),
chats: 0
});
client.say(target, "View times and comments are now being tracked for " + username + " in this channel.");
console.log("View object created for " + username + " in " + target + ".")
}
else if (commandName === '-leave') {
const userIsReg = await twitch_names.findOne({
where: {
twitchName: username
}
});
const view = await views.findOne({
where: {
twitchName: username,
channel: target
}
})
if (userIsReg) {
if (view) {
console.log("Successfully located " + username + "'s entry into " + target + ".")
let current = new Date();
let diff = (current.getTime() - view['startTime'].getTime()) / 1000
diff /= 60;
num = Math.abs(Math.round(diff));
chats = view['chats'];
bottlecaps_earned = (Math.floor(num/10) * .25) + (.05 * chats)
console.log("By watching for " + diff + " minutes, and chatting " + chats + " times, " + username + " earned " + bottlecaps_earned + " bottlecaps.");
client.say(target, "By watching for " + diff + " minutes, and chatting " + chats + " times, " + username + " earned " + bottlecaps_earned + " bottlecaps.")
await doc.useServiceAccountAuth(creds);
await doc.loadInfo();
const sheet = doc.sheetsByIndex[1];
const rows = await sheet.getRows({offset: 0, limit: 650});
await sheet.loadCells('A1:S660');
disName = userIsReg['discordName'];
for (let i = 0; i < rows.length; i++) {
name = await sheet.getCellByA1("A" + rows[i].rowNumber).value;
if (name.toLowerCase() == disName.toLowerCase()) {
console.log('Located ' + username + ' on spreadsheet...')
const points = await sheet.getCellByA1("P" + rows[i].rowNumber)
val = points.value;
const wagers = await sheet.getCellByA1("Q" + rows[i].rowNumber)
hold = await sheet.getCellByA1("S" + rows[i].rowNumber)
hold.value = parseFloat(hold.value) + bottlecaps_earned;
await sheet.saveUpdatedCells();
client.say(target, "Points have been updated for " + username + ". They had " + val + " and now have " + (parseFloat(val) + bottlecaps_earned).toFixed(2).toString() + ".");
console.log("Updated " + username + "'s points successfully.")
console.log("--------------------------------------------------------")
await view.destroy();
return;
}
}
client.say(target, "Unable to locate " + username + " on spreadsheet. Please ensure your registration is correct, or contact a Bartender.")
console.log("Unable to locate " + username + " on spreadsheet.")
console.log("--------------------------------------------------------")
}
else {
client.say(target, "Could not locate log of user logging into this channel.")
console.log("Could not locate log of " + username + " logging into this channel.")
}
}
else {
client.say(target, "Could not locate user's registration. Please ensure you've used the -register command.")
console.log("Could not locate registration for " + username + ".")
}
}
else {
const view = await views.findOne({
where: {
twitchName: username,
channel: target
}
})
if (view) {
view.chats = view.chats + 1;
await view.save();
console.log("Chat updated for " + username + ".")
}
else {
const newView = await views.create({
twitchName: username,
channel: target,
startTime: new Date(),
chats: 1
});
console.log("View object created via chat for " + username + ".")
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
async function register(target, context, msg, self) {
holdN = '';
totalMessage = msg.split(" ")
if (totalMessage.length > 1) {
for (let i = 1; i < totalMessage.length; i++) {
holdN = holdN + totalMessage[i] + " "
}
holdN = holdN.trim();
}
try {
const tag = await twitch_names.create({
twitchName: context['username'],
discordName: holdN
});
client.say(target, context['username'] + ", you have been registered as " + holdN + ".");
}
catch (e) {
if (e.name == 'SequelizeUniqueConstraintError') {
const upd = twitch_names.update({
discordName: holdN
}, {
where: {
twitchName: context['username']
}
})
client.say(target, context['username'] + ", you have been re-registered as " + holdN + ".");
}
else {
console.log(e)
return client.say(target, 'Something went wrong with registering. Contact HunBurry.');
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
async function ePoints(target, context, msg, self) {
disName = ''
const user = await twitch_names.findOne({
where: {
twitchName: context['username']
}
});
disName = user['discordName']
///sent = message.channel.send("Loading data... Please wait.")
doc.useApiKey('API_KEY_HERE');
await doc.loadInfo();
const sheet = doc.sheetsByIndex[1];
const rows = await sheet.getRows({offset: 0, limit: 450});
await sheet.loadCells('A1:S460');
didLoad = false;
for (let i = 0; i < rows.length; i++) {
name = sheet.getCellByA1("A" + rows[i].rowNumber).value;
if (name != null && (name.toLowerCase() == disName.toLowerCase())) {
points = sheet.getCellByA1("P" + rows[i].rowNumber).value;
wagered = sheet.getCellByA1("Q" + rows[i].rowNumber).value;
client.say(target, disName + ", you have earned " + points + " bottlecaps this season, and wagered " +
wagered + ". You have " + (parseFloat(points) - parseInt(wagered)).toString() + " bottlecaps remaining.")
didLoad = true;
break;
}
}
if (!didLoad) {
client.say(target, "Sorry " + disName + ", but I couldn't find your event points! Check the spreadsheet manually, and contact HunBurry if you see them on there but this command didn't work.")
}
}
function onConnectedHandler(addr, port) {
twitch_names.sync();
views.sync();
console.log(`* Connected to ${addr}:${port}`);
}
// Connect to Twitch:
client.connect();