Discord Python 机器人运行时警告:协程“Client.run.<locals>.runner”从未等待过

问题描述 投票:0回答:1

我有一个不和谐的机器人,它有几个运行良好的扩展。我把它放了几个月,现在不起作用了 我有这个错误,不知道如何解决: “...引发错误。来自 e 的ExtensionFailed(key, e) Discord.ext.commands.errors.ExtensionFailed:扩展“更改”引发错误:RuntimeError:asyncio.run() 无法从正在运行的事件循环中调用 sys:1:运行时警告:从未等待协程“Client.run..runner””

我尝试遵循指南,现在我的主文件中有这个:

import discord
from discord.ext import commands
import mysql.connector


#connections with databases...


class CustomBot(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix="gg",
            intents=discord.Intents.all()
        )

    async def setup_hook(self):
        await self.load_extension("change")

CustomBot().run("mytoken")

以及我的一个扩展中的类似内容:

import discord
from discord.ext import commands
from ggbot import conexion_inventarios, conexion_juegos, tablas_suffix


#connections with databases


class MiComandoCog1(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    

    @commands.command()
    async def emoji(self, ctx, emoji: discord.Emoji):
        await ctx.send(f":{emoji.name}:{emoji.id}")


    @commands.command()
    async def change(self, ctx, columna_a_cambiar, nombre_encontrar, valor):
        for sufijo in tablas_suffix:
            cursor_juegos.execute(f"SELECT {columna_a_cambiar} FROM per_{sufijo} WHERE nombres = '{nombre_encontrar}'")
            resultado = cursor_juegos.fetchone()
        
            if resultado is not None:
                cursor_juegos.execute(f"UPDATE per_{sufijo} SET {columna_a_cambiar} = '{valor}' WHERE nombres = '{nombre_encontrar}'")
                conexion_juegos.commit()
        await ctx.send("Valores cambiados.")


    # more commands...
        

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.guild and message.guild.me.guild_permissions.ban_members:
            await message.author.ban(reason="no speek")
        
    async def cog_load(self):
        print(f"{self.__class__.__name__} loaded!")

    async def cog_unload(self):
        print(f"{self.__class__.__name__} unloaded!")    

async def setup(bot):
    await bot.add_cog(MiComandoCog1(bot=bot))`
python discord discord.py bots runtime-error
1个回答
0
投票

当您尝试在异步上下文之外运行 Discord 机器人时,通常会出现错误消息

RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
。这是因为 `setup_hook 函数是异步的,不能在这样的上下文之外使用。

要解决此问题,最好在异步上下文中启动机器人:

.. your code ..


# Login to Discord
bot = CustomBot()
async def login() -> None:
    async with bot:
        await bot.start("token")


# Don't run the login twice
if __name__ == "__main__":
    done = asyncio.run(login())

您还应该确保您的 Cog 文件名为

change
并且应位于与主文件相同的文件夹中 - 否则他找不到扩展名。

顺便说一句:Discord.py 在其 Github 存储库上提供了许多如何使用该库的简单示例:https://github.com/Rapptz/discord.py/tree/master/examples

© www.soinside.com 2019 - 2024. All rights reserved.