You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何解决Discord.py中出现的CommandRegistrationError:The command commands is already an existing command or alias错误?

解决Discord.py的CommandRegistrationError问题

这个报错的核心原因很直白:你自定义的commands命令和discord.py内置的命令重名了!此外你的代码里还有几个小细节问题需要一起修正,我来给你一步步梳理:

问题拆解与修复步骤

  • 命令名冲突:discord.py的commands.Bot类默认已经内置了一个名为commands的命令(用来展示所有已注册命令的帮助信息),所以你不能再用这个名字定义自己的命令。把你的命令改成别的名字,比如cmds或者helpme
  • 重复注册命令:使用@bot.command()装饰器的时候,已经自动把函数注册为Bot的命令了,不需要再手动调用bot.add_command(),重复注册只会引发额外问题,删掉这三行代码:
    bot.add_command(commands)
    bot.add_command(info)
    bot.add_command(users)
    
  • 上下文参数缺失:你的命令函数里直接使用了message,但discord.py的命令函数需要接收ctx(上下文)参数才能获取频道、服务器等信息。把所有命令函数的参数改成ctx,并替换代码里的messagectx
  • 服务器成员计数错误users命令里的id.member_count是错误的,应该用ctx.guild.member_count来获取当前服务器的成员数量。
  • 多余的Client实例commands.Botdiscord.Client的子类,你不需要同时创建两个客户端实例,删掉client = discord.Client()client.run(token),改用bot.run(token)启动机器人。

修正后的完整代码

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='$')

def read_token():
    with open("token.txt", "r") as f:
        lines = f.readlines()
        return lines[0].strip()

token = read_token()

@bot.command(name="cmds")  # 重命名避免冲突
async def cmds(ctx):
    embed = discord.Embed(title="Commands")
    embed.add_field(name="$info", value="Shows info about the bot", inline=False)
    embed.add_field(name="$users", value="Shows how many members the server has", inline=False)
    await ctx.channel.send(content=None, embed=embed)

@bot.command()
async def info(ctx):
    await ctx.channel.send("Bot feito por Ra'Ed#2931")

@bot.command()
async def users(ctx):
    await ctx.channel.send(f"""Esse server tem {ctx.guild.member_count} membros""")

bot.run(token)

这样修改后,你的机器人就能正常运行,不会再出现命令注册冲突的报错啦!

内容的提问来源于stack exchange,提问作者RaEd

火山引擎 最新活动