File size: 23,664 Bytes
14dabf7 | 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 | import discord
from discord.ext import commands
import json
import os
from yt_dlp import YoutubeDL
import random
import asyncio
import ssl
import psutil
import math
import random
import requests
#import wavelink
from ffmpeg import *
from URL import URLwrite#URL関連モジュール
from URL import get_multiple_urls#title取得複数化
from URL import get_url#title取得
import dl#yt-dlp関連モジュール
ssl._create_default_https_context = ssl._create_unverified_context
#discord botの権限
intents = discord.Intents.all()
intents.message_content = True
intents.members = True
intents.voice_states= True
bot = commands.Bot(command_prefix='k/',case_insensitive=True, intents=intents)#クライアント
#非常用
password1 = 000000
id = 956061385777881108
@bot.command(name="password")
async def hoge(ctx):
global password1
password1 = ''.join(random.choices('0123456789', k=6))
if ctx.author.id==id:
embed = discord.Embed(title="Password",description=password1+"\n 構文 k/emergency id Type password",color=0x00ffb7)
else:
embed = discord.Embed(title="Password",description="passwordをkatasouに送信しました。\n 構文 k/emergency id Type password",color=0x00ffb7)
ctx.send(embed=embed)
ka = bot.get_user(id)
ch = await ka.create_dm()
embed = discord.Embed(title="Password",description=password1,color=0x00ffb7)
ch.send(embed=embed)
@bot.command(name="emergency")
async def hoge(ctx,id:int,Type:str,password:int):
#type role,mute,time
if not password1==password:
embed = discord.Embed(title="認証失敗",description="認証コードが不正です。",color=0xff0000)
ctx.send(embed=embed)
return
if Type=="role":
#管理者権限role
pass
elif Type=="mute":
#鯖ミュート解除
pass
elif Type=="time":
#タイムアウト解除
pass
else:
embed = discord.Embed(title="Error",description="Typeが不正です。",color=0xff0000)
ctx.send(embed=embed)
#通常コマンド
@bot.hybrid_command(name="ping",description="鯖との接続ラグを表示します。")
async def hoge(ctx):
embed = discord.Embed(title="Pong!",description=str(bot.latency*1000)+"ms",color=0xa9ceec)
await ctx.send(embed=embed)
@bot.hybrid_command(name="status",description="現在の鯖の状況を表示します。")
async def hoge(ctx):
sta = pc()
embed = discord.Embed(title="Status",description="鯖の現在状況",color=0xa9ceec)
embed.add_field(name="鯖の所在地",value=str(sta[9]),inline=False)
embed.add_field(name="CPU使用率",value=str(sta[0])+"%",inline=False)
embed.add_field(name="メモリ使用率",value=str(sta[4])+"%",inline=False)
embed.add_field(name="実装メモリ",value=str(sta[1]),inline=True)
embed.add_field(name="メモリ使用量",value=str(sta[2]),inline=True)
embed.add_field(name="利用可能",value=str(sta[3]),inline=True)
embed.add_field(name="ストレージ使用率",value=str(sta[8])+"%",inline=False)
embed.add_field(name="実装ストレージ",value=str(sta[5]),inline=True)
embed.add_field(name="ストレージ使用量",value=str(sta[6]),inline=True)
embed.add_field(name="利用可能",value=str(sta[7]),inline=True)
await ctx.send(embed=embed)
@bot.hybrid_command(name="hello",description="Helloと返す")
async def hoge(ctx):
embed = discord.Embed(title="Hello",color=0xa9ceec)
await ctx.send(embed=embed)
@bot.hybrid_command(name="join",description="使用者が接続しているボイスチャンネルに接続する")
async def hoge(ctx):
if ctx.author.voice is None:#エラー使用者未接続
embed = discord.Embed(title="先にボイスチャンネルに接続してください。",color=0xff0000)
await ctx.send(embed=embed)
elif not ctx.guild.voice_client==None:#エラー接続済み
embed = discord.Embed(title="既に接続済みです。",color=0xff0000)
await ctx.send(embed=embed)
else:
await ctx.author.voice.channel.connect()#接続
embed = discord.Embed(title="接続しました。",color=0x5AFF19)
await ctx.send(embed=embed)
#list初期化
with open(str(ctx.guild.id)+".txt", "w") as f:
pass
data = {"status": "none", "url": "none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
if str(ctx.guild.voice_client.channel.type)=="stage_voice":#接続先がステージチャンネルならスピーカーになる
member = ctx.author.guild.me
await member.edit(suppress=False)
@bot.hybrid_command(name="leave",description="ボイスチャンネルから切断する")
async def hoge(ctx):
if ctx.guild.voice_client is None:#エラー未接続
embed = discord.Embed(title="ボイスチャンネルに接続していません",color=0xff0000)
await ctx.send(embed=embed)
return
await ctx.guild.voice_client.disconnect()#切断
#discord.VoiceProtocol.cleanup()
embed = discord.Embed(title="切断しました",color=0x5AFF19)
await ctx.send(embed=embed)
with open(str(ctx.guild.id)+".txt", "w") as f:
pass
data = {"status": "end", "url": "none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
def awaitable_voice_client_play(func, player, loop):
f = asyncio.Future()
after = lambda e: loop.call_soon_threadsafe(lambda: f.set_result(e))
func(player, after=after)
return f
@bot.hybrid_command(name="play",description="音楽を再生する。")
async def hoge(ctx,url:str):#音声関連
guild_id=str(ctx.guild.id)
if ctx.guild.voice_client is None:
embed = discord.Embed(title="ボイスチャンネルに接続していません",color=0xff0000)
await ctx.send(embed=embed)
return
await ctx.defer()#処理待ちコマンド
urlwrite = URLwrite(url,guild_id)#playlistに書き込み&返信
if urlwrite[1] != "Error":
if urlwrite[1] == "Video":
info = dl.get_video_info(urlwrite[0])
embed = discord.Embed(title="Playlistに追加しました。",color=0x006dca)
embed.add_field(name=urlwrite[1],value=info[0],inline=False)
embed.add_field(name="URL",value=urlwrite[0],inline=False)
if not url.startswith("https://podcasts.google.com"):
embed.set_thumbnail(url=info[1])
await ctx.send(embed=embed)
else:
info = dl.get_playlist_info(urlwrite[0])
if not info[0]=="Error":
embed = discord.Embed(title="Playlistに追加しました。",color=0x006dca)
embed.add_field(name=urlwrite[1],value=info[0],inline=False)
embed.add_field(name="URL",value=urlwrite[0],inline=False)
embed.set_thumbnail(url=info[1])
await ctx.send(embed=embed)
else:
embed = discord.Embed(title="再生エラー "+urlwrite[0],description='''
playlist中のすべてのvideoが
bot起動中の鯖所在地の国で再生できない。
またはメン限の可能性もあり。
もしくは、有料serviceの可能性あり。
''',color=0xff0000)
await ctx.send(embed=embed)
return
else:#エラー
embed = discord.Embed(title="URLエラー",description='''URLが正しくない可能性があります。
video,playlistが未公開設定になっている可能性があります。
もしくは、そのserviceが未対応な可能性があります。
''',color=0xff0000)
await ctx.send(embed=embed)
return
if not os.path.exists(guild_id+".json"):#Statusjson存在しない
data = {"status": "none", "url": "none"}
with open(guild_id+".json", "w") as f:
json.dump(data, f, indent=4)
with open(guild_id+".json", "r") as f:
data = json.load(f)
if data["status"]=="none":#再生開始
with open(guild_id+".txt", "r") as f:
url = f.readline().rstrip()
data = {"status": "play", "url": url}
with open(guild_id+".json", "w") as f:
json.dump(data, f, indent=4)
#再生しょり
print("再生")
if str(ctx.guild.voice_client.channel.type)=="stage_voice":#接続先がステージチャンネルならスピーカーになる
member = ctx.author.guild.me
await member.edit(suppress=False)
if not url.startswith("https://www.nicovideo.jp"):
try:
t = True
info = YoutubeDL().extract_info(url, download=False)
except:
t= False
embed = discord.Embed(title="再生エラー "+url,description='''
videoがbot起動中の鯖所在地の国で再生できない。
またはメン限の可能性もあり。
もしくは、有料serviceの可能性あり。
''',color=0xff0000)
await ctx.channel.send(embed=embed)
if t:
player = await YTDLSource.from_url(url,loop=bot.loop,stream=True,volume=0.2)
player.original.seek(**ffmpeg_options,seek_time="0:00")
embed = discord.Embed(title=info["title"]+"を再生します",color=0x006dca)
await ctx.channel.send(embed=embed)
await awaitable_voice_client_play(ctx.voice_client.play,player,bot.loop)
else:
info = YoutubeDL().extract_info(url, download=False)
embed = discord.Embed(title=info["title"]+"を再生します",color=0x006dca)
await ctx.channel.send(embed=embed)
player, niconico = await NicoNicoDLSource.from_url(url, log=True, volume=0.2)
await awaitable_voice_client_play(ctx.voice_client.play,player,bot.loop)
niconico.close()
while True:
if not ctx.guild.voice_client is None:#再生中なら
with open(str(ctx.guild.id)+".json", "r") as f:
data = json.load(f)
if not data["status"] =="stop":
print("再生終了")
with open(guild_id+".txt", "r") as f:
lines = f.readlines()
with open(guild_id+".txt", "w") as f:
for line in lines[1:]:
f.write(line)#一行目削除
with open(guild_id+".txt", "r") as f:#再生リストの中身確認
line_count = sum(1 for _ in f)
if line_count == 0:#中身なし
with open(str(ctx.guild.id)+".json", "r") as f:
data = json.load(f)
if data["status"]=="one":
data = {"status":"none", "url":"none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
embed = discord.Embed(title="ボイスチャンネルから人がいなくなったため切断します。",color=0x006dca)
await ctx.channel.send(embed=embed)
elif not data["status"]=="end":
data = {"status":"none", "url":"none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
embed = discord.Embed(title="Playlistの中身をすべて再生しました。",color=0x006dca)
await ctx.channel.send(embed=embed)
else:
data = {"status":"none", "url":"none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
break#再生終了の知らせを出し止める
with open(guild_id+".txt", "r") as f:
url = f.readline().rstrip()
data = {"status": "play", "url": url}#ステータス更新
with open(guild_id+".json", "w") as f:
json.dump(data, f, indent=4)
if str(ctx.guild.voice_client.channel.type)=="stage_voice":#接続先がステージチャンネルならスピーカーになる
member = ctx.author.guild.me
await member.edit(suppress=False)
if not url.startswith("https://www.nicovideo.jp"):
try:
t = True
info = YoutubeDL().extract_info(url, download=False)
except:
t= False
embed = discord.Embed(title="再生エラー "+url,description='''
videoがbot起動中の鯖所在地の国で再生できない。
またはメン限の可能性もあり。
もしくは、有料serviceの可能性あり。
''',color=0xff0000)
await ctx.channel.send(embed=embed)
if t:
player = await YTDLSource.from_url(url,loop=bot.loop,stream=True,volume=0.2)
player.original.seek(**ffmpeg_options,seek_time="0:00")
embed = discord.Embed(title=info["title"]+"を再生します",color=0x006dca)
await ctx.channel.send(embed=embed)
await awaitable_voice_client_play(ctx.voice_client.play,player,bot.loop)
else:
info = YoutubeDL().extract_info(url, download=False)
embed = discord.Embed(title=info["title"]+"を再生します",color=0x006dca)
await ctx.channel.send(embed=embed)
player, niconico = await NicoNicoDLSource.from_url(url, log=True, volume=0.2)
await awaitable_voice_client_play(ctx.voice_client.play,player,bot.loop)
niconico.close()
else:#中断または再生
return
@bot.hybrid_command(name="clear",description="playlistの中身を削除します。")
async def hoge(ctx):
embed = discord.Embed(title="削除しました",color=0x5AFF19)
await ctx.send(embed=embed)
with open(str(ctx.guild.id)+".txt", "w") as f:
pass
data = {"status": "none", "url": "none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
@bot.hybrid_command(name="skip",description="現在再生している曲をskipします。")
async def hoge(ctx):
with open(str(ctx.guild.id)+".json", "r") as f:
data = json.load(f)
embed = discord.Embed(title="Skip:"+data["url"],color=0x5AFF19)
await ctx.send(embed=embed)
data = {"status": "play", "url": "none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
ctx.guild.voice_client.stop()
@bot.hybrid_command(name="shuffle",description="playlistの中身をシャッフルします。")
async def hoge(ctx):
guild_id = str(ctx.guild.id)
embed = discord.Embed(title="シャッフルしました。",color=0x5AFF19)
await ctx.send(embed=embed)
with open(str(ctx.guild.id)+".txt", "r") as file:
lines = file.readlines()
shuffled_lines = lines[0:1] + random.sample(lines[1:], len(lines) - 1)
with open(str(ctx.guild.id)+".txt", "w") as file:
file.writelines(shuffled_lines)
@bot.hybrid_command(name="pause",description="再生を一時停止します。")
async def hoge(ctx):
embed = discord.Embed(title="再生停止 :pause_button:",color=0x5AFF19)
with open(str(ctx.guild.id)+".json", "r") as f:
data1 = json.load(f)
data = {"status": "stop", "url":data1["url"]}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
ctx.guild.voice_client.pause()
await ctx.send(embed=embed)
@bot.hybrid_command(name="resume",description="再生を開始します。")
async def hoge(ctx):
if ctx.guild.voice_client.is_paused():
with open(str(ctx.guild.id)+".json", "r") as f:
data1 = json.load(f)
data = {"status": "play", "url":data1["url"]}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
ctx.guild.voice_client.resume()
embed = discord.Embed(title="再生開始 :arrow_forward:",color=0x5AFF19)
await ctx.send(embed=embed)
@bot.hybrid_command(name="stop",description="再生を終了します。")
async def hoge(ctx):
if ctx.guild.voice_client.is_playing():
embed = discord.Embed(title="再生終了 :stop_button:",color=0x5AFF19)
await ctx.send(embed=embed)
with open(str(ctx.guild.id)+".txt", "w") as f:
pass
data = {"status": "end", "url": "none"}
with open(str(ctx.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
ctx.guild.voice_client.stop()
@bot.hybrid_command(name="manual",description="コマンド一覧を表示")
async def hoge(ctx):#マニュアル
embed = discord.Embed(title="コマンド一覧",color=0xa9ceec)
embed.add_field(name="コマンド一覧を表示",value="/manual",inline=False)
embed.add_field(name="helloを返す",value="/hello",inline=False)
embed.add_field(name="ボイスチャンネルに接続",value="/join",inline=False)
embed.add_field(name="ボイスチャンネルから切断",value="/leave",inline=False)
embed.add_field(name="playlistに曲を追加",value="/play URL",inline=False)
embed.add_field(name="曲を一時停止",value="/pause",inline=False)
embed.add_field(name="一時停止を解除",value="/resume ",inline=False)
embed.add_field(name="playlistをシャッフル",value="/shuffle",inline=False)
embed.add_field(name="再生を終了",value="/stop",inline=False)
embed.add_field(name="playlistの中身を消去",value="/clear",inline=False)
embed.add_field(name="playlistの中身を表示",value="/queue" ,inline=False)
await ctx.send(embed=embed)
@bot.hybrid_command(name="queue",description="playlistの内容を表示")
async def hoge(ctx):
if not ctx.guild.voice_client is None:
embed = discord.Embed(title="Now loading.",color=0x006dca)
await ctx.send(embed=embed)
with open(str(ctx.guild.id)+".txt", "r") as file:
lines = file.readlines()
n = len(lines)
print(lines)
with open(str(ctx.guild.id)+".json", "r") as f:
data = json.load(f)
if data["status"]=="play":
title=get_url(lines[0])
txt = "Now playing \n"+title+"\n\n"
elif data["status"]=="stop":
title=get_url(lines[0])
txt ="Now stopped \n"+title+"\n\n"
if n>= 11:
n = 1
urls = []
for url in lines[n:n+10]:#1~10
urls.append(url)
titles = get_multiple_urls(urls)
for title in titles:
txt =txt+(title)+"\n"
embed = discord.Embed(title="Playlist",description=txt,color=0x006dca)
await ctx.channel.send(embed=embed)
remainder = len(lines) % 10 #あまり
for i in range(len(lines)//10):#ループ
n=n+11
txt = ""
urls = []
for url in lines[n:n+10]:#1~10
urls.append(url)
titles = get_multiple_urls(urls)
for title in titles:
txt =txt+(title)+"\n"
embed = discord.Embed(title="Playlist",description=txt,color=0x006dca)
await ctx.channel.send(embed=embed)
txt = ""
n=n+11
urls = []
for url in lines[n:n+10]:#1~10
urls.append(url)
titles = get_multiple_urls(urls)
for title in titles:
txt =txt+(title)+"\n"
embed = discord.Embed(title="Playlist",description=txt,color=0x006dca)
await ctx.channel.send(embed=embed)
return
else:
lines.pop(0)
urls = []
for url in lines:
urls.append(url)
titles = get_multiple_urls(urls)
for title in titles:
txt =txt+(title)+"\n"
embed = discord.Embed(title="Playlist",description=txt,color=0x006dca)
await ctx.channel.send(embed=embed)
return
else:
embed = discord.Embed(title="ボイスチャンネルに接続していません",color=0xff0000)
await ctx.send(embed=embed)
return
@bot.event#自動退出
async def on_voice_state_update(member,before,after):
if member.guild.voice_client==None:
return
if before.channel is not None and before.channel:
members = [i.id for i in member.guild.voice_client.channel.members]
if len(members)==1:
if members[0]==bot.user.id:
await member.guild.voice_client.disconnect()#切断
with open(str(member.guild.id)+".txt", "w") as f:
pass
data = {"status": "one", "url": "none"}
with open(str(member.guild.id)+".json", "w") as f:
json.dump(data, f, indent=4)
def convert_size(size):
units = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB")
i = math.floor(math.log(size, 1024)) if size > 0 else 0
size = round(size / 1024 ** i, 2)
return f"{size} {units[i]}"
def pc():
c= psutil.cpu_percent()
#print(psutil.cpu_stats())
#print(psutil.cpu_freq())
mt = convert_size(psutil.virtual_memory().total)
mu = convert_size(psutil.virtual_memory().used)
ma = convert_size(psutil.virtual_memory().available)
mp = psutil.virtual_memory().percent
st = convert_size(psutil.disk_usage(path='/').total)
su = convert_size(psutil.disk_usage(path='/').used)
sf = convert_size(psutil.disk_usage(path='/').free)
sp = psutil.disk_usage(path='/').percent
geo_request_url = 'https://get.geojs.io/v1/ip/geo.json'
data = requests.get(geo_request_url).json()
sc = data['country']+"/"+data['region']
print(c,mt,mu,ma,mp,st,su,sf,sp,sc)
return c,mt,mu,ma,mp,st,su,sf,sp,sc
@bot.event#discordに接続完了でたたかれる
async def on_ready():
await bot.tree.sync()#/コマ同期
print("bot is on ready")
def run():#bot起動関連
bot.run(os.getenv("token"))
#bot.run("")
import platform
if platform.system()=="Windows":
run()
else:
from threading import Thread
Thread(target=run).start()
from pathlib import Path
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown(Path('landing.md').read_text())
demo.launch() |