-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
484 lines (330 loc) · 13.9 KB
/
client.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
from discord.ext import commands
from discord.ext import tasks
from collections import deque
from waifuim import WaifuAioClient
from datetime import date
import math
import os
import random
import discord
import asyncio
# import youtube_dl
import audio_metadata
import datetime
class SumerianBot(commands.Bot):
rofl_mode = False
repeat = False
repeat_all = False
playlist = deque()
voice:discord.VoiceClient = None
main_guild = None
main_channel = None
control_message = None
sound_dir = "sounds/"
playlist_dir = "playlists/"
week_dir = "week/"
waifuClient = WaifuAioClient()
#######################################################################################################
######################## BASE SECTION ###########################################################
#######################################################################################################
async def on_ready(self):
self.sounds = os.getenv("JUMPSCARE_SND").split(",")
self.call_word = os.getenv("CALL_PHRASE").split(",")
self.kill_word = os.getenv("KILL_PHRASE").split(",")
for guild in self.guilds:
if(guild.id == int(os.getenv("GUILD_ID"))):
self.main_guild = guild
for channel in guild.text_channels:
if(channel.id == int(os.getenv("MAIN_CHN"))):
self.main_channel = channel
break
if self.rofl_mode:
self.jumpscare.start()
print(f"{self.user} has connected!")
################## MESSAGES ##################
async def on_message(self, message, /) -> None:
if message.author == self.user:
return
#Commands processing
if(message.content.startswith("!")):
await self.process_commands(message)
await message.delete()
return
if not self.rofl_mode:
return
#Rofl mode features
#Bot call
if(any(sub in message.content for sub in self.call_word)):
await self.gen_sound(message.author.voice.channel)
return
#Bot kill
if(any(sub in message.content for sub in self.kill_word)):
await self.voice.disconnect()
self.voice = None
#Bot random phrase reply
value = random.random()
if(value > 0.5):
await message.channel.send(self.gen_random_sumerian())
pass
################## ERROR HANDLER ##################
async def on_command_error(self, interaction, error):
if isinstance(error, commands.CommandNotFound):
embed = discord.Embed(title="Command error!", description="Command not found!", color=discord.Color.red())
await interaction.send(embed=embed)
#######################################################################################################
######################## TASK SECTION ###########################################################
#######################################################################################################
################## JUMPSCARE ##################
@tasks.loop(hours=2, count=None)
async def jumpscare(self):
channels = []
for channel in self.main_guild.voice_channels:
if len(channel.members) > 0 and channel.id != int(os.getenv("AFK_CHN")):
channels.append(channel)
if(random.random() > .7):
await self.gen_sound(random.choice(channels))
else:
print("Jumpscare failed! I will try later")
pass
################## SOUND PLAYING ##################
@tasks.loop(seconds=1, count=None)
async def playing(self):
if len(self.playlist) <= 0:
return
next_sound = self.playlist[0]
await self.play_sound(next_sound)
while(self.voice.is_playing() or self.voice.is_paused()):
await asyncio.sleep(1)
if(not self.repeat):
if(len(self.playlist) > 0):
self.playlist.popleft()
if(self.repeat_all):
self.playlist.append(next_sound)
if(len(self.playlist) <= 0):
self.playing.stop()
pass
#######################################################################################################
######################## FUNCTIONS SECTION ######################################################
#######################################################################################################
################## UTILITY ##################
def findVoiceChannel(self, userID:int, guild):
for voiceChannel in guild.voice_channels:
member = self.findMemberInChannel(userID, voiceChannel)
if(member != None):
return voiceChannel
return None
def findMemberInChannel(self, userID:int, channel:discord.VoiceChannel):
for member in channel.members:
if(member.id == userID):
return member
return None
def findMember(self, userID:int, guild):
for voiceChannel in guild.voice_channels:
member = self.findMemberInChannel(userID, voiceChannel)
if(member != None):
return member
################## SOUND WORK ##################
async def gen_sound(self, channel):
value = random.choice(self.sounds)
await self.play_sound_leave(channel, value)
pass
async def play_sound_leave(self, channel, sound):
await self.connectToVoice(channel)
self.play_sound(sound)
while(self.voice.is_playing()):
await asyncio.sleep(1.0)
await self.voice.disconnect()
self.voice = None
pass
def check_sound(self, sound:str):
sounds = os.listdir(self.sound_dir[:-1])
for s in sounds:
if(sound.lower() == s.lower()):
return True, s
if(sound.lower() == s.split(".", 1)[0].lower()):
return True, s
return False, sound
pass
async def play_sound(self, sound):
if(self.voice == None):
return
if(self.voice.is_playing()):
return
self.voice.play(source=discord.FFmpegPCMAudio(executable="util/ffmpeg.exe", source=f"{self.sound_dir}{sound}"))
metadata = self.get_sound_metadata(sound=sound)
duration = "TNG"
if metadata != None:
duration = datetime.timedelta(seconds=math.ceil(metadata.streaminfo.duration))
await self.main_channel.send(embed=discord.Embed(title="Playing", description=f"{sound}({duration})", color=discord.Color.green()))
print(f"Playing: {sound}({duration})")
pass
def get_sound_metadata(self, sound):
try:
metadata = audio_metadata.load(f"{self.sound_dir}{sound}")
except Exception as ex:
print(ex)
return None
print(metadata)
return metadata
async def start_sound(self):
if(not self.playing.is_running()):
self.playing.start()
pass
async def stop_playing(self):
if(self.voice == None):
return
self.playlist.clear()
self.voice.stop()
self.repeat = False
def stop_sound(self):
if(self.voice == None):
return
if(self.voice.is_playing()):
self.voice.stop()
print("Sound stoped")
pass
def pause_sound(self):
if(self.voice == None):
return
if not self.voice.is_paused():
self.voice.pause()
print(f"{self.playlist[0]} is paused")
return True
else:
return False
pass
def resume_sound(self):
if(self.voice == None):
return
if self.voice.is_paused():
self.voice.resume()
print(f"{self.playlist[0]} is resumed")
return True
else:
return False
pass
def skip_sound(self):
if(self.voice == None):
return
if(len(self.playlist) <= 0):
return
sound = self.playlist[0]
self.voice.stop()
print(f"{self.playlist[0]} is skipped")
return discord.Embed(title="Skipped", description=sound, color=discord.Color.red())
################## PLAYLISTS ##################
def show_soundlist(self) -> discord.Embed:
sounds = os.listdir(self.sound_dir[:-1])
result = ""
number = 1
for sound in sounds:
result += f"{number}. {sound}\n"
embed = discord.Embed(title="Sound list", description=result, color=discord.Color.dark_blue())
return embed
pass
def show_playlist(self):
result = ""
position = 1
for sound in self.playlist:
string = f"{position}. {sound}"
result += string
if(self.playlist.index(sound) == 0):
result += " - :loud_sound:"
result += "\n"
embed = discord.Embed(title="Playlist", description=result, color=discord.Color.purple())
return embed
def add_playlist(self, sound) -> discord.Embed:
self.playlist.append(sound)
return discord.Embed(title="Added", description=sound, color=discord.Color.yellow())
def show_playlists(self):
return discord.Embed(title="Available playlists", description=os.listdir(self.playlist_dir[:-1]), color=discord.Color.gold())
pass
def save_playlist(self, name):
try:
file = open(f"{self.playlist_dir}{name}", "w")
for sound in self.playlist:
file.write(sound + "\n")
file.close()
print(f"Saved as {name}")
except:
return False
return True
def load_playlist(self, name):
try:
file = open(f"{self.playlist_dir}{name}", "r")
playlist = file.readlines()
for sound in playlist:
self.playlist.append(sound[:-1])
print(f"Loaded: {playlist}")
except:
return False
return True
################## VOICE ##################
async def connectToVoice(self, channel):
if(self.voice != None):
return
self.voice = await channel.connect()
async def disconnect(self):
if(self.voice == None):
return
self.playlist.clear()
if(self.voice.is_playing()):
self.voice.stop()
while self.playing.is_running():
await asyncio.sleep(1)
await self.voice.disconnect()
self.voice = None
pass
################## OTHERS ##################
def gen_random_sumerian(self):
length = random.randint(5, 20)
return self.gen_sumerian(length)
pass
def gen_sumerian(self, l) -> str:
result = ""
for i in range(l):
value = random.randint(160, 223)
code = 66304 + value
result += chr(code)
sign = [' ', '!', '?']
result += random.choice(sign)
return result
pass
# def download_sound_YT(self, url, name):
# ydl_opts = {
# 'format': 'bestaudio/best',
# 'postprocessors': [{
# 'key': 'FFmpegExtractAudio',
# 'preferredcodec': 'mp3',
# 'preferredquality': '192',
# }],
# 'outtmpl': f'{self.sound_dir}{name}.mp3',
# }
# with youtube_dl.YoutubeDL(ydl_opts) as ydl:
# ydl.download([url])
async def get_anime(self, tags:str):
image = None
if(len(tags) != 0):
tags = tags.replace(" ", "")
tags = tags.split(",")
try:
image = await self.waifuClient.search(included_tags=tags)
except Exception:
await self.main_channel.send(embed=discord.Embed(title="Error!", description="Typed tag is incorrect!", color=discord.Color.red()))
else:
image = await self.waifuClient.search()
if(image == None):
return
embed = discord.Embed(title="Picture", description=tags, type="image", color=discord.Color.blurple())
embed.set_image(url=image.url)
await self.main_channel.send(embed=embed)
print(f"Picture loaded: {image.url}")
async def what_day(self):
today = date.today()
weekday = today.weekday()
try:
with open(f"{self.week_dir}{weekday}.gif", "rb") as file:
image = discord.File(file)
return image
except Exception:
await self.main_channel.send(embed=discord.Embed(title="Sorry!", description="No to celebrate today", color=discord.Color.red()))