#python #python-3.x #discord #discord.py
#python #python-3.x #Discord #discord.py
Вопрос:
Я перенес своего бота discord на использование MySQL вместо хранения данных в файлах json. Единственная проблема, с которой я столкнулся сейчас, это когда я пытаюсь загрузить музыкальное расширение бота… Код:
import discord
import lavalink
from discord import Guild
from discord import User
from discord.ext import commands
# from bot import get_musicchannel
# from bot import get_prefix
from bot import mycursor
def get_musicchannel(guild: Guild):
# with open("cogs/music.json") as f:
# channels = json.load(f)
# channel: TextChannel = discord.utils.get(guild.text_channels, id=channels[str(guild.id)])
# return channel.id
sqlcommand = "SELECT channelid FROM musicchannels WHERE guildid = %s"
vals = (guild.id,)
mycursor.execute(sqlcommand, vals)
result = mycursor.fetchall()
strchannelid = str(result[0]).replace("(", "").replace(")", "").replace(",", "")
channelid = int(strchannelid)
return channelid
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.music = lavalink.Client(self.bot.user.id)
self.bot.music.add_node("IP", 2333, 'PASS', 'eu', 'music-node')
self.bot.add_listener(self.bot.music.voice_update_handler, 'on_socket_response')
self.bot.music.add_event_hook(self.track_hook)
@commands.command(name="music")
async def music(self, ctx, opt, *, arg=None):
if ctx.message.channel.id != get_musicchannel(ctx.guild):
# channel = get_musicchannel(ctx.guild)
actual_channel = discord.utils.get(ctx.guild.text_channels, id=get_musicchannel(ctx.guild))
return await ctx.send(f"Music commands can only be used in the music channel ({actual_channel.mention})")
if opt == "join":
member = discord.utils.find(lambda m: m.id == ctx.author.id, ctx.guild.members)
if member is not None and member.voice is not None:
vc = member.voice.channel
player = self.bot.music.player_manager.create(ctx.guild.id, endpoint=str(ctx.guild.region))
if not player.is_connected:
player.store('channel', ctx.guild.id)
await self.connect_to(ctx.guild.id, str(vc.id))
# Unimportant code
async def track_hook(self, event):
if isinstance(event, lavalink.events.QueueEndEvent):
guild_id = int(event.player.guild_id)
await self.connect_to(guild_id, None)
async def connect_to(self, guild_id: int, channel_id: int):
ws = self.bot._connection._get_websocket(guild_id)
await ws.voice_state(str(guild_id), channel_id)
async def disconnect_from(self, guild_id: int):
ws = self.bot._connection.voice_clients
print(ws)
def setup(bot):
bot.add_cog(Music(bot))
Когда я пытаюсь запустить бота, он выдает мне эту ошибку:
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", line 668, in run
loop.run_forever()
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libasynciowindows_events.py", line 314, in run_forever
assert self._self_reading_future is None
AssertionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", line 93, in _cleanup_loop
_cancel_tasks(loop)
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", line 78, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libasynciobase_events.py", line 592, in run_until_complete
self._check_running()
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libasynciobase_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordextcommandsbot.py", line 607, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:FicheirosPastasTudoCodingPythonProjectsServer-Utilscogsmusic.py", line 11, in <module>
from bot import mycursor
File "D:FicheirosPastasTudoCodingPythonProjectsServer-Utilsbot.py", line 1383, in <module>
bot.run(TOKEN)
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", line 674, in run
_cleanup_loop(loop)
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", line 98, in _cleanup_loop
loop.close()
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libasyncioproactor_events.py", line 674, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", line 312, in _run_event
await coro(*args, **kwargs)
File "D:/Ficheiros/Pastas/Tudo/Coding/Python/Projects/Server-Utils/bot.py", line 421, in on_ready
bot.load_extension('cogs.music')
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordextcommandsbot.py", line 664, in load_extension
self._load_from_module_spec(spec, name)
File "C:UsersxlysaAppDataLocalProgramsPythonPython38-32libsite-packagesdiscordextcommandsbot.py", line 610, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music' raised an error: RuntimeError: Cannot close a running event loop
Process finished with exit code 0
Событие on_ready просто имеет bot.load_extension('cogs.music')
вот откуда возникает ошибка
Я не знаю, что я могу сделать, чтобы запустить это… Помощь приветствуется.