-
Notifications
You must be signed in to change notification settings - Fork 0
/
discordbot.py
1367 lines (1214 loc) · 55 KB
/
discordbot.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
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# make requirements.txt command -> (myenv)$ pip freeze > requirements.txt
# Video and audio are file-like objects.
# This Discord bot uses PyNaCl & FFmpeg in VoiceChat class.
# pip update
# powershell: pip3 install --upgrade ((pip3 freeze) -replace '==.+','')
# https://www.yukkuriikouze.com/2019/07/12/3105/
from __future__ import unicode_literals
from discord import channel
# ----- basic module ----
import os
import io
import re
import math
import random
import string
import json
import random
import socket
import time
import platform
import threading
# ----- extend module -----
import aiohttp #画像転送系
from pyshorteners import Shortener
from gtts import gTTS
import asyncio
import pathlib
import psutil
import cpuid
import youtube_dl
import discord
from discord.ext import commands
from discord_slash import SlashCommand
from discord_slash import cog_ext, SlashContext
import urllib.request
import urllib.parse
from niconico_dl_async import NicoNico
import ffmpeg
# ---- my module ----
from modules import my_key # get my api keys
from modules import my_music
from modules import brainfuck # my brainfuck interpreter
from modules import kawaii_voice_gtts
from modules import htr # get hattori
from modules import htr_end
from modules import htr_dead
from modules import eq_check
from modules import up_server
VERSION='v2.6.11 beta'
_TOKEN, _A3RT_URI, _A3RT_KEY, _GoogleTranslateAPP_URL,\
LOG_C, MAIN_C, VOICE_C, HA, _UP_SERVER,\
M_CALL = my_key.get_keys()
HTR_LIST = htr.get_hattori()
HTRE_LIST = htr_end.end_hattori()
HTRD_LIST = htr_dead.dead_hattori()
description = 'BさんのBBBot ('+VERSION+')'
bot = commands.Bot(
command_prefix='?', # コマンドの最初の文字
description=description,
case_insensitive = True, # コマンドの大文字小文字
)
slash = SlashCommand(bot, sync_commands=True, sync_on_cog_reload=True)
#----------------------------------------------------------
# 起動時に動作する処理
@bot.event
async def on_ready():
# ログイン通知
print(bot.user.name + ' is logged in.')
# await bot.change_presence(status=discord.Status.idle, activity=discord.Game(name="BBBot "+VERSION, emoji="🍝"))
await bot.change_presence(status=discord.Status.online, activity=discord.Game(name="BBBot "+VERSION, emoji="🍝"))
# await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name="BBBot "+VERSION))
lChannel = bot.get_channel(LOG_C)
await lChannel.send('BBBot is Ready! ' + VERSION)
#---------------------------------------------------------- 定期実行系
# 非同期並行処理
eqc = eq_check.EqCheck(bot, LOG_C, MAIN_C)
ups = up_server.UpServer(bot, LOG_C, _UP_SERVER)
await asyncio.gather(
eqc.p2peq_check(),
ups.up_server(),
)
# メッセージ受信時に動作する処理
@bot.event
async def on_message(message):
if message.content.startswith('?'):
lChannel = bot.get_channel(LOG_C)
await lChannel.send("```\n@"+str(message.author.name)+"\n"+str(message.author.id)+"\n"+str(message.content)+" ```")
if message.author.bot: return # ボットだったら何もしない
await bot.process_commands(message)
#---------------------------------------------------------- 計算系
class Calc(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command(description='計算 Eval')
# Evalなので攻撃しないでください。
async def calc(self, ctx, *inc: str):
"""Calc number Eval"""
inc = ''.join(inc)
inc = re.sub(r"[\u3000 \t]", "", inc)
await Basic.send(self, ctx, eval(inc, {}, {'math':math}))
@commands.command(description='足し算')
async def add(self, ctx, left: str, right: str):
"""Add number + number"""
left = float(left); right = float(right)
await Basic.send(self, ctx, left + right)
@commands.command(description='引き算')
async def sub(self, ctx, left: str, right: str):
"""Sub number - number"""
left = float(left); right = float(right)
await Basic.send(self, ctx, left - right)
@commands.command(description='掛け算')
async def mul(self, ctx, left: str, right: str):
"""Mul number * number"""
left = float(left); right = float(right)
await Basic.send(self, ctx, left * right)
@commands.command(description='割り算')
async def div(self, ctx, left: str, right: str):
"""Div number / number"""
left = float(left); right = float(right)
await Basic.send(self, ctx, left / right)
@commands.command(description='自己情報量I()')
async def self_info(self, ctx, p: str):
"""Self-information I(p)"""
p = float(eval(p))
if p == 0.0:
await Basic.send(self, ctx, 0.0)
else:
await Basic.send(self, ctx, -p*math.log2(p))
@commands.command(description='エントロピー関数計算H()')
async def ent(self, ctx, p: str):
"""EntropyFunc H(p)"""
p = float(eval(p))
if p == 0.0:
await Basic.send(self, ctx, 0.0)
else:
await Basic.send(self, ctx, -p*math.log2(p)-(1-p)*math.log2(1-p))
@commands.command(description='乱数(int) 1~x')
async def rand(self, ctx, p: str):
"""Random(int) 1~x"""
p = int(eval(p))
if p>1:
await Basic.send(self, ctx, random.randint(1, p))
else:
await Basic.send(self, ctx, random.randint(p, 1))
@commands.command(description='乱数(float)) 1.0~x')
async def randd(self, ctx, p: str):
"""Random(float) 1.0~x"""
p = float(eval(p))
if p > 1.0:
await Basic.send(self, ctx, random.uniform(1.0, p))
else:
await Basic.send(self, ctx, random.uniform(p, 1.0))
@commands.command(description='素因数分解(2以上の整数のみ)')
async def fractor(self, ctx, p: int):
try:
p = int(p)
ct = p
if p >= 2:
res = []
for i in range(2, int(p**0.5)+1):
if ct % i == 0:
cn = 0
while ct % i == 0:
ct //= i # intへのキャストの代わり ( /= だとdoubleになってちょっと遅くなるかもしれないので)
cn += 1
res.append([i, cn])
if ct != 1: res.append([ct, 1]) # iで割れずに残っている場合
if res == []: res.append([p, 1]) # 単純に素数の場合
else:
await Basic.send(self, ctx, 'The value must be greater than or equal to 2')
res_t = f'{p} = '
for i in range(len(res)):
res_t += f'{res[i][0]}^{res[i][1]}'
if i != len(res)-1: res_t += ' * '
await Basic.send(self, ctx, str(res_t))
except Exception as e:
print(e)
await Basic.send(self, ctx, 'The number must be an integer greater than or equal to 2')
#---------------------------------------------------------- B系
class B(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command(description='Bを連続送信します')
async def BLOOP(self, ctx, times: int):
"""BLOOP number<=11"""
if times > 12 :
await Basic.send(self, ctx, 'too B!')
return
for _ in range(times):
await Basic.send(self, ctx, 'B')
@commands.group(description='greet, hello, help, block')
# async def B(self, ctx, swit: str, swit2: str):
async def B(self, ctx):
"""B + (greet / sysinfo / hello / block / typing)"""
if ctx.invoked_subcommand is None:
await Basic.send(self, ctx, 'B!')
@B.command()
async def greet(self, ctx):
await Basic.send(self, ctx, 'こんにちは! BBBot('+VERSION+')だよ。\nよろしくね')
@B.command()
async def sysinfo(self, ctx):
ipInfo = 'IP :'+socket.gethostname()+': '+socket.gethostbyname(socket.gethostname())
platInfo = 'OS : '+platform.platform()
cpuInfo = 'CPU: '+cpuid.cpu_name()
#cpuInfo = 'CPU: ['+str(psutil.cpu_count(logical=False))+'C '+str(psutil.cpu_count())+'T]'
memInfo = 'MEM: '+str('{:.2f}'.format(psutil.virtual_memory().used/(1024*1024)))+'MB / '\
+str('{:.2f}'.format(psutil.virtual_memory().total/(1024*1024)))+'MB'
await Basic.send(self, ctx, ipInfo+"\n"+platInfo+"\n"+cpuInfo+"\n"+memInfo)
@B.command()
async def hello(self, ctx):
await Basic.send(self, ctx, 'Hello B!')
@B.command()
async def block(self, ctx):
await Basic.send(self, ctx, '□□□□□□□□\n□■■■■□□□\n□■□□□■□□\n□■□□□■□□\n□■■■■□□□\n□■□□□■□□\n□■□□□□■□\n□■□□□□■□\n□■■■■■□□\n□□□□□□□□')
@B.command()
async def ping(self, ctx):
await Basic.send(self, ctx, f"{bot.latency*1000}ms")
@B.command()
async def typing(self, ctx):
async with ctx.typing():
await asyncio.sleep(10)
ctx.typing()
await Basic.send(self, ctx, 'B')
@B.command()
async def hattori(self, ctx, *tx:str):
""" htr """
txx = ' '.join(tx)
# mChannel = bot.get_channel(MAIN_C)
if 'end' in txx.lower():
await Basic.send(self, ctx, HTRE_LIST[random.randrange(len(HTRE_LIST))])
elif 'd' in txx.lower():
await Basic.send(self, ctx, HTRD_LIST[random.randrange(len(HTRD_LIST))])
else:
await Basic.send(self, ctx, HTR_LIST[random.randrange(len(HTR_LIST))])
# @B.command()
# async def morning_call(self, ctx):
# """強制モーニングコールが行われる"""
# vChannel = bot.get_channel(VOICE_C)
# user = bot.fetch_user(HA) # get user from id
# await Basic.send(self, ctx, user)
# await user.move_to(vChannel)
# await vChannel.connect()
# VoiceChat.v_music(self, ctx, M_CALL)
#---------------------------------------------------------- 画像系
class Image(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.group(description='send img')
async def img(self, ctx):
"""send img. melt/abya/shiran/party/... -> ?help img"""
if ctx.invoked_subcommand is None:
await Basic.send(self, ctx, 'img help: `?help img`')
@img.command(description='melt picture')
async def melt(self, ctx):
"""melt picture"""
await Image.get_pic(self, ctx, 'https://dic.nicovideo.jp/oekaki/674964.png', 'melt.png')
@img.command(description='abya picture')
async def abya(self, ctx):
"""abya picture"""
await Image.get_pic(self, ctx, 'https://livedoor.blogimg.jp/mn726/imgs/0/3/03812153.jpg', 'abya.png')
@img.command(description='shiran kedo~ picture')
async def shiran(self, ctx):
"""shiran kedo~ picture"""
await Image.get_pic(self, ctx, 'https://pbs.twimg.com/media/DoGwbj0UwAALenI.jpg', 'shiran.jpg')
@img.command(description='party parrot GIF')
async def party(self, ctx):
"""party parrot GIF"""
await Image.get_pic(self, ctx, 'https://cdn.discordapp.com/attachments/705099416083890281/766528750456012841/parrot.gif', 'party_parrot.gif')
@img.command(description='B picture')
async def b_pic(self, ctx):
"""B picture"""
await Image.get_pic(self, ctx, 'https://cdn.discordapp.com/attachments/705099416083890281/766668684188975114/letter-b-clipart-158558-5546542.jpg', 'b_picture.jpg')
@img.command(description='gaming presentation GIF')
async def presen(self, ctx):
"""gaming presentation GIF"""
await Image.get_pic(self, ctx, 'https://cdn.discordapp.com/attachments/733937061199085610/768300192818135040/GPW.gif', 'gaming_presentation.gif')
@img.command(description='maji yabakune')
async def majiyaba(self, ctx):
"""maji yabakune"""
await Image.get_pic(self, ctx, 'https://pbs.twimg.com/media/C34X4w0UcAEyKW-.jpg', 'majiyaba.jpg')
@img.command(description='bohe')
async def bohe(self, ctx):
"""bohe"""
await Image.get_pic(self, ctx, 'https://maidragon.jp/news/wordpress/wp-content/uploads/2021/07/806b36e95d491beec2aaaec7af98ad28-2.gif', 'bohe.gif')
@img.command(description='gyu')
async def gyu(self, ctx):
"""gyu GIF"""
await Image.get_pic(self, ctx, 'https://maidragon.jp/news/wordpress/wp-content/uploads/2021/07/58b9f8279c61a217bc7770446a6d542f.gif', 'gyu.gif')
@img.command(description='ha!')
async def ha(self, ctx):
"""ha! GIF"""
await Image.get_pic(self, ctx, 'https://maidragon.jp/news/wordpress/wp-content/uploads/2021/07/13a658840a8373deb4355975b3e56e0b.gif', 'ha!.gif')
@img.command(description='hello')
async def hello(self, ctx):
"""hello GIF"""
await Image.get_pic(self, ctx, 'https://maidragon.jp/news/wordpress/wp-content/uploads/2021/07/3f5592cb37efa6b1a0e1f5ac2cc86e26.gif', 'hello.gif')
@img.command(description='maken')
async def maken(self, ctx):
"""maken GIF"""
await Image.get_pic(self, ctx, 'https://maidragon.jp/news/wordpress/wp-content/uploads/2021/07/a5f64bc592c42aecea1e8fb29eac3642-2.gif', 'maken.gif')
@img.command(description='onegai')
async def onegai(self, ctx):
"""onegai GIF"""
await Image.get_pic(self, ctx, 'https://maidragon.jp/news/wordpress/wp-content/uploads/2021/07/a533a6932106c9f63ae9ee4ea3a478a5.gif', 'onegai.gif')
@img.command(description='Pet the B')
async def b_pet(self, ctx):
"""Pet the B GIF"""
await Image.get_pic(self, ctx, 'https://cdn.discordapp.com/attachments/705099416083890281/880373964088692736/Pet_the_B.gif', 'Pet_the_B.gif')
@img.command(description='thx')
async def thx(self, ctx):
"""thx GIF"""
await Image.get_pic(self, ctx, 'https://cdn.discordapp.com/attachments/880371118148558848/880701571917307914/meidora2.gif', 'thx.gif')
@commands.command(description='send photo')
async def b_img(self, ctx, url: str, file_name: str):
"""b_img url file_name"""
await Image.get_pic(self, ctx, url, file_name)
async def get_pic(self, ctx, url: str, file_name: str):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status != 200:
return await Basic.send(self, ctx, 'server error... b')
data = io.BytesIO(await resp.read())
await ctx.send(file=discord.File(data, file_name))
#---------------------------------------------------------- AI系
class AI(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command(description='a3rt AI TalkAPI')
async def ai(self, ctx, talk: str):
"""a3rt AI TalkAPI"""
try:
data = urllib.parse.urlencode({"apikey":_A3RT_KEY, "query":talk}).encode('utf-8')
request = urllib.request.Request(_A3RT_URI, data)
res = urllib.request.urlopen(request)
json_load = json.load(res)
# await Basic.send(self, ctx, '精度:'+str(json_load['results'][0]['perplexity'])+"\n"+json_load['results'][0]['reply'])
await Basic.send(self, ctx, json_load['results'][0]['reply'])
except Exception as e:
print(e)
await bot.get_channel(LOG_C).send(str(e))
#---------------------------------------------------------- youtube-dl
class Youtube(commands.Cog):
ytdl_opts = {
'format' : 'bestaudio/best',
# 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'outtmpl': '%(title)s.%(id)s.%(ext)s',
'restrictfilenames': True,
# 'noplaylist': True, # allow playlist
'nocheckcertificate': True,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
# ytdl = youtube_dl.YoutubeDL(ytdl_opts)
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command(description='youtube-dl audio only')
async def ydl(self, ctx, url: str):
"""youtube-dl audio only [ org / max 8MB ]"""
if 'soundcloud' in urllib.parse.urlparse(url).netloc: # soundcloud
await self.ydl_m4a(ctx, url)
else: # youtube (or niconico)
filename = await self.ydl_proc(ctx, url, self.ytdl_opts)
for i in range(len(filename)):
await self.ydl_send(ctx, filename[i])
@commands.command(description='youtube-dl audio mp3')
async def ydl_mp3(self, ctx, url: str):
"""youtube-dl audio only [ mp3 / max 8MB ]"""
setOpt = {
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
}]
}
filename = await self.ydl_proc(ctx, url, dict(self.ytdl_opts, **setOpt))
for i in range(len(filename)):
await self.ydl_send(ctx, filename[i])
@commands.command(description='youtube-dl audio m4a')
async def ydl_m4a(self, ctx, url: str):
"""youtube-dl audio only [ m4a / max 8MB ]"""
setOpt = {
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'm4a',
}]
}
filename = await self.ydl_proc(ctx, url, dict(self.ytdl_opts, **setOpt))
for i in range(len(filename)):
await self.ydl_send(ctx, filename[i])
# await Basic.send(self, ctx, json.dumps(self.ytdl_opts | setOpt)) #Debug
@commands.command(description='youtube-dl audio aac')
async def ydl_aac(self, ctx, url: str):
"""youtube-dl audio only [ aac / max 8MB ]"""
setOpt = {
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'aac',
}]
}
filename = await self.ydl_proc(ctx, url, dict(self.ytdl_opts, **setOpt))
for i in range(len(filename)):
await self.ydl_send(ctx, filename[i])
# await Basic.send(self, ctx, json.dumps(self.ytdl_opts | setOpt)) #Debug
async def ydl_getc(self, ctx, url:str, ytdl_opts):
"""" get playlist """
async with ctx.typing():
try:
with youtube_dl.YoutubeDL(ytdl_opts) as ydl:
pre_info = ydl.extract_info(url, download=False)
if 'entries' in pre_info:
video = pre_info['entries']
plist = []
for i, item in enumerate(video):
plist.append(pre_info['entries'][i]['webpage_url'])
return plist
else:
return [url]
except Exception as e:
print(e)
await bot.get_channel(LOG_C).send(str(e))
return False
async def ydl_proc(self, ctx, url:str, ytdl_opts):
"""" download video & return filenames(list) """
if 'nico' in urllib.parse.urlparse(url).netloc: # niconico
return await Youtube.ndl_proc(self, ctx, url)
else: # youtube
async with ctx.typing():
try:
# 事前に情報取得
with youtube_dl.YoutubeDL(ytdl_opts) as ydl:
pre_info = ydl.extract_info(url, download=False)
if 'entries' in pre_info:
# playlist (multiple video)
video = pre_info['entries']
filenames = []
for i, item in enumerate(video):
with youtube_dl.YoutubeDL(ytdl_opts) as ydl:
info = ydl.extract_info(pre_info['entries'][i]['webpage_url'], download=True)
filename = ydl.prepare_filename(info)
if 'postprocessors' in ytdl_opts:
filename = pathlib.PurePath(filename).stem + '.' + ytdl_opts['postprocessors'][0]['preferredcodec']
filenames.append(filename)
return filenames
else:
# single video
with youtube_dl.YoutubeDL(ytdl_opts) as ydl:
info = ydl.extract_info(url, download=True)
filename = ydl.prepare_filename(info)
if 'postprocessors' in ytdl_opts:
filename = pathlib.PurePath(filename).stem + '.' + ytdl_opts['postprocessors'][0]['preferredcodec']
return [filename]
except Exception as e:
await Basic.send(self, ctx, 'Error: Youtube.ydl_proc')
await bot.get_channel(LOG_C).send(str(e))
return False
# niconico download
async def ndl_proc(self, ctx, url:str):
try:
nico_path = pathlib.Path(str(url)).name
nico = NicoNico(nico_path)
nico_data = await nico.get_info()
title = nico_data["video"]["title"] + '.mp4'
await nico.download(title) # download & save
nico.close()
return await Youtube.ffmpeg(self, title, 'm4a')
except Exception as e:
await bot.get_channel(LOG_C).send(str(e))
return False
# convert (need install ffmpeg) fmt = m4a, mp3, ...
async def ffmpeg(self, filename:str, fmt):
stream = ffmpeg.input(filename)
stream = ffmpeg.output(stream, filename+'.'+fmt, format=fmt)
ffmpeg.run(stream)
try:
os.remove(filename)
finally:
return filename+'.'+fmt
async def ydl_send(self, ctx, filename):
try:
with open(filename, 'rb') as fp:
await ctx.send(file=discord.File(fp, filename))
if os.path.exists(filename):
os.remove(filename)
except discord.errors.HTTPException:
await Basic.send(self, ctx, 'Error: File size is too large? [Max 8MB]\n')
except Exception as e:
print(e)
await Basic.send(self, ctx, 'Error: Unknown')
await bot.get_channel(LOG_C).send(str(e))
#---------------------------------------------------------- Discord_VoiceChat
class VoiceChat(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
self.now = None # now playing
self.volume = 1.0
self.inf_play = False # infinity play music
self.queue = [] # music queue ['now play', 'next', '...'] (url)
self.state = False # continue to play
self.nightcore = False # nightcore effect
self.bassboost = False # bassboost effect
self.ytdl_opts = {
'format' : 'bestaudio/best',
# 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'outtmpl': '%(title)s.%(id)s.%(ext)s',
'restrictfilenames': True,
# 'noplaylist': True,
'nocheckcertificate': True,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
self.ytdl_opts_np = {
'format' : 'bestaudio/best',
'outtmpl': '%(title)s.%(id)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
@commands.command(description='Discord_VoiceChat Connect')
async def v_connect(self, ctx):
"""Voice Connect"""
channel = ctx.author.voice.channel
if (not ctx.author.voice) or (not ctx.author.voice.channel): # ボイスチャンネルに入っていない
await Basic.send(self, ctx, 'You need to be in the voice channel first.')
return
if ctx.voice_client is not None:
return await ctx.voice_client.move_to(channel)
await channel.connect()
@commands.command(description='Discord_VoiceChat Disconnect')
async def v_disconnect(self, ctx):
"""Voice Disconnect"""
self.inf_play = False
self.queue = []
self.state = False
await ctx.voice_client.disconnect()
@commands.command(description='same as v_disconnect')
async def v_d(self, ctx):
"""Voice Disconnect (same as ?v_disconnect)"""
await VoiceChat.v_disconnect(self, ctx)
@commands.command(description='Discord_VoiceChat TTS')
async def v_boice(self, ctx, *tx:str):
"""Voice TTS (Japanese)"""
await VoiceChat.make_tts(self, ctx, tx, 'ja', 1)
@commands.command(description='same as v_boice')
async def v_voice(self, ctx, *tx:str):
"""Voice TTS (Japanese) (same as ?v_boice)"""
tx = ' '.join(tx)
await VoiceChat.v_boice(self, ctx, tx)
@commands.command(description='Discord_VoiceChat TTS EN')
async def v_boice_en(self, ctx, *tx:str):
"""Voice TTS EN (English)"""
await VoiceChat.make_tts(self, ctx, tx, 'en', 0)
@commands.command(description='same as v_boice_en')
async def v_voice_en(self, ctx, *tx:str):
"""Voice TTS EN (English) (same as v_boice_en)"""
tx = ' '.join(tx)
await VoiceChat.v_boice_en(self, ctx, tx)
@commands.group(description='play music (b/b_loop/stop/skip/queue/play)')
async def v_music(self, ctx):
"""play music. (b/b_loop/stop/skip/queue/queue_del/play)"""
await VoiceChat.v_connect(self, ctx) # 接続確認
if ctx.invoked_subcommand is None: # サブコマンドがない場合
self.state = False # auto play: off
self.inf_play = False # stop inf play
tx = str(ctx.message.content).split()[1] # サブコマンドではない場合、URLとして扱う
if not tx:
await Basic.send('The URL value is not appropriate')
return
try: # try connect url
f = urllib.request.urlopen(tx)
f.close()
except Exception as e:
print(e)
await Basic.send('network error')
await bot.get_channel(LOG_C).send(str(e))
return False
if self.now != None and self.state != True:
self.now.stop()
self.now = None
await ctx.message.delete()
pre_send = await Basic.send(self, ctx, "Now processing...")
plist = await Youtube.ydl_getc(self, ctx, tx, self.ytdl_opts)
if plist:
self.queue.extend(plist)
if self.now == None and len(self.queue):
if len(self.queue) == 1: # 1曲だけの場合
next_song_url = self.queue.pop(0)
[next_song_filename] = await Youtube.ydl_proc(self, ctx, next_song_url, self.ytdl_opts)
next_song_filename = await VoiceChat.effect(self, next_song_filename) # エフェクト
await Basic.delete(self, pre_send) # 事前に送信したメッセージの削除
await VoiceChat.voice_send(self, ctx, next_song_filename)
elif len(self.queue) > 0: # 複数曲の場合 (曲の表示等あり)
await Basic.delete(self, pre_send)
await Basic.send(self, ctx, str(len(plist))+" songs added ("+str(len(self.queue))+" songs in the queue)")
await VoiceChat.play(self, ctx)
else: return False
@v_music.command(description='skip')
async def skip(self, ctx):
"""skip current music"""
# self.inf_play = False # infiniry play: off
self.now.stop()
self.now = None
# if self.now != None:
# self.now.stop()
# self.now = None
# if self.inf_play:
# self.now.stop()
# self.now = None
# pass # b_loopの時は、self.nowを停止してself.now = Noneにすると自動的に次の曲になるので.
# elif len(self.queue) > 0:
# self.queue.pop(0)
# if len(self.queue) > 0:
# await VoiceChat.play(self, ctx)
@v_music.command(description='stop')
async def stop(self, ctx):
"""stop music"""
self.state = False # auto play: off
if self.now != None:
self.now.stop()
self.now = None
self.inf_play = False
self.state = False
@v_music.command(description='pause music')
async def pause(self, ctx):
"""pause music"""
if self.now != None and not self.now.is_paused():
self.now.pause()
else:
await Basic.send('No song is currently playing')
@v_music.command(description='resume music')
async def resume(self, ctx):
"""resume paused music"""
if self.now != None and self.now.is_paused():
self.now.resume()
else:
await Basic.send('The son has not been paused')
@v_music.command(description='random play!')
async def b(self, ctx):
"""One song from Mr. B's recommendation"""
self.state = False # auto play: off
self.inf_play = False # stop inf play
if self.now != None:
self.now.stop()
self.now = None
pre_send = await Basic.send(self, ctx, "Now processing...")
brand_n, mm = my_music.get_music() # 1曲ランダムに取り出し
filename_ = await Youtube.ydl_proc(self, ctx, mm['url'], self.ytdl_opts_np)
if filename_:
filename = filename_[0]
filename = await VoiceChat.effect(self, filename) # エフェクト
# await Basic.send(self, ctx, f'`{brand_n}` - `{mm["title"]}`')
await Basic.delete(self, pre_send)
await Basic.send(self, ctx, f'```ini\n[TITLE] {brand_n} - {mm["title"]}\n[ URL ] {mm["url"]}```')
await VoiceChat.voice_send(self, ctx, filename)
@v_music.command(description='infinity random play!')
async def b_loop(self, ctx):
"""infinity random play!"""
self.state = False # auto play: off
if self.now != None:
self.now.stop()
self.now = None
self.inf_play = True # infiniry play: on
music, sagyou_music = my_music.get_my_music()
while self.inf_play:
brand_n, mm = my_music.get_music() # 1曲ランダムに取り出し
pre_send = await Basic.send(self, ctx, "Now processing...")
filename_ = await Youtube.ydl_proc(self, ctx, mm['url'], self.ytdl_opts_np)
if not filename_ and self.now == None: # youtube_dl error
# await Basic.send(self, ctx, 'Error: Youtube.ydl_proc')
await Basic.delete(self, pre_send)
print('Error: Youtube.ydl_proc')
continue
elif self.now == None: # 正常
# try:
filename = filename_[0]
filename = await VoiceChat.effect(self, filename) # エフェクト
# await Basic.send(self, ctx, f'`{brand_n}` - `{mm["title"]}`')
await Basic.delete(self, pre_send)
await Basic.send(self, ctx, f'```ini\n[TITLE] {brand_n} - {mm["title"]}\n[ URL ] {mm["url"]}```')
await VoiceChat.voice_send(self, ctx, filename)
# except:
# await Basic.send(self, ctx, 'Error: Youtube.voice_send')
else:
await Basic.delete(self, pre_send)
break
@v_music.command(description='play')
async def play(self, ctx):
"""play queue"""
self.state = True
try:
if self.now.is_paused(): # 既にpauseされていた場合
self.now.resume()
except: pass
if len(self.queue) <= 0:
await Basic.send(self, ctx, 'queue = Null')
while len(self.queue):
if self.now == None:
# try:
pre_send = await Basic.send(self, ctx, "Now processing...")
next_song_url = self.queue.pop(0)
[next_song_filename] = await Youtube.ydl_proc(self, ctx, next_song_url, self.ytdl_opts)
next_song_filename = await VoiceChat.effect(self, next_song_filename) # エフェクト
split_filename = os.path.basename(next_song_filename).split('.')
split_filename.pop(len(split_filename)-1) # ファイルの拡張子を除く
split_filename.pop(len(split_filename)-1) # youtube id を除く
await Basic.delete(self, pre_send)
await Basic.send(self, ctx, f'```ini\n[TITLE] {"".join(split_filename)}\n[ URL ] {next_song_url}```')
await VoiceChat.voice_send(self, ctx, next_song_filename)
# except:
# await Basic.send(self, ctx, "Error: VoiceChat.play")
# continue
if len(self.queue) <= 0 or not self.state:
break
@v_music.command(description='show queue')
async def queue(self, ctx):
"""show queue"""
if len(self.queue) > 0:
sd = '> | '+str(self.queue[0])+'\n'
for i in range(1, len(self.queue)):
sd += str(i)+' | '+str(self.queue[i])+'\n'
await Basic.send(self, ctx, "```py\n"+sd+"```")
else:
await Basic.send(self, ctx, "queue = Null")
@v_music.command(description='delete queue')
async def del_queue(self, ctx):
"""delete queue"""
self.queue = []
await Basic.send(self, ctx, "deleted queue")
@v_music.command(description='nightcore effect toggle')
async def nightcore(self, ctx):
self.nightcore = True if not self.nightcore else False
await Basic.send(self, ctx, "nightcore = "+str(self.nightcore))
@v_music.command(description='bassboost effect toggle')
async def bassboost(self, ctx):
self.bassboost = True if not self.bassboost else False
await Basic.send(self, ctx, "bassboost = "+str(self.bassboost))
# @v_music.command(description='loop the currently playing music')
# @commands.command(description='play music + kawaii_voice_gtts.music_pack1')
# async def v_music_pack1(self, ctx, tx:str):
# """play music + kawaii_voice_gtts.music_pack1"""
# try: # try connect url
# f = urllib.request.urlopen(tx)
# f.close()
# except: return False
# ytdl_opts = {
# 'format' : 'bestaudio/best',
# # 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
# 'outtmpl': '%(title)s%(id)s.%(ext)s',
# 'restrictfilenames': True,
# 'noplaylist': True, # not allow playlist
# 'nocheckcertificate': True,
# 'no_warnings': True,
# 'default_search': 'auto',
# 'source_address': '0.0.0.0',
# 'postprocessors': [{
# 'key': 'FFmpegExtractAudio',
# 'preferredcodec': 'mp3',
# }]
# }
# if tx.lower() == 'stop' and self.now != None:
# self.now.stop()
# self.now = None
# filename_ = await Youtube.ydl_proc(self, ctx, tx, ytdl_opts)
# if not filename_ and self.now == None:
# await Basic.send(self, ctx, 'Error; Youtube.ydl_proc')
# return False
# elif self.now == None: # 正常
# try:
# filename = filename_[0]
# imouto = kawaii_voice_gtts.kawaii_voice(filename)
# imouto = imouto.music_pack1()
# imouto.audio.export(filename, 'mp3')
# await VoiceChat.voice_send(self, ctx, filename)
# except:
# await Basic.send(self, ctx, 'Error: kawaii_voice_gttx.kawaii_voice, imouto.music_pack1, Youtube.voice_send')
async def make_tts(self, ctx, text, lg, k_option): # text=text, lg=language, k_option=kawaii_voice_gtts(0=false, 1=true)
voice_client = ctx.message.guild.voice_client
text = ' '.join(text)
pool = string.ascii_letters + string.digits
randm = ''.join(random.choice(pool) for _ in range(16))
filename = str(randm) + ".mp3"
gTTS(str(text), lang=lg).save(filename)
if k_option == 1:
imouto = kawaii_voice_gtts.kawaii_voice(filename)
imouto = imouto.pitch(0.4)
imouto.audio.export(filename, 'mp3')
if not voice_client: # join voice channel
await ctx.author.voice.channel.connect()
await VoiceChat.voice_send(self, ctx, filename)
async def effect(self, filename):
if self.nightcore == False and self.bassboost == False: # オプションがない場合
return filename
org_filename = filename
split_filename = os.path.basename(filename).split('.')
split_filename_ext = split_filename.pop(len(split_filename)-1) # ファイルの拡張子を除く
if split_filename_ext != 'mp3':
try:
tmp_audio = ffmpeg.input(filename)
tmp_audio_enc = ffmpeg.output(tmp_audio, str('.'.join(split_filename))+'.mp3', format='mp3')
ffmpeg.run(tmp_audio_enc)
try: os.remove(org_filename) # ファイル形式の変換前のファイルを削除
except Exception as e: print(e)
filename = str('.'.join(split_filename))+'.mp3'
except Exception as e:
print(e)
await bot.get_channel(LOG_C).send(str(e))
# await Basic.send('Error: VoiceChat.effect')
return filename
imouto = kawaii_voice_gtts.kawaii_voice(filename)
if self.nightcore:
imouto = imouto.music_pack1()
if self.bassboost:
imouto = imouto.bass_boost(0)
imouto.audio.export(filename, 'mp3') # 保存
return filename
async def voice_send(self, ctx, filename):
if self.now != None:
self.now.stop()
if os.path.exists(filename): # ファイル存在確認
if self.volume == 1.0: audio_source = discord.FFmpegPCMAudio(filename)
else: audio_source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(filename), volume=self.volume)
self.now = ctx.voice_client
try:
self.now.play(audio_source) # 再生
while ctx.guild.voice_client.is_playing() or ctx.guild.voice_client.is_paused():
await asyncio.sleep(1)
except Exception as e:
print(e)
self.inf_play = False
self.state = False
await bot.get_channel(LOG_C).send(str(e))
# await VoiceChat.v_connect(self, ctx)
os.remove(filename)
self.now = None
@commands.command(description='change music volume')
async def v_volume(self, ctx, vol:str):
"""change music volume"""
try:
if float(vol) > 1.0: vol = 1.0
elif float(vol) < 0: vol = 0.0
self.volume = float(vol)
except:
self.volume = 1.0
await Basic.send(self, ctx, 'volume : '+str(self.volume))
@commands.command(description='Channel member list')
async def v_list(self, ctx):
"""channel member list"""
channel = ctx.author.voice.channel
out = ''
cnt = 1
for ch in channel.guild.voice_channels:
if len(ch.members)>0 and len(out)>0: # メンバーがいて、2番目以降
out += '-\n'
for member in ch.members:
out += str(cnt) +' | '+ str(member) + '\n'
cnt += 1
# await member.move_to(None)
await Basic.send(self, ctx, '```py\n'+out+'```')
@commands.command(description='voice mute')
async def v_mute(self, ctx, no):
"""voice mute. (b = all)"""
channel = ctx.author.voice.channel
if str(no).lower() == 'b': # 全員
for ch in channel.guild.voice_channels:
for member in ch.members:
await member.edit(mute = True)
else: # 通常のミュート
try:
no = int(no)
if no <= 0: return
except: return
cnt = 0
for ch in channel.guild.voice_channels:
for member in ch.members:
cnt += 1