-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBot.py
More file actions
824 lines (754 loc) · 35.8 KB
/
Bot.py
File metadata and controls
824 lines (754 loc) · 35.8 KB
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
#!/usr/bin/python3.6
import threading
from datetime import datetime, date
from threading import Thread
from random import randrange
import asyncio
import requests
import pymysql
from youtube_dl import YoutubeDL
from cleverbot import Cleverbot
import discord
from RiotAPI import RiotAPI
from YoutubeAPI import YoutubeAPI
import overwatch_api
from discord.client import ConnectionState
import schedule
import asynchttpserver
from voice_entry import VoiceEntry
class Bot(discord.Client):
"""
Bot object that inherits from the Client object of discord.py
Mostly designed for League of Legends.
"""
def __init__(self, name="Botwyniel", wl=[], **kwargs):
super().__init__()
self.otherloop = None
self.voice = []
self.player = None
self.ydl = YoutubeDL({"socket_timeout": 5})
self.init_time = datetime.now()
self.servs = {}
self.servers_by_id = {}
self.channels = {}
self.aliases = {}
self.yt = YoutubeAPI()
self.songs = asyncio.Queue()
self.play_next_song = asyncio.Event()
self.name = name
self.whitelist = wl
self.cleverbot = Cleverbot("botwyniel")
self.steam_key = "7079BC4D125AF8E3C3D362F8A98235CC"
with open(".keys") as f:
self.riot_key = f.readlines()[3][:-1]
print(self.riot_key)
self.regions = ["BR", "EUNE", "EUW", "KR", "LAN", "LAS", "NA", "OCE", "TR", "RU", "JP", "PBE"]
self.commands = {"0!rank": self.rank,
"0!gameranks": self.gameranks,
"0!uptime": self.send_uptime,
"0!status": self.status,
"0!send": self.send,
"0!fc": self.free_champs,
"0!py": self.execute,
"0!help": self.help,
"0!ytlatest": self.latest_videos,
"0!ytsearch": self.search_video,
"0!ytthumbnail": self.get_thumbnail,
"0!avatar": self.avatar,
"0!sendpm": self.sendpm,
"0!love": self.love,
"0!8ball": self.eightball,
"0!dice": self.dice,
"0!coin": self.coin,
"0!suggest": self.suggest,
"0!play": self.queue_song,
"0!pause": self.pause,
"0!ytplay": None,
"0!setalias": self.set_alias,
"0!removealias": self.remove_alias,
"0!about": self.about,
"0!joinvoice": self.join_voice,
"0!resume": self.resume,
"0!leavevoice": self.leave_voice,
"0!skip": self.skip_song,
"0!queue": self.list_queue,
"0!owrank": self.ow_rank,
"0!schedule": self.schedule,
"0!music": self.send_music_url
}
self.commands_help = {"0!music": "Control Botwyniel from your browser!",
"0!rank": "Returns the rank of the specified player. If your Discord username is the "
"same as your summoner name, or if you have set an alias using 0!setalias, you can use 0!rank me, *region* or 0!rank instead.\n"
"Syntax: `0!rank username (, region)` -- region is optional if the player you are looking is on EUW",
"0!gameranks": "Returns the ranks of the players in the game the specified player is "
"currently in. If your Discord username is the same as your summoner "
"name, or if you have set an alias using 0!setalias, you can use !gameranks me, *region* or 0!gameranks instead.\n"
"Syntax: `0!gameranks username (, region)` -- region if the player you are looking for is on EUW",
"0!uptime": "Returns the duration for which the bot has been running.",
"0!status": "Changes the game the bot is playing to the specified game.",
"0!send": "Makes the bot send a message to the specified channel. The bot needs to be "
"connected to this server for this command to function.",
"0!love": "Send Botwyniel some love!",
"0!fc": "Returns this week's free champions.",
"0!py": "Executes a python command or block of code. Admin-only.",
"0!help": "...really?",
"0!ytsearch": "Sends the URL of the first corresponding youtube video.",
"0!ytlatest": "Sends the URL of the last 3 videos of the specified youtube channel.",
"0!ytthumbnail": "Sends the thumbnail of the first corresponding youtube video.",
"0!avatar": "Sends the URL of the mentionned user's avatar.\n"
"Syntax: `0!avatar @username`",
"0!sendpm": "Sends a private message to the mentionned user.",
"0!8ball": "Ask me a question!",
"0!coin": "Flip a coin!",
"0!dice": "Roll n dices with x faces.\n The command should look like this: **ndx**",
"0!suggest": "Make a suggestion to improve " + self.name,
"0!setalias": "Tell Botwyniel to remember your LoL username and region, so you can call 0!rank and 0!gameranks without arguments.\n"
"Syntax: `0!setalias username, region`",
"0!removealias": "Tell Botwyniel to forget your alias.\n"
"Syntax: `0!removealias`"
}
async def on_ready(self):
print('Logged in as ' + self.user.name)
self.fetch_aliases()
self.loop.create_task(self.check_update())
self.list_servers()
await self.log("Botwyniel initialized")
chans = self.servs["Etwyniel's"].channels
if not discord.opus.is_loaded():
try:
discord.opus.load_opus('/app/.heroku/vendor/lib/libopus.so.0')
except Exception as e:
await self.log('Failed to load opus: ' + str(e))
for c in chans:
if str(c.type) != 'text' and c.name == 'Music':
self.voice.append(await self.join_voice_channel(c))
self.voice[-1].player = None
self.voice[-1].queue = []
self.voice[-1].current = None
async def on_message(self, message):
"""if message.content == '0!play':
url = 'https://www.youtube.com/watch?v=B1O0R0t6zdI'
subprocess.call('youtube-dl --metadata-from-title "%(artist)s - %(title)s"\
--extract-audio --audio-format mp3 --add-metadata ' + url)
video_id = url[url.find('=')+1:]
for f in os.listdir('.'):
if video_id in f:
filename = f
break
await self.songs.put(VoiceEntry(message, filename))
self.current = await self.songs.get()
self.player = self.voice.create_ffmpeg_player(self.current.song, after=self.delete_file)
self.player.start()"""
if message.content.startswith('0!'):
if message.content.split(' ')[0] in self.commands:
await self.log(str(message.author) + ": " + message.content)
await self.commands[message.content.split(" ")[0]](message)
elif message.channel.id == "270622650521485312" and message.author.id != "179225702556499968":
await self.send_message(message.channel,
self.cleverbot.ask(message.content))
async def pause(self, message):
for voice in self.voice:
if voice.server.id == message.server.id and voice.player != None and voice.player.is_playing():
voice.current.position += voice.player.loops * voice.player.delay
voice.player.pause()
asynchttpserver.send_message(message.server.id, "MEDIA_PAUSED")
async def resume(self, message):
for voice in self.voice:
if voice.server.id == message.server.id and voice.player != None and not voice.player.is_playing():
try:
voice.player = voice.create_ffmpeg_player(voice.current.url, before_options="-ss " + str(voice.current.position))
voice.player.start()
asynchttpserver.send_message(message.server.id, "MEDIA_PLAYING")
except:
self.send_message(message.channel, 'No song paused.')
async def skip_song(self, message):
for voice in self.voice:
if voice.server.id == message.server.id and voice.player != None and voice.player.is_playing():
voice.player.stop()
async def queue_song(self, message):
await self.send_typing(message.channel)
if message.server.voice_client == None:
await self.send_message(message.channel, "No voice client on this server (use 0!joinvoice).")
return
url, info = self.get_url(self.truncate(message.content))
if url == None:
await self.send_message(message.channel, "Song not found.")
entry = VoiceEntry(message.server, info["title"], url, info["duration"], info["thumbnail"] if "thumbnail" in info.keys() else '')
voice = message.server.voice_client
if voice.player == None or not voice.player.is_playing():
await self.play_song(voice, entry)
else:
voice.queue.append(entry)
await self.send_message(message.channel, "Queued `{}`".format(info["title"]))
asynchttpserver.send_message(message.server.id, "MEDIA_QUEUED \n" + str(entry.duration) + "\n" + entry.title + '\n' + entry.thumbnail_url)
"""
for voice in self.voice:
if voice.server.id == message.server.id:
url = self.yt.search_video(self.truncate(message.content))
info = self.ydl.extract_info(url, download=False)
audio_url = ""
abr = 0
for f in info["formats"]:
if f["vcodec"] == 'none':
if f["abr"] == 128:
audio_url = f["url"]
abr = 128
break
if f["abr"] > abr:
audio_url = f["url"]
abr = f["abr"]
entry = VoiceEntry(message.server, info["title"], audio_url, info["duration"], info["thumbnail"], message)
if voice.player is None or not voice.player.is_playing():
#await self.send_message(message.channel, "Now playing `{0} Link:{1}`".format(info['title'],url))
await self.play_song(voice, entry)
else:
voice.queue.append(entry)
await self.send_message(message.channel, "Queued `{}`".format(info['title']))
asynchttpserver.send_message(message.server.id, "MEDIA_QUEUED \n" + str(entry.duration) + "\n" + entry.title + '\n' + entry.thumbnail_url)
return
await self.send_message(message.channel, 'No voice client on this server (use 0!joinvoice).')
"""
async def list_queue(self, message):
await self.send_typing(message.channel)
for voice in self.voice:
if voice.server.id == message.server.id:
if voice.queue:
out = "*Playlist:*"
for i in range(len(voice.queue)):
out += "\n" + str(i + 1) + ". `" + voice.queue[i].title + "`"
await self.send_message(message.channel, out)
else:
await self.send_message(message.channel, "Nothing queued.")
return
await self.send_message(message.channel, "No voice client on this server.")
async def play_song(self, voice, entry):
#voice.player = await voice.create_ytdl_player(url)
voice.player = voice.create_ffmpeg_player(entry.url)
voice.player.start()
voice.current = entry
if entry.channel != None:
await self.send_message(entry.channel, 'Now playing `' + entry.title + '`')
while not voice.player.is_done():
await asyncio.sleep(1)
if hasattr(voice, "queue") and voice.queue:
next_song = voice.queue.pop(0)
asynchttpserver.send_message(entry.server.id, "MEDIA_NEXT");
await self.play_song(voice, next_song)
return
async def join_voice(self, message):
channel = self.truncate(message.content).lower()
for c in list(message.server.channels):
if c.name.lower() == channel and str(c.type) == "voice":
for v in self.voice:
if v.server.id == message.server.id:
await v.move_to(c)
return
self.voice.append(await self.join_voice_channel(c))
self.voice[-1].player = None
self.voice[-1].queue = []
return
await self.send_message(message.channel, 'Channel not found.')
async def leave_voice(self, message):
for v in range(len(self.voice)):
if self.voice[v].server.id == message.server.id:
try:
self.voice[v].player.stop()
except:
pass
await self.voice.pop(v).disconnect()
def list_servers(self):
print("\nLogged in to {} servers.".format(len(self.servers)))
for a in self.servers:
#print(a.name)
self.servs[a.name] = a
self.servers_by_id[a.id] = a
ch_dict = {}
for channel in a.channels:
ch_dict[channel.name] = channel
self.channels[a] = ch_dict
print('------')
def fetch_aliases(self):
conn = self.db_connect()
cursor = conn.cursor()
cursor.execute("SELECT * FROM aliases")
row = cursor.fetchone()
while row != None:
self.aliases[row[0]] = [row[1], row[2]]
row = cursor.fetchone()
def uptime(self, ignore):
uptime = datetime.now() - self.init_time
uptime = str(uptime).split(".")[0].split(":")
if uptime[0] == "0":
to_return = "I have been running for {m}m and {s}s.".format(m=uptime[1], s=uptime[2])
if uptime[1] == "00":
to_return = "I have been running for {s}s.".format(s=uptime[2])
else:
to_return = "I have been running for {h}h{m}m and {s}s.".format(h=uptime[0], m=uptime[1], s=uptime[2])
return to_return
async def send_uptime(self, message):
await self.send_typing(message.channel)
await self.send_message(message.channel, self.uptime(message))
async def love(self, message):
outputs = ["You smart. You loyal. You’re grateful. I appreciate that."
"Go buy your momma a house. Go buy your whole family houses."
"Put this money in your savings account. Go spend some money for no reason."
"Come back and ask for more.",
"Marry me!",
"No. F*ck you.",
"*Faints in a puddle of tears of happiness*",
"You're just one of many.",
"Don't tell the others, but I love you too.",
"This needs to stop.",
"You da real MVP!",
"Alright, I won't kill you.",
"Ok, I'll kill you last.",
"Umm... wrong number.",
"Love received!"]
await self.send_message(message.author, outputs[randrange(len(outputs))])
async def status(self, message):
if type(message) == discord.Message:
message.content = self.truncate(message.content)
game = discord.Game(name=message.content)
await self.change_presence(game=game)
self.current_status = message.content
else:
game = discord.Game(name=message)
await self.change_presence(game=game)
self.current_status = message
async def avatar(self, message):
if len(message.mentions) == 0:
await self.send_message(message.channel, message.author.avatar_url)
else:
try:
for user in message.mentions:
await self.send_message(message.channel, user.avatar_url)
except discord.errors.HTTPException:
await self.send_message(message.channel, "This user does not have an avatar.")
@staticmethod
def truncate(message):
message = " ".join(message.split(" ")[1:])
if "```" in message:
message = message.split('```')[1]
return message
def get_player(self, message):
m = self.truncate(message.content)
m = m.split(', ')
username = m[0]
try:
region = m[1]
except IndexError:
region = 'euw'
return username, region.lower()
def author_is_admin(self, message):
return message.author.id in self.whitelist
async def rank(self, message):
await self.send_typing(message.channel)
player = self.get_player(message)
username = player[0]
region = player[1]
if region.upper() not in self.regions:
await self.send_message(message.channel, 'Invalid region')
return None
if username in ["me", '']:
if message.author.id in self.aliases:
username, region = self.aliases[message.author.id]
else:
username = message.author.name
try:
riot = RiotAPI(self.riot_key, region)
rank = riot.get_summoner_rank("".join(username.split(" ")))
to_return = "The summoner {username} is ranked {tier} {division} and currently has {LP} LPs. (S6 winrate: {winrate}%)".format(
username=username,
tier=rank[0].capitalize(),
division=rank[1],
LP=str(rank[2]),
winrate=str(rank[3])
)
except (ValueError, KeyError):
try:
level = riot.get_summoner_level("".join(username.split(" ")))
to_return = "The summoner {username} is unranked and is level {level}.".format(
username=username,
level=str(level)
)
except:
to_return = "The summoner {username} does not exist or is not on the {region} server.".format(
username=username,
region=region
)
await self.send_message(message.channel, to_return)
async def gameranks(self, message):
await self.send_typing(message.channel)
player = self.get_player(message)
username = player[0]
region = player[1]
if region.upper() not in self.regions:
await self.send_message(message.channel, 'Invalid region')
return None
if username in ["me", '']:
if message.author.id in self.aliases:
username, region = self.aliases[message.author.id]
else:
username = message.author.name
riot = RiotAPI(self.riot_key, region)
ranks = riot.get_game_ranks("".join(username.split(" ")))
if not ranks:
await self.send_message(message.channel, "The summoner {username} is "
"not currently in a game or does not exist.".format(
username=username
)
)
return None
to_send = ""#"**Red team**:\n"
for player in ranks:
if ranks.index(player) == len(ranks)/2:
await self.send_message(message.channel, "", embed=discord.Embed(
title="Red team", description=to_send, color=discord.Colour.dark_red()))
to_send = ""#"\n**Blue team**:\n"
if player[2] == "unranked":
to_send += "{name} (**{champion}**): Unranked\n".format(
name=player[0],
champion=player[1]
)
else:
to_send += "{name} (**{champion}**): {tier} {division}\n".format(
name=player[0],
champion=player[1],
tier=player[2].capitalize(),
division=player[3]
)
await self.send_message(message.channel, "", embed=discord.Embed(
title="Blue team", description=to_send, color=discord.Colour.dark_blue()))
async def latest_videos(self, message):
username = self.truncate(message.content)
try:
await self.send_message(message.channel, self.yt.latest_vids(username))
except IndexError:
await self.send_message(message.channel, "The {} channel does not seem to exist.".format(username))
async def search_video(self, message):
query = self.truncate(message.content)
try:
await self.send_message(message.channel, self.yt.search_video(query))
except IndexError:
await self.send_message(message.channel, "No video found matching this query.")
async def get_thumbnail(self, message):
query = self.truncate(message.content)
try:
await self.send_message(message.channel, self.yt.get_thumbnail(query))
except IndexError:
await self.send_message(message.channel, "No video found matching this query.")
async def dice(self, message):
try:
arguments = self.truncate(message.content)
n = int(arguments.split('d')[0])
d = int(arguments.split('d')[1])
if n > 10:
to_return = 'Too many dices!'
elif d > 100:
to_return = 'Too many faces!'
else:
to_return = ''
sum = 0
for a in range(n-1):
number = randrange(d) + 1
sum += number
to_return += str(number) + ' + '
number = randrange(d) + 1
sum += number
to_return += str(number) + ' = ' + str(sum)
except:
to_return = 'Invalid format!'
await self.send_message(message.channel, to_return)
async def coin(self, message):
value = randrange(2)
if value:
to_return = 'Heads!'
else:
to_return = 'Tails!'
await self.send_message(message.channel, to_return)
async def send(self, message):
args = self.truncate(message.content).split(", ")
server = args[0]
channel = args[1]
message.content = ", ".join(args[2:])
chan = self.channels[self.servs[server]][channel]
await self.send_typing(chan)
await self.send_message(chan, message.content)
async def sendpm(self, message):
m = self.truncate(message.content)
receiver = message.mentions[0]
if not message.channel.is_private and receiver.nick != None:
m = m.replace("@" + receiver.nick + " ", "")
else:
m = m.replace("@" + receiver.name + " ", "")
await self.send_message(receiver, m)
def kill(self, message):
if self.author_is_admin(message):
self.send_message(message.channel,
"TRAITOR! ({uptime})".format(user=message.author.name,
uptime=self.uptime(message)))
exit(1)
else:
self.send_message(message.channel, "This is an admin-only command")
async def free_champs(self, message):
await self.send_typing(message.channel)
riot = RiotAPI(self.riot_key)
free_champs = riot.get_free_champions()
to_send = "The free champions this week are {champions} and {last}.".format(
champions=", ".join(free_champs[0:len(free_champs) - 1]),
last=free_champs[len(free_champs) - 1]
)
await self.send_message(message.channel, to_send)
##Overwatch commands
async def ow_rank(self, message):
await self.send_typing(message.channel)
query = self.truncate(message.content)
if ',' in query:
query, region = query.split(", ")
else:
region = 'eu'
try:
rank_image = overwatch_api.get_rank(query, region)
await self.send_file(message.channel, rank_image)
except overwatch_api.PlayerNotFound as e:
await self.send_message(message.channel, str(e))
async def eightball(self, message):
"""THERE YOU GO VANERI!"""
outputs = ["Hell no.",
"Absolutely not!",
"I don't think so.",
"Outlook not so good.",
"Don't count on it.",
"My sources say no.",
"Very doubtful.",
"My reply is no.",
"You won't like the answer...",
"Forget about it.",
"I have my doubts.",
"Are you kidding?",
"Don't bet on it.",
"Forget about it.",
"It is certain.",
"It is decidedly so.",
"As I see it, yes.",
" You may rely on it.",
"Without a doubt.",
"Outlook good.",
"Concentrate and ask again.",
"Reply hazy try again.",
"Cannot predict now.",
"Yes.",
"No.",
"Better not tell you now.",
"Ask again later.",
"Cannot predict now.",
"As I see it, yes."]
to_send = outputs[randrange(len(outputs))]
await self.send_message(message.channel, to_send)
await self.log("Answer: " + to_send)
async def schedule(self, message):
await self.send_typing(message.channel)
_class = self.truncate(message.content)
week = datetime.now().isocalendar()[1] + 122
for i in range(3):
if _class:
calendar = schedule.get_calendar(_class, week)
else:
calendar = schedule.get_calendar("INFOS2INT1-2", week)
events = schedule.next_day_events(calendar)
if not events:
week += 1
else:
break
if not events:
await self.send_message(message.channel, "No upcoming events for the week.")
return
to_send = ""
for event in events:
to_send += ("\n" if to_send else "") + event.begin.format(
"**HH:mm** - ") + event.name + ' - ' + event.location
await self.send_message(message.channel, "",
embed=discord.Embed(
title=events[0].begin.format("dddd, MMMM DD"),
description=to_send,
color=discord.Colour.dark_green()))
async def execute(self, message):
if not self.author_is_admin(message):
await self.send_message(message.channel, "This is an admin-only command.")
return None
try:
command = ""
for char in self.truncate(message.content):
if char == '\n':
if command.startswith('await'):
await eval(command.split('await ')[1])
else:
exec(command)
command = ""
else:
command += char
if command.startswith('await'):
await eval(command.split('await ')[1])
else:
exec(command)
except Exception as e:
await self.log(str(e))
await self.send_message(message.channel, "Error occured: " + str(e))
async def suggest(self, message):
suggestion = self.truncate(message.content)
if suggestion != "":
await self.send_message(self.channels[self.servs['Etwyniel\'s']]['suggestions'], message.author.id + ': ' + suggestion)
await self.send_message(message.channel, "Thanks for the suggestion!")
else:
await self.send_message(message.channel, "Please enter a suggestion.")
async def help(self, message):
if self.truncate(message.content) == "":
await self.send_message(message.author, "The available commands are:\n"
"**0!music**\n"
"**0!rank** *username*, *region*\*\n"
"**0!gameranks** *username*, *region*\*\n"
"**0!setalias** *username*, *region*\*\n"
"**0!removealias**\n"
"**0!avatar** @*user*\n"
"**0!ytsearch** *query*\n"
"**0!ytlatest** *channel name*\n"
"**0!ytthumbnail** *query*\n"
"**0!joinvoice** *voice channel*\n"
"**0!leavevoice**\n"
"**0!play** *query*\n"
"**0!pause**\n"
"**0!resume**\n"
"**0!queue**\n"
"**0!uptime**\n"
"**0!send** *server*, *channel*, message\n"
"**0!sendpm** @*user* *message*\n"
"**0!fc**\n"
"**0!love**\n"
"**0!8ball** *question*\n"
"**0!coin**\n"
"**0!dice** *number of dices* d *type of dice*\n"
"**0!status** *game id*\n"
"**0!suggest** *suggestion*\n"
"**0!about**\n"
"**optional, default is euw.*\n\n"
"Please type '0!help *command*' for more precise instructions.")
elif self.truncate(message.content) in self.commands:
await self.send_message(message.author, self.commands_help[self.truncate(message.content)])
else:
await self.send_message(message.author, "Unknown command.")
async def about(self, message):
await self.send_message(message.channel, ("I am a discord bot created by Etwyniel, using discord.py by Rapptz.\n"
"I can find your League of Legends rank, or the ranks of the people you are playing with and against.\n"
"I can also find videos on YouTube.\n\n"
"I am currently used by {} servers.").format(str(len(self.servers))))
async def log(self, event):
channel = self.channels[self.servs["Etwyniel's"]]["logs"]
to_send = "[{date}] - *{time}*\n{event}".format(
date=str(date.today()),
time="".join(str(datetime.now().time()).split(".")[0])[0:5],
event=event)
await self.send_message(channel, to_send)
async def set_alias(self, message):
id = message.author.id
m = self.truncate(message.content)
if ',' in m:
alias, region = m.split(', ')
else:
alias = m
region = 'euw'
if len(alias) > 32:
self.send_message(message.channel, "This alias is too long.")
elif alias == "":
self.send_message(message.channel, "Please enter your alias.")
elif region.upper() not in self.regions:
self.send_message(message.channel, "Please enter a valid region.")
conn = self.db_connect()
cursor = conn.cursor()
if id in self.aliases:
query = "UPDATE aliases SET alias = '{1}', region = '{2}' WHERE id = '{0}';"
else:
query = "INSERT INTO aliases (id, alias, region) VALUES ('{0}', '{1}', '{2}');"
cursor.execute(query.format(id, alias, region))
conn.commit()
conn.close()
self.aliases[id] = [alias, region]
await self.send_message(message.channel, "Alias {} successfully set!".format(alias))
async def send_music_url(self, message):
await self.send_message(message.channel, "http://botwyniel.ddns.net/" + message.server.id)
def get_url(self, query):
if not query.startswith("http"):
query = self.yt.search_video(query)
try:
info = self.ydl.extract_info(query, download=False)
abr = 0
url = None
for form in info["formats"]:
if "abr" in form.keys() and form["abr"] > abr:
if form["abr"] >= 96:
return form["url"], info
abr = form["abr"]
url = form["url"]
else:
return form["url"]
return url, info
except:
return None, None
async def remove_alias(self, message):
conn = self.db_connect()
cursor = conn.cursor()
id = message.author.id
cursor.execute("SELECT alias FROM aliases WHERE id = '{}'".format(id))
alias = cursor.fetchone()[0]
query = "DELETE FROM aliases WHERE id = '{}'"
cursor.execute(query.format(id))
conn.commit()
conn.close()
self.aliases.pop(id)
await self.send_message(message.channel, "Alias {} successfully removed!".format(alias))
def db_connect(self):
#db = input("Database url: ")[8:]
keys = open(".keys")
keys.readline()
db = keys.readline()[8:-1]
keys.close()
db_server = db[db.index('@') + 1:db.index('/')]
db_username = db[:db.index(':')]
db_password = db[db.index(':') + 1:db.index('@')]
db_database = db[db.index('/') + 1:db.index('?')]
conn = pymysql.connect(host=db_server, user=db_username, password=db_password, db=db_database)
return conn
async def check_update(self):
# What a mess...
league_url = "http://euw.leagueoflegends.com/en/news/"
#current_version = requests.get(db_url, params=args).text
while True:
channel = discord.Object('211180551502168064')
conn = self.db_connect()
cursor = conn.cursor()
cursor.execute("SELECT * FROM botwyniel_data WHERE name='last update'")
current_version = cursor.fetchone()[1]
#current_version = requests.get(db_url, params=args).text
patch_page = requests.get(league_url).text
index = patch_page.index("lol-core-file-formatter")
field = patch_page[patch_page.rfind("<", 0, index):patch_page[index:].find(">") + index]
latest_version = field[field.index("title=") + 7:field[field.index("title=") + 7:].index('"') + field.index("title=") + 7]
if current_version != latest_version:
patch_url = "http://euw.leagueoflegends.com" + \
field[field.index("href=") + 6:field[field.index("href=") + 6:].index('"') + field.index("href=") + 6]
await self.send_message(channel, "New League of Legends update!\n" + patch_url)
cursor.execute("UPDATE botwyniel_data SET val='{}' WHERE name='last update'".format(latest_version))
conn.commit()
current_version = latest_version
conn.close()
await asyncio.sleep(900)
"""
try:
keys = open(".keys")
token = keys.readline()[:-1]
keys.close()
botwyniel = Bot(wl=["112836380245114880"])
botwyniel.run(token)
except Exception as e:
print(e)
botwyniel = Bot(wl=["112836380245114880"])
botwyniel.run(input("Token: "))"""