-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
372 lines (326 loc) Β· 10.5 KB
/
index.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
require("dotenv").config();
const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const WebSocket = require("ws");
const fetch = require("node-fetch");
let ws;
let sessionId;
const broadcasterID = "510641053";
const io = new Server(server);
const closeCodes = {
4000: "Internal Server Error",
4001: "Client sent inbound traffic",
4002: "Client failed ping-pong",
4003: "Connection unused",
4004: "Reconnect grace time expired",
4005: "Network Timeout",
4006: "Network error",
4007: "Invalid Reconnect",
};
const customRewardsToCreate = [
{
title: "π Invade (1px) π",
cost: 10,
},
{
title: "π Invade (10px) π",
cost: 100,
},
{
title: "π Invade (100px) π",
cost: 1000,
},
];
//channel:read:hype_train
//channel:manage:redemptions
// https://github.com/BarryCarlyon/twitch_misc/tree/main/channel_points
const client_config = JSON.parse(
fs.readFileSync(path.join(__dirname, "jsons", "config_client.json"))
);
const account_config = JSON.parse(
fs.readFileSync(path.join(__dirname, "jsons", "config_user.json"))
);
let rewardsConfig = JSON.parse(
fs.readFileSync(path.join(__dirname, "jsons", "config_rewards.json"))
);
async function entry() {
// If not token, first auth with the URL /auth
if (!account_config.access_token) {
console.error("First go on localhost:3000/auth to authorize the app");
return false;
}
// See if the access_token is still valid
console.info("Check validity of access_token");
let resp = await fetch("https://id.twitch.tv/oauth2/validate", {
method: "GET",
headers: {
Authorization: `Bearer ${account_config.access_token}`,
Accept: "application/json",
},
});
// If access_token isn't valid anymore, regenerate it
if (resp.status != 200) {
console.info("access_token not valid, regenerate it");
regenerate();
return;
}
return true;
}
async function regenerate() {
let url = new URL("https://id.twitch.tv/oauth2/token");
url.search = new URLSearchParams([
["grant_type", "refresh_token"],
["client_id", client_config.client_id],
["client_secret", client_config.client_secret],
["refresh_token", client_config.refresh_token],
]).toString();
let resp = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "x-www-form-urlencoded",
},
});
if (resp.status != 200) {
console.error("Error", resp.status, await resp.text());
return;
}
let body = await resp.json();
for (var k in body) {
account_config[k] = body[k];
}
fs.writeFileSync(
path.join(__dirname, "jsons", "config_user.json"),
JSON.stringify(account_config, null, 4)
);
}
const twitchFetchHeaders = {
Authorization: `Bearer ${account_config.access_token}`,
"Client-ID": client_config.client_id,
"Content-Type": "application/json",
};
async function subscriptionSub(type) {
return await fetch(
"https://api.twitch.tv/helix/eventsub/subscriptions",
{
method: "POST",
headers: twitchFetchHeaders,
body: JSON.stringify({
type: type,
version: "1",
condition: {
broadcaster_user_id: broadcasterID,
},
transport: {
method: "websocket",
session_id: sessionId,
},
}),
}
);
}
async function customRewardsSub(id, cost) {
return await fetch(
`https://api.twitch.tv/helix/channel_points/custom_rewards?broadcaster_id=${broadcasterID}&id=${id}`,
{
method: "PATCH",
body: JSON.stringify({
cost: cost / 2,
}),
headers: twitchFetchHeaders,
}
);
}
async function connect() {
if (!(await entry())) return;
// ws = new WebSocket("ws://localhost:8080/ws");
ws = new WebSocket("wss://eventsub.wss.twitch.tv/ws");
ws.on("open", () => {
console.log(`Opened Connection to Twitch`);
});
ws.on("error", (error) => {
console.error("ERR: " + JSON.stringify(error) + "\n");
});
ws.on("message", async (event) => {
const eventData = JSON.parse(event.toString());
let { metadata, payload } = eventData;
let { message_type } = metadata;
console.log(message_type);
switch (message_type) {
/* WELCOME MESSAGE */
case "session_welcome":
sessionId = payload.session.id;
// Subscription to Channel Point Redeem Event
const subChannelPointGetterRes = await subscriptionSub("channel.channel_points_custom_reward_redemption.add");
const subChannelPointGetterData = await subChannelPointGetterRes.json();
// Subscription to Sub Event
const subChannelSubRes = await subscriptionSub("channel.subscribe");
const subChannelSubData = await subChannelSubRes.json();
// Subscription to Sub Event
const subBitsSubRes = await subscriptionSub("channel.cheer");
const subBitsSubData = await subBitsSubRes.json();
// Subscription to beginning Hype Train Event
const subBeginHypeTrainRes = await subscriptionSub("channel.hype_train.begin");
const subBeginHypeTrainData = await subBeginHypeTrainRes.json();
// Subscription to ending Hype Train Event
const subEndHypeTrainRes = await subscriptionSub("channel.hype_train.end");
const subEndHypeTrainData = await subEndHypeTrainRes.json();
break;
case "session_keepalive":
console.log(`Recv KeepAlive - ${message_type}`);
// this.emit("session_keepalive");
break;
case "notification":
let { subscription, event } = payload;
let { type } = subscription;
console.log(type);
switch (type) {
case "channel.channel_points_custom_reward_redemption.add":
if (event.reward.title === "π Invade (1px) π") {
// Emit with Socket IO to client side
io.emit("channel-point", 1);
}
if (event.reward.title === "π Invade (10px) π") {
// Emit with Socket IO to client side
io.emit("channel-point", 10);
}
if (event.reward.title === "π Invade (100px) π") {
// Emit with Socket IO to client side
io.emit("channel-point", 100);
}
break;
case "channel.subscribe":
if (event.tier === "1000") io.emit("sub", 10);
else if (event.tier === "2000") io.emit("sub", 30);
else if (event.tier === "3000") io.emit("sub", 90);
break;
case "channel.cheer":
// return the greater integer
io.emit("cheer", Math.ceil(event.bits / 10));
break;
case "channel.hype_train.begin":
rewardsConfig.forEach(async ({ id, cost }) => {
const editReward = await customRewardsSub(id, cost / 4);
console.log(await editReward.json());
});
break;
case "channel.hype_train.end":
rewardsConfig.forEach(async ({ id, cost }) => {
const editReward = await customRewardsSub(id, cost);
console.log(await editReward.json());
});
break;
}
break;
}
});
ws.on("close", (close) => {
console.log("EventSub close", close);
console.log(`Connection Closed: ${close} Reason - ${closeCodes[close]}`);
});
}
connect();
/* SOCKETIO */
io.on("connection", (socket) => {
// console.log("a user connected");
});
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/index.html"));
});
app.get("/auth", function (req, res) {
// res.sendFile(path.join(__dirname, "/auth.html"));
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DevGirl_'s Malware - Auth</title>
</head>
<body>
<a href="
https://id.twitch.tv/oauth2/authorize?response_type=code&client_id=${client_config.client_id}&redirect_uri=http://localhost:3000/auth/redirect&scope=channel%3Aread%3Aredemptions+channel%3Amanage%3Aredemptions+channel%3Aread%3Ahype_train+channel%3Aread%3Asubscriptions
">Twitch Auth</a>
</body>
</html>
`);
});
app.get("/auth/redirect", async function (req, res) {
let url = new URL("https://id.twitch.tv/oauth2/token");
url.search = new URLSearchParams([
["grant_type", "authorization_code"],
["client_id", client_config.client_id],
["client_secret", client_config.client_secret],
["redirect_uri", "http://localhost:3000/auth/redirect"],
["code", req.query.code],
["scope", req.query.scope],
]).toString();
let resp = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "x-www-form-urlencoded",
},
});
if (resp.status != 200) {
console.error("Error", resp.status, await resp.text());
return;
}
let body = await resp.json();
// Get the ids
for (var k in body) {
account_config[k] = body[k];
}
// Write the ids in config file
fs.writeFileSync(
path.join(__dirname, "jsons", "config_user.json"),
JSON.stringify(account_config, null, 4)
);
res.send("");
// Create the custom rewards
rewardsConfig = [];
await Promise.all(
customRewardsToCreate.map(async (reward) => {
const create = await fetch(
`https://api.twitch.tv/helix/channel_points/custom_rewards?broadcaster_id=${broadcasterID}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${account_config.access_token}`,
"Client-ID": client_config.client_id,
"Content-Type": "application/json",
},
body: JSON.stringify(reward),
}
);
// Fetch error
if (create.status != 200) {
console.error("Error", create.status, await create.text());
return;
}
const rewardsData = await create.json();
// Twitch error
if (!rewardsData.data) {
console.error("Error", rewardsData.status, await rewardsData.message);
return;
}
rewardsConfig.push(rewardsData.data[0]);
})
);
console.log(rewardsConfig);
// Write the ids in config file
fs.writeFileSync(
path.join(__dirname, "jsons", "config_rewards.json"),
JSON.stringify(rewardsConfig, null, 4)
);
});
app.use(express.static("public"));
server.listen(3000, () => {
console.log("listening on *:3000");
});