-
Notifications
You must be signed in to change notification settings - Fork 4
/
mini.js
176 lines (160 loc) · 6.26 KB
/
mini.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
const { ApiClient } = require('@twurple/api');
const { ChatClient } = require('@twurple/chat');
const { getTokenInfo, exchangeCode } = require('@twurple/auth');
const { Client } = require('pg');
const express = require('express')
const path = require('path')
const repeat = require('./repeat');
const auth = require('./auth');
const spin = require('./minispin');
const dashboard = require('./minidashboard');
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
const bot = "mini_vanilla_bot"
const PORT = process.env.PORT || 5001
const HOST = process.env.HOST || 'http://localhost:5001'
const ssl = process.env.DATABASE_URL.startsWith('postgres://localhost')
? false
: { rejectUnauthorized: false }
const db = new Client({
connectionString: process.env.DATABASE_URL,
ssl
});
db.connect();
console.log("Database connected");
const run = async () => {
const botAuth = await auth.provider(db, bot, clientId, clientSecret);
const { rows } = await db.query('SELECT channel FROM mini_vanilla');
let channels = rows.map(row => row.channel);
const chatClient = new ChatClient({ authProvider: botAuth, channels });
const apiClient = new ApiClient({ authProvider: botAuth });
// Shutdown handlers
['SIGINT', 'SIGTERM'].forEach(signal => process.on(signal, () => {
console.log('Mini Vanilla powering down...');
for (const channel of channels) {
chatClient.say(channel, 'Mini Vanilla powering down...').catch(error => {
console.log(error);
});
}
db.end();
process.exit(0);
}));
express()
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', async (req, res) => {
res.render('pages/mini/index', {
add_params: `client_id=${clientId}&redirect_uri=${HOST}/add&response_type=code&scope=`,
remove_params: `client_id=${clientId}&redirect_uri=${HOST}/remove&response_type=code&scope=`,
})
})
.get('/add', async (req, res) => {
const code = req.query.code;
// Get an access token and use it to instantiate an ApiClient.
const token = await exchangeCode(clientId, clientSecret, code, `${HOST}/add`);
const tokenInfo = await getTokenInfo(token.accessToken, clientId);
const channel = tokenInfo.userName;
const channels = await db.query('SELECT channel FROM mini_vanilla WHERE channel = $1', [channel]);
if (channels.rows.length > 0) {
res.render('pages/mini/add', { channel, error: 'Channel already added' })
} else {
await db.query('INSERT INTO mini_vanilla (channel) VALUES ($1)', [channel]);
chatClient.join(channel).then(() => {
chatClient.say(channel, 'Mini Vanilla reporting for duty!');
});
res.render('pages/mini/add', { channel, error: null })
}
})
.get('/remove', async (req, res) => {
const code = req.query.code;
// Get an access token and use it to instantiate an ApiClient.
const token = await exchangeCode(clientId, clientSecret, code, `${HOST}/remove`);
const tokenInfo = await getTokenInfo(token.accessToken, clientId);
const channel = tokenInfo.userName;
const channels = await db.query('SELECT channel FROM mini_vanilla WHERE channel = $1', [channel]);
if (channels.rows.length > 0) {
await db.query('DELETE FROM mini_vanilla WHERE channel = $1', [channel]);
chatClient.say(channel, 'Ok byeeeeeeeeeeee');
chatClient.part(channel);
res.render('pages/mini/remove', { channel, error: null })
} else {
res.render('pages/mini/remove', { channel, error: 'Channel not joined' })
}
})
.get('/queue/:channel', async (req, res) => {
const channel = req.params.channel;
const queue = await spin.queue(channel, db);
res.render('pages/queue', { 'results': queue })
})
.get('/dashboard', async (req, res) => {
const results = await dashboard.dashboard(apiClient, db);
res.render('pages/mini/dashboard', { results: results })
})
.listen(PORT, () => console.log(`Listening on ${PORT}`))
chatClient.onMessage(async (channel, user, m, msg) => {
try {
const message = m.replace('\udb40\udc00', ''); // Remove garbage \uE0000 character.
repeat.add(chatClient, channel, user, message);
const args = message.split(' ');
const command = args.shift().toLowerCase();
if (command.startsWith('!')) {
// print message
console.log(`[${channel}] ${user}: ${message}`);
}
const mod = msg.userInfo.isMod || msg.userInfo.isBroadcaster;
switch (command) {
case '!mini':
chatClient.say(channel, HOST);
break;
case '!spin':
chatClient.say(channel, 'You can request songs by typing !request followed by the song name or spin id. You can look up songs to request on https://spinsha.re/');
break;
case '!request':
await spin.request(chatClient, channel, db, user, args);
break;
case '!done':
if (!mod) {
chatClient.say(channel, `Sorry, ${user}, only mods may perform this action`);
break;
}
await spin.done(channel, db, args.shift());
break;
case '!clear':
if (!mod) {
chatClient.say(channel, `Sorry, ${user}, only mods may perform this action`);
break;
}
await spin.clear(channel, db);
break;
case '!open':
if (!mod) {
chatClient.say(channel, `Sorry, ${user}, only mods may perform this action`);
break;
}
await spin.open(chatClient, channel, db);
break;
case '!close':
if (!mod) {
chatClient.say(channel, `Sorry, ${user}, only mods may perform this action`);
break;
}
await spin.close(chatClient, channel, db);
break;
case '!q':
case '!queue':
chatClient.say(channel, HOST + '/queue/' + channel);
break;
}
} catch (err) {
console.log(err);
}
});
await chatClient.connect();
console.log('Mini Vanilla reporting for duty!');
for (const channel of channels) {
chatClient.say(channel, 'Mini Vanilla reporting for duty!').catch(error => {
console.log(error);
});
}
};
run();