Discord bot discord.py 命令无效

Discord bot discord.py commands aren't working

我对制作 discord 机器人还很陌生,我正在尝试制作一个基本的测试命令,你说 (prefix)test abc,机器人也说 abc。我没有收到任何错误,但是当我输入 r!test abc 时,没有任何反应。我在终端也什么也得不到。

这是我的代码。

import discord

from dotenv import load_dotenv
from discord.ext import commands

load_dotenv()


GUILD = os.getenv('DISCORD_GUILD') # Same thing but gets the server name
client = discord.Client()
bot = commands.Bot(command_prefix='r!')
TOKEN = 'TOKENGOESHERE'
on = "I'm up and running!"
print("Booting up...")
channel = client.get_channel(703869904264101969)

@client.event # idk what this means but you have to do it

async def on_ready(): # when the bot is ready

    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(f'{client.user} has connected to Discord! They have connected to the following server: ' #client.user is just the bot name
    f'{guild.name}(id: {guild.id})' # guild.name is just the server name


    )

    channel2 = client.get_channel(channelidishere)
    await channel2.send(on)
#everything works up until I get to here, when I run the command, nothing happens, not even some output in the terminal.

@commands.command()
async def test(ctx):
    await ctx.send("test")



client.run(TOKEN)

谢谢大家!

关键问题是您没有正确定义装饰器。由于您使用的是命令,因此您只需要 bot = commands.Bot(command_prefix='r!') 语句。不需要 client = discord.Client()。因为它是 bot = ...,所以你所有的装饰器都需要以 @bot 开头。此外,您不会使用 client ,您将使用像 channel2 = bot.get_channel(channelidishere).

这样的机器人

删除了公会循环并将其替换为 discord.utils.get 以获得公会 - guild = discord.utils.get(bot.guilds, name=GUILD)。这需要另一个导入 - import discord

试试这个:

import os
import discord
from dotenv import load_dotenv
from discord.ext import commands

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')  # Same thing but gets the server name
bot = commands.Bot(command_prefix='r!')
on = "I'm up and running!"
print("Booting up...")


@bot.event  # idk what this means but you have to do it
async def on_ready():  # when the bot is ready
    guild = discord.utils.get(bot.guilds, name=GUILD)
    print(
        f'{bot.user} has connected to Discord! They have connected to the following server: '  # client.user is just the bot name
        f'{guild.name}(id: {guild.id})')  # guild.name is just the server name
    channel2 = bot.get_channel(channelidishere)
    await channel2.send(on)


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


bot.run(TOKEN)