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()