我无法使用discord.py将命令添加到我的discord机器人中

时间:2018-06-22 05:14:02

标签: python python-3.x bots discord discord.py

这是我的代码:

from discord.ext import commands
import discord
import config

class Bot(commands.AutoShardedBot):

    def __init__(self):
        super().__init__(command_prefix="~")

    @commands.command()
    async def test(self, ctx):
        await ctx.send("some random text")

    def run(self):
        super().run(config.TOKEN)


if __name__ == "__main__":
    bot = Bot()
    bot.run()

因此,现在,当我键入~test时,它应该以{{1​​}}进行响应,但此错误消息会在终端中弹出:

some random text

我看不到我做错了。

2 个答案:

答案 0 :(得分:1)

Discord.py当前无法自动注册Client修饰的@commands.command()子类中的命令。但是,您仍然可以手动将它们添加到__init__或将要运行的任何位置:

class Bot(commands.AutoShardedBot):

    def __init__(self):
        super().__init__(command_prefix="~")
        self.add_command(commands.Command("test", self.test))
        # or uglier:
        self.command()(self.test)

    async def test(self, ctx):
        await ctx.send("some random text")

如果愿意,您仍然可以使用装饰器(我更喜欢这种方式,因为它更加简单):

class Bot(commands.AutoShardedBot):

    def __init__(self):
        super().__init__(command_prefix="~")
        self.add_command(self.test)

    @commands.command()
    async def test(self, ctx):
        await ctx.send("some random text")

如果您要使用许多初始命令并且懒于为每个命令调用add_command,则可以执行以下操作:

import inspect

class Bot(commands.AutoShardedBot):
    def __init__(self):
        super().__init__(command_prefix="~")

        members = inspect.getmembers(self)
        for name, member in members:
            if isinstance(member, commands.Command):
                if member.parent is None:
                    self.add_command(member)

    @commands.command()
    async def test(self, ctx):
        await ctx.send("some random text")

    @commands.command()
    async def test2(self, ctx):
        await ctx.send("some random text2")

    @commands.command()
    async def test3(self, ctx):
        await ctx.send("some random text3")

答案 1 :(得分:0)

尝试做:

ma​​in.py

import discord
import os

client = discord.Client

@client.event
async def on_message(message):
if message.content.startswith("!hello")
await message.channel.send("hello!")

client.run(os.getenv("TOKEN"))

.env

TOKEN=paste your token here