-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
596 lines (463 loc) · 17.7 KB
/
bot.py
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
import discord
import requests
import numpy.random as random
import dotenv
import os
import asyncio
import json
#===============================================================================
# Randomizing Manga
#===============================================================================
def randomMangas(difficulty):
base_url = "https://api.mangadex.org"
included_tag_names = []
excluded_tag_names = []
tags = requests.get(
f"{base_url}/manga/tag"
).json()
included_tag_ids = [
tag["id"]
for tag in tags["data"]
if tag["attributes"]["name"]["en"]
in included_tag_names
]
excluded_tag_ids = [
tag["id"]
for tag in tags["data"]
if tag["attributes"]["name"]["en"]
in excluded_tag_names
]
order = {"rating": "desc", "followedCount": "desc"}
# order = {'followedCount': "desc"}
final_order_query = dict()
# { "order[rating]": "desc", "order[followedCount]": "desc" }
for key, value in order.items():
final_order_query[f"order[{key}]"] = value
mangaTitles = []
while len(mangaTitles) < 4:
startOffset = (difficulty-1)*250
endOffset = difficulty*250
offset = random.randint(startOffset, endOffset)
r = requests.get(
f"{base_url}/manga",
params={
**{
"limit": 1,
"offset": offset,
"includedTags[]": included_tag_ids,
"excludedTags[]": excluded_tag_ids,
"originalLanguage[]": ["ja"],
},
**final_order_query,
},
)
data = r.json()['data']
manga = data[0]
if 'en' in manga['attributes']['title']:
mangaTitle = manga['attributes']['title']['en']
elif 'ja' in manga['attributes']['title']:
mangaTitle = manga['attributes']['title']['ja']
elif 'ko' in manga['attributes']['title']:
mangaTitle = manga['attributes']['title']['ko']
else:
print('No valid title, retrying...')
return (None, None)
if mangaTitle in mangaTitles:
continue
else:
mangaTitles.append(mangaTitle)
if len(mangaTitles) == 1:
manga_id = manga['id']
return manga_id, mangaTitles
def randomMangaWithMAL(malUsers):
with open('data.json') as f:
data = json.load(f)
mdexLst = []
for username in malUsers:
mdexLst.extend(data['mal'][username])
mdexLstIdxes = random.choice(len(mdexLst), 4, replace=False)
mangaTitles = []
for i in range(4):
manga_id, mangaTitle = mdexLst[mdexLstIdxes[i]]
mangaTitles.append(mangaTitle)
if i == 0:
correct_manga_id = manga_id
f.close()
return correct_manga_id, mangaTitles
def randomPages(manga_id):
fullURLs = []
while len(fullURLs) < 3:
base_url = "https://api.mangadex.org"
r = requests.get(
f"{base_url}/manga/{manga_id}/feed",
params={"translatedLanguage[]": ["en"]},
)
chapter_ids = [chapter["id"] for chapter in r.json()["data"]]
if len(chapter_ids) == 0:
print('No valid chapters, retrying...')
return None
chapter_id = random.choice(chapter_ids)
r = requests.get(f"{base_url}/at-home/server/{chapter_id}")
r_json = r.json()
if "baseUrl" not in r_json:
print('baseUrl not in r_json, retrying...')
return None
host = r_json["baseUrl"]
chapter_hash = r_json["chapter"]["hash"]
data = r_json["chapter"]["data"]
# data_saver = r_json["chapter"]["dataSaver"]
if len(data) <= 1:
print('Chapter has 0 pages, retrying...')
return None
randomPageIdx = random.randint(0, len(data)-1)
fullURL = f'{host}/data/{chapter_hash}/{data[randomPageIdx]}'
fullURLs.append(fullURL)
return fullURLs
def randomImg(difficulty, malUsers):
if malUsers != []:
manga_id, mangaTitles = randomMangaWithMAL(malUsers)
fullURLs = randomPages(manga_id)
while fullURLs == None:
manga_id, mangaTitles = randomMangaWithMAL(malUsers)
fullURLs = randomPages(manga_id)
return fullURLs, mangaTitles
else:
manga_id, mangaTitles = randomMangas(difficulty)
while manga_id == None:
manga_id, mangaTitles = randomMangas(difficulty)
fullURLs = randomPages(manga_id)
while fullURLs == None:
manga_id, mangaTitles = randomMangas(difficulty)
fullURLs = randomPages(manga_id)
return fullURLs, mangaTitles
#===============================================================================
# Starting up bot
#===============================================================================
bot = discord.Bot()
@bot.event
async def on_ready():
setAllRoundsOutOfProgress()
print(f'We have logged in as {bot.user}')
#===============================================================================
# Embeds/Buttons
#===============================================================================
# returns difficulty name given difficulty
def difficultyName(difficulty):
if difficulty == 1:
return 'Easy'
elif difficulty == 2:
return 'Normal'
elif difficulty == 3:
return 'Hard'
elif difficulty == 4:
return 'Harder'
elif difficulty == 5:
return 'Insane'
async def startEmbed(ctx, difficulty, malUsers):
startEmbed = discord.Embed(
title="Starting round in 3 seconds...",
color=discord.Colour.yellow(),
)
difficultyLevel = difficultyName(difficulty)
if malUsers == []:
value = f'Difficulty: **{difficultyLevel}**'
else:
value = f'From **{",".join(malUsers)}** MyAnimeList list(s)'
startEmbed.add_field(name='Settings', value=value)
await ctx.respond(embed=startEmbed)
async def panelEmbed(ctx, fullURL, mangaTitle):
panelEmbed = discord.Embed(
title="Random Manga Panel",
description="Guess the correct manga!",
color=discord.Colour.greyple(),
)
panelEmbed.set_image(url=fullURL)
await asyncio.sleep(3)
# panelEmbed.set_footer(text=mangaTitle) # putting correct manga as embed footer
await ctx.respond(embed=panelEmbed)
async def buttons(ctx, mangaTitles):
correctManga = mangaTitles[0]
random.shuffle(mangaTitles)
lostPlayers = set()
isWinner = []
# initializing button class
class MyView(discord.ui.View):
async def changeButtonColors(self, state, interaction=None):
for child in self.children:
child.disabled = True
if child.label != correctManga:
child.style = discord.ButtonStyle.secondary
elif state == 'win':
child.style = discord.ButtonStyle.success
elif state == 'loss':
child.style = discord.ButtonStyle.danger
if state == 'win':
setRoundOutOfProgress(ctx)
await self.roundWin(interaction)
elif state == 'loss':
setRoundOutOfProgress(ctx)
await ctx.respond(f'No one got the correct answer! The correct answer was **{correctManga}**.')
await self.message.edit(view=self)
async def roundWin(self, interaction):
if isWinner != []:
await interaction.response.defer()
else:
isWinner.append(interaction.user)
updateScore(interaction)
username = str(interaction.user)[:-2]
await ctx.respond(f'**{username}** has won!')
async def buttonPressResponse(self, button, interaction):
# correct choice -- round ends
if button.label == correctManga:
await self.changeButtonColors('win', interaction)
# incorrect choice
else:
lostPlayers.add(interaction.user)
await interaction.response.send_message("Sorry, that is the wrong answer!", ephemeral=True)
async def on_timeout(self):
if isWinner != []:
return
await self.changeButtonColors('loss')
async def repeatedButtonPress(self, interaction):
try:
await interaction.response.defer()
except discord.errors.InteractionResponded:
pass
async def buttonInteraction(self, button, interaction):
if interaction.user in lostPlayers or isWinner != []:
await self.repeatedButtonPress(interaction)
else:
await self.buttonPressResponse(button, interaction)
await self.repeatedButtonPress(interaction)
@discord.ui.button(label=mangaTitles[0], row=0, style=discord.ButtonStyle.primary)
async def first_button_callback(self, button, interaction):
await self.buttonInteraction(button, interaction)
@discord.ui.button(label=mangaTitles[1], row=1, style=discord.ButtonStyle.primary)
async def second_button_callback(self, button, interaction):
await self.buttonInteraction(button, interaction)
@discord.ui.button(label=mangaTitles[2], row=2, style=discord.ButtonStyle.primary)
async def third_button_callback(self, button, interaction):
await self.buttonInteraction(button, interaction)
@discord.ui.button(label=mangaTitles[3], row=3, style=discord.ButtonStyle.primary)
async def fourth_button_callback(self, button, interaction):
await self.buttonInteraction(button, interaction)
await ctx.send(view=MyView(timeout=10))
#===============================================================================
# Updating playing guilds / leaderboard
#===============================================================================
def isRoundInProgress(ctx):
with open('data.json') as f:
data = json.load(f)
isRoundInProgress = ctx.guild.id in data["playingGuilds"]
f.close()
return isRoundInProgress
def setRoundInProgress(ctx):
with open('data.json') as f:
data = json.load(f)
data["playingGuilds"].append(ctx.guild.id)
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
f.close()
def setRoundOutOfProgress(ctx):
with open('data.json') as f:
data = json.load(f)
if ctx.guild.id in data["playingGuilds"]:
data["playingGuilds"].remove(ctx.guild.id)
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
f.close()
def setAllRoundsOutOfProgress():
with open('data.json') as f:
data = json.load(f)
data["playingGuilds"] = []
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
f.close()
def updateScore(interaction):
with open('data.json') as f:
data = json.load(f)
user = str(interaction.user)
if user not in data["score"]:
data["score"][user] = 1
else:
data["score"][user] += 1
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
f.close()
#===============================================================================
# Bot commands
#===============================================================================
def checkForValidMALs(myAnimeLists):
with open('data.json') as f:
data = json.load(f)
malLists = myAnimeLists.split(',')
for i in range(len(malLists)):
username = (malLists[i].strip()).lower()
if username not in data['mal']:
f.close()
return ('No user', username)
mdexLst = data['mal'][username]
if len(mdexLst) < 4:
f.close()
return ('Not enough manga', username)
malLists[i] = username
f.close()
return malLists
# parsing manga titles that are > 80 characters
def shortenTitles(mangaTitles):
for i in range(len(mangaTitles)):
mangaTitle = mangaTitles[i]
if len(mangaTitle) > 80:
mangaTitles[i] = mangaTitle[:77] + '...'
return mangaTitles
@bot.command(description='Play a manga guessing game.')
@discord.option(
"difficulty",
description="Enter the difficulty",
default=1,
min_value=1,
max_value=5)
@discord.option(
"mal",
description="MyAnimeList usernames (seperated by commas)",
default="",
)
async def pg(ctx, difficulty : int, mal : str):
if isRoundInProgress(ctx):
await ctx.respond('A round is already in progress!')
return
setRoundInProgress(ctx)
malUsers = []
if mal != "":
malUsers = checkForValidMALs(mal)
if isinstance(malUsers, tuple):
error, username = malUsers
if error == 'No user':
await ctx.respond(f"{username}'s list on MyAnimeList has not been synced yet. Use the `sync` command to syncronize the list.")
setRoundOutOfProgress(ctx)
return
elif error == 'Not enough manga':
await ctx.respond(f"{username}'s list does not have enough manga!")
setRoundOutOfProgress(ctx)
return
try:
await startEmbed(ctx, difficulty, malUsers)
fullURLs, mangaTitles = randomImg(difficulty, malUsers)
mangaTitles = shortenTitles(mangaTitles)
correctManga = mangaTitles[0]
fullURL = fullURLs[0]
await panelEmbed(ctx, fullURL, correctManga)
await buttons(ctx, mangaTitles)
except:
setRoundOutOfProgress(ctx)
print('Error occurred, please try again.')
@bot.command(description="Forcefully stops the current round. Only use if bot is softlocked.")
async def forcestop(ctx):
setRoundOutOfProgress(ctx)
await ctx.respond(f'Current round has forcefully been stopped.')
@bot.command(description="Sends user's current score.")
async def score(ctx):
with open('data.json') as f:
data = json.load(f)
user = str(ctx.user)
if user not in data["score"]:
f.close()
await ctx.respond(f"{user[:-2]} has gotten 0 manga correct!")
else:
score = data["score"][user]
f.close()
await ctx.respond(f"{user[:-2]} has gotten {score} manga correct!")
@bot.command(description="Sends the bot's latency.")
async def ping(ctx):
await ctx.respond(f"Pong! Latency is {bot.latency}")
@bot.command(description="Sends top players.")
async def top(ctx):
leaderboardEmbed = discord.Embed(
title="Top Players",
color=discord.Colour.blurple(),
)
with open('data.json') as f:
data = json.load(f)
leaderboardList = []
for user in data["score"]:
score = data["score"][user]
leaderboardList.append((score, user))
leaderboardList.sort(reverse = True)
leaderboard = ""
for i in range(10):
if i < len(leaderboardList):
score, user = leaderboardList[i]
leaderboard += f"\n`{i+1}` {user[:-2]} `{score}`"
else:
leaderboard += f"\n`{i+1}` N/A `0`"
f.close()
leaderboardEmbed.add_field(name='Players', value=leaderboard)
await ctx.respond(embed=leaderboardEmbed)
def myAnimeListRequest(mangaTitles, username, status):
url = f'https://api.myanimelist.net/v2/users/{username}/mangalist?offset=0&limit=1000&status={status}'
r = requests.get(url, headers = {'X-MAL-CLIENT-ID': CLIENT_ID})
if 'data' not in r.json():
return None
mangaList = r.json()['data']
if 'error' in mangaList:
return None
for manga in mangaList:
mangaTitle = manga['node']['title']
mangaTitles.append(mangaTitle)
return mangaTitles
@bot.command(description='Sync MyAnimeList manga list.')
async def sync(ctx, username : str):
await ctx.respond('The bot will DM you when sync is complete!')
mangaTitles=[]
mangaTitles = myAnimeListRequest(mangaTitles, username, 'reading')
if mangaTitles == None:
await ctx.respond(f'{username} is not a valid username on MyAnimeList.')
return
mangaTitles = myAnimeListRequest(mangaTitles, username, 'completed')
if mangaTitles == None:
await ctx.respond(f'{username} is not a valid username on MyAnimeList.')
return
base_url = "https://api.mangadex.org"
final_order_query = {'order[relevance]': 'desc'}
mdexLst = []
for i in range(len(mangaTitles)):
mangaTitle = mangaTitles[i]
r = requests.get(
f"{base_url}/manga",
params={
**{
"limit": 1,
"title": mangaTitle,
},
**final_order_query,
},
)
data = r.json()["data"]
if data == []:
continue
manga = data[0]
if manga['attributes']['originalLanguage'] != 'ja':
continue
manga_id = manga['id']
if 'en' in manga['attributes']['title']:
mangaTitle = manga['attributes']['title']['en']
elif 'ja' in manga['attributes']['title']:
mangaTitle = manga['attributes']['title']['ja']
elif 'ko' in manga['attributes']['title']:
mangaTitle = manga['attributes']['title']['ko']
else:
continue
mdexLst.append((manga_id, mangaTitle))
with open('data.json') as f:
data = json.load(f)
data['mal'][username.lower()] = mdexLst
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
f.close()
user = ctx.author
await user.send(f'Syncing is complete! You can now use `mal:{username}` as a parameter.')
# Tokens
dotenv.load_dotenv()
CLIENT_ID = str(os.getenv("CLIENT_ID"))
token = str(os.getenv("TOKEN"))
bot.run(token)