使用类制作discord bot来实现简单的hello功能

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

我编写的代码工作正常,但是当我在频道上调用 .hello 时,它给了我错误

import discord 
from discord.ext import commands

class Bot(commands.Bot):
    async def on_ready(self):
        print(f"bot {self.user.display_name} started succesfully!!")

    @commands.command()
    async def hello(self, ctx):
        await ctx.send(f'hello {ctx.author.display_name}')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.add_command(self.hello)

intents= discord.Intents.default()
intents.message_content= True
bot= Bot(command_prefix= '.', intents= intents)

tokn= 'MTE5MzU5NDM5ODI0NDYxODI3MA.GpvNRT.T1kNBXpP3egZ_g3a-8hOhYrmzzPIMtYGSOdPro'

bot.run(tokn) 

它给我的错误

Traceback (most recent call last):
  File "C:\Users\risha\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped      
    ret = await coro(*args, **kwargs)
TypeError: Bot.hello() missing 1 required positional argument: 'ctx'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\risha\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke       
    await ctx.command.invoke(ctx)
  File "C:\Users\risha\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke      
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\risha\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped      
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Bot.hello() missing 1 required positional argument: 'ctx'

我运行这段代码并且它有效。我在聊天中使用 .help 它显示你好 作为一个选项,但当我使用 .hello 时,它不会给我重播并抛出上面的错误。 请指导我找到解决方案并告诉我我做错了什么。

python-3.x discord discord.py bots
1个回答
0
投票

您的项目有点混乱,但是经过一些清理,就可以运行 hello 命令。

您尝试在类中创建机器人,这似乎不是discord.py建议您使用其库创建机器人的方式 - 请参阅discord.py/quickstart

下面是代码的修改版本,更符合前面提到的链接中提供的示例。

import discord 
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True
intents.message_content = True

token = ''
bot = commands.Bot(command_prefix='.', intents=intents)

@bot.event
async def on_ready():
    print(f"bot {bot.user.display_name} started successfully!")

@bot.command()
async def hello(ctx):
    await ctx.send(f'hello {ctx.author.display_name}')

bot.run(token)

.hello 和 .help 命令的执行如下所示:

.你好

.帮助

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