-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbot.js
408 lines (349 loc) · 13.2 KB
/
bot.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
const banner =`\n
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣷⣦⣄⡀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣴⣶⣾⣿⠆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⠻⢿⣷⣦⡀⠀⠀⠀
⠀⠀⠀⠀⠀⢀⣴⣿⠟⠛⠋⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⢿⣆⠀⠀
⠀⠀⠀⢀⣴⡿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣤⣤⣤⣄⡀⠹⠆⠀
⠀⠀⣰⡿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠰⢋⣵⠆⣶⣶⣶⣬⠀⠀⠀
⠀⠰⠏⠀⠀⠀⢀⣤⠴⠶⢚⠛⠛⠛⠒⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⣿⡇⠀⢹⣿⣿⡏⣧⠀⠀
⠀⠀⠀⠀⠀⢚⡉⠖⠛⢿⣿⣿⣿⣦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⣿⣷⣴⣾⣿⣿⢣⡏⠇⠀
⠀⠀⠀⢀⣴⡿⣷⣤⣀⣼⣿⣿⣿⣿⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢨⡁⢹⣿⣿⣿⣿⡿⢠⠁⠀⠀
⠀⠀⢠⡿⢋⡅⢻⣿⣿⣿⣿⣿⣿⣿⡟⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⡇⠈⢿⣿⣿⣿⠇⡺⠀⠀⠀
⠀⠀⣸⠁⠸⣇⠀⢿⣿⣿⣿⣿⣿⣿⠃⠛⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢳⡀⠈⠛⠛⠁⣰⠃⠀⠀⠀
⠀⠀⠀⠀⠀⢻⣄⠀⠙⢿⣿⡿⠟⠁⢀⣿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠳⢦⣤⣤⣁⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠙⢶⣄⠀⠀⠀⠀⢤⣾⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣬⣽⣶⠶⠟⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀
__| __|__ __|_ ) _ \__ __|
(_ | _| | _ \ ( | |
\___|___| _| ___/\___/ _|
`;
console.log(banner)
// includes and config
const fs = require('fs');
const config = require('./config.js');
const { ETwitterStreamEvent, TwitterApi } = require('twitter-api-v2');
// Bot parameters
const twitterUser = config.botname; // bot username
const fortunes = ["Bad Luck","Average Luck","Good Luck","Excellent Luck","Reply hazy, try again","Godly Luck","Very Bad Luck","Outlook good","Better not tell you now","You will meet a dark handsome stranger","キタ━━━━━━(゚∀゚)━━━━━━ !!!!","( ´,_ゝ`)","Good news will come to you by mail"];
// Twitter API
const client = new TwitterApi(config.bearer_token); // read-only? uses bearer token
// 0Auth2 Authentication
// https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Manage-Tweets/create_tweet.js
const axios = require('axios');
const crypto = require('crypto');
const OAuth = require('oauth-1.0a');
const qs = require('querystring');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const consumer_key = config.consumer_key;
const consumer_secret = config.consumer_secret;
const endpointURL = `https://api.twitter.com/2/tweets`;
// Authenticate in browse with PIN
const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write';
const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
secret: consumer_secret
},
signature_method: 'HMAC-SHA1',
hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
});
async function input(prompt) {
return new Promise(async (resolve, reject) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
async function requestToken() {
const authHeader = oauth.toHeader(oauth.authorize({
url: requestTokenURL,
method: 'POST'
}));
const req = await axios.post(requestTokenURL, {}, {
headers: {
Authorization : authHeader.Authorization
},
});
if (req) {
return qs.parse(req.data);
} else {
throw new Error('Cannot get an OAuth request token');
}
}
async function accessToken({
oauth_token,
oauth_token_secret
}, verifier) {
const authHeader = oauth.toHeader(oauth.authorize({
url: accessTokenURL,
method: 'POST'
}));
const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await axios.post(path, {},{
headers: {
Authorization : authHeader.Authorization
}
});
if (req.data) {
return qs.parse(req.data);
} else {
throw new Error('Cannot get an OAuth request token');
}
}
async function getRequest({
oauth_token,
oauth_token_secret
}, data) {
const token = {
key: oauth_token,
secret: oauth_token_secret
};
const authHeader = oauth.toHeader(oauth.authorize({
url: endpointURL,
method: 'POST'
}, token));
const req = await axios.post(endpointURL, data, {
responseType: 'json',
headers: {
Authorization : authHeader.Authorization,
'user-agent': "TWITABA Bot",
'content-type': "application/json",
'accept': "application/json"
}
});
if (req.data) {
return req.data;
} else {
//throw new Error('Unsuccessful request');
console.log("oops")
}
}
async function getRequestEndpoint({
oauth_token,
oauth_token_secret
}, data, _endpointURL) {
const token = {
key: oauth_token,
secret: oauth_token_secret
};
const authHeader = oauth.toHeader(oauth.authorize({
url: _endpointURL,
method: 'POST'
}, token));
const req = await axios.post(_endpointURL, data, {
responseType: 'json',
headers: {
Authorization : authHeader.Authorization,
'user-agent': "TWITABA Bot",
'content-type': "application/json",
'accept': "application/json"
}
});
if (req.data) {
return req.data;
} else {
throw new Error('Unsuccessful request');
}
}
async function getAuth() {
try {
// Get request token
const oAuthRequestToken = await requestToken();
// Get authorization
authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token);
console.log('Please go here and authorize:', authorizeURL.href);
const pin = await input('Paste the PIN here: ');
// Get the access token
const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
console.log("Authenticated Successfully")
return oAuthAccessToken;
} catch (e) {
console.log(e);
process.exit(-1);
}
}
// Bot functions
function randInt(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
function checkWin(postId) {
var postId = postId.toString()
var search_pattern = new RegExp(/(\d)\1+$/);
if (search_pattern.test(postId)) {
var winGet;
console.log("Winrar! " + postId)
if (search_pattern.test(postId.slice(0,-1))) { // trips
if (search_pattern.test(postId.slice(0,-2))) {
winGet = '☆ quads!' // quads
} else {
winGet = '☆ trips!'
}
} else {
winGet = "☆ dubs! check 'em ;)" // dubs
}
return winGet;
} else {
return false;
}
}
async function sendTweet(roll, username, tweetId, fortune, oAuthAccessToken) {
const botUserInfo = await client.v2.userByUsername(twitterUser.replace('@', ''));
var hasFortune = false;
if (typeof fortune === 'undefined') {
hasFortune = false;
} else {
hasFortune = true;
}
var fortuneText = `Your fortune: ${fortune}\n`
var winGet = checkWin(roll)
var replyMsg = ''
if (winGet) {
replyMsg = `@${username} ${roll}\n${winGet}`;
} else {
replyMsg = `@${username} ${roll}`;
}
if (hasFortune) {
replyMsg = fortuneText + replyMsg;
}
const data = {
"text": replyMsg,
"reply" : {"in_reply_to_tweet_id": tweetId}
}
const response = await getRequest(oAuthAccessToken, data);
let responseTweetId = response.data.id
if (winGet) {
// Retweet roll result post
let data = {
"tweet_id": responseTweetId
}
let response = await getRequestEndpoint(oAuthAccessToken, data, `https://api.twitter.com/2/users/${botUserInfo.data.id}/retweets`)
// Like tweet being replied to
data = {
"tweet_id": tweetId
}
response = await getRequestEndpoint(oAuthAccessToken, data, `https://api.twitter.com/2/users/${botUserInfo.data.id}/likes`)
}
}
// main loop
async function listener() {
const oAuthAccessToken = await getAuth();
const rules = await client.v2.streamRules();
if (rules.data?.length) {
console.log("Clearing previous Stream Rules")
await client.v2.updateStreamRules({
delete: { ids: rules.data.map(rule => rule.id) },
});
}
await client.v2.updateStreamRules({
add: [{ value: twitterUser }],
});
const stream = await client.v2.searchStream({
'tweet.fields': ['conversation_id'],
'user.fields' : ['username'],
expansions: ['referenced_tweets.id', 'author_id'],
});
// Enable auto reconnect
stream.autoReconnect = true;
var roulette_lobby;
if (fs.existsSync('lobby.json')) {
let jsonData = fs.readFileSync('lobby.json');
roulette_lobby = JSON.parse(jsonData);
console.log("Loaded previous lobbies from file");
} else {
roulette_lobby = [];
}
console.log("Listener Stream Started...")
stream.on(ETwitterStreamEvent.Data, async tweet => {
const isRetweet = tweet.data.referenced_tweets?.some(tweet => tweet.type === 'retweeted') ?? false;
var isQuoteStatus = tweet.data.is_quote_status;
if (isRetweet || isQuoteStatus) {
return;
}
//console.log(JSON.stringify(tweet,null,2)) // debug
var conversation_id = tweet.data.conversation_id;
var tweet_id = tweet.data.id;
var text = tweet.data.text;
var name = tweet.includes.users[0].username;
var userId = tweet.includes.users[0].id;
var fortune;
var hasFortune;
// give fortune on #fortune
if (text.includes("#fortune")) {
var fortuneNum = randInt(0,fortunes.length);
fortune = fortunes[fortuneNum];
hasFortune = true;
} else {
hasFortune = false;
}
if (text.includes("!roll") || text.includes("/roll")) {
var lobbyId = conversation_id.toString()
var lobbyExists = roulette_lobby.find(lobby => lobby.id === conversation_id ? true : false)
if (!lobbyExists) {
let userLobby =
{
"id": lobbyId,
"data": {
"fullGame": false,
"participants": []
}
}
roulette_lobby.push(userLobby)
console.log(`[☆ NEW LOBBY ☆ ${lobbyId}]`)
}
var lobby = roulette_lobby.filter(lobby => lobby.id === lobbyId)[0]
var lobbyParticipants = lobby.data.participants
var rollId = randInt(1000000,9999999);
var userRoll;
if (lobbyExists) {
var userExistsInLobby = lobbyParticipants.find(user => user.id === userId ? true : false)
if (userExistsInLobby) {
userRoll = lobbyParticipants.filter(user => user.id === userId)[0];
hasReroll = userRoll.rollData.hasReroll;
if (hasReroll) {
userRoll.rollData.hasReroll = false;
userRoll.rollData.reroll = rollId;
} else {
rollId = userRoll.rollData.reroll;
console.log(`User @${name} attempted to roll more than twice!`)
return false;
}
} else {
userRoll = {
"id": userId, "rollData":
{
"username": name,
"roll": rollId,
"reroll": null,
"hasReroll": true,
}
}
lobbyParticipants.push(userRoll)
}
} else {
userRoll = {
"id": userId, "rollData":
{
"username": name,
"roll": rollId,
"reroll": null,
"hasReroll": true,
}
}
lobbyParticipants.push(userRoll)
}
sendTweet(rollId, name, tweet_id,fortune,oAuthAccessToken)
fs.writeFile('lobby.json', JSON.stringify(roulette_lobby, null, 4), (err) => {
if (err) throw err;
});
console.log(`[${lobbyId}] User @${name} rolled ${rollId}: ${text}`)
} else if (hasFortune) {
}
});
}
listener();