You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py改用ctx编写命令后无法加载,更新代码仍失效求助

Discord机器人ctx命令无法加载的解决办法

核心问题及修复方案

  • 命令前缀冲突
    你把传统ctx命令的前缀设为/,但Discord会优先将/开头的内容识别为Slash交互命令,而非discord.py的传统前缀命令。修改命令前缀为非/的符号,比如!:

    bot = commands.Bot(command_prefix="!", intents = discord.Intents.all())
    

    之后用户输入!hello就能触发对应命令。

  • 错误使用ephemeral参数
    传统ctx.send()方法不支持ephemeral=True(这是Slash命令专属参数),会导致命令执行报错,甚至影响命令加载。直接删除该参数:

    @bot.command(description="Support Invite")
    async def support(ctx):
        await ctx.send(f"{ctx.author.mention} 请加入我们的服务器获取支持![invite]")
    
  • 开启后台Intents权限
    即使代码里写了Intents.all(),也必须在Discord开发者后台的机器人页面,手动开启Message Content Intent权限,否则机器人无法接收用户消息,命令自然触发不了。

  • 移除无效的sync命令
    sync是用来同步Slash交互命令的,对传统ctx命令完全没用,直接删除该命令即可。

修改后的完整代码示例

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents = discord.Intents.all())

@bot.event
async def on_ready():
    print(f'机器人已成功登录:{bot.user}')
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"Chilling Music - {len(bot.guilds)}"))

# 命令
@bot.command(description="打招呼")
async def hello(ctx):
    await ctx.send(f"Hello {ctx.author.mention}!")

@bot.command(description="播放音乐")
async def play(ctx, song_name : str):
    # 增加判断,避免用户不在语音频道时报错
    if not ctx.author.voice:
        await ctx.send("你得先加入一个语音频道!")
        return
    await ctx.author.voice.channel.connect()
    await ctx.send(f"正在播放:{song_name}")

@bot.command(description="查看服务器数量")
async def servercount(ctx):
    await ctx.send(f"Chill Bot 已加入 {len(bot.guilds)} 个服务器!")

@bot.command(description="查看机器人延迟")
async def ping(ctx):
    await ctx.send(f"🏓Pong\nChill Bot 的延迟是\n{round(bot.latency * 1000)} ms")

@bot.command(description="发送公告")
async def announce(ctx, *, message : str):  # 加*支持带空格的长消息
    await ctx.send(message)

@bot.command(description="获取支持服务器邀请")
async def support(ctx):
    await ctx.send(f"{ctx.author.mention} 请加入我们的服务器获取支持![invite]")

bot.run('你的机器人Token')

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:25:20