如何正确地在 class 中创建 discord.Client 并将 运行 作为循环中的任务?

How can I make discord.Client in a class correctly and run as a task in my loop?

我正在使用 Discord.py,我需要在我自己的循环中制作 discord.Client 运行,因为我希望它 运行 多次(更多机器人,所以我不必制作越来越多的文件,这样它们就可以同时运行)。

这是我能做的最简单的例子:

import discord
import asyncio
from discord.ext import commands

token = "token"

class Client(discord.Client):
    
    @commands.Cog.listener()
    async def on_ready():
        print(self.user.id)
    
    @commands.command()
    async def testing(ctx):
        await ctx.send("hello")

loop = asyncio.get_event_loop()
client = Client(command_prefix="!")
loop.create_task(client.start(token))
loop.run_until_complete

它根本 return 什么都没有;它只是自行关闭。我知道我在那里有错误,但我不知道是哪个错误以及为什么。我该如何修复它们?

首先,您要混合使用 discord.Client 和命令。Bot/commands.Cog

class Client(discord.Client):

应该是

class Client(commands.Cog):

并尝试通过循环 运行 多个机器人不会顺利进行。我强烈建议您制作多个文件。

另外,应该是:

def setup(client):
    client.add_cog(Client(client))

如果你要让它成为一个齿轮,那么你必须将它加载到另一个文件中。

如果您只想要一个单一文件,那么它应该如下所示:

class Client(commands.Bot):
    @bot.event
    async def on_ready():
        print(self.user.id)

    @bot.command()
    async def testing(ctx):
        await ctx.send("hello")

client = Client(command_prefix="!")
client.run(token)