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

Python开发Discord机器人Slash Commands无法显示问题求助

问题原因及解决方案

核心问题

你的代码没有将斜杠命令同步到Discord服务器。Discord的斜杠命令必须显式完成同步流程,服务器才能识别并展示这些命令,这是命令不显示的关键原因。

修改后的代码

在on_ready事件中添加命令同步逻辑,同时避免重复同步:

import discord
from discord import app_commands
from discord import Interaction

intents = discord.Intents.all()
intents.message_content = True
bot = discord.Client(command_prefix='!', intents=intents)
tree = app_commands.CommandTree(bot)
# 标记是否已完成同步,防止每次重启重复执行
synced = False

@bot.event
async def on_ready():
    global synced
    print('Logged in!')
    await bot.change_presence(activity=discord.Game('is playing'), status=discord.Status.online)
    # 执行命令同步
    if not synced:
        # 全局同步(对所有服务器生效,可能需要1-2小时才能显示)
        await tree.sync()
        # 测试阶段推荐用指定服务器同步(立即生效,替换成你的服务器ID)
        # await tree.sync(guild=discord.Object(id=1234567890))
        synced = True
        print("命令已同步!")

@tree.command(name='test', description='this is just a simple reply test')
async def test(interaction: Interaction):
    await interaction.response.send_message(f'test has worked, {interaction.user.mention}')

@tree.command(name='clear', description='Clears the channels last messages')
async def clear(interaction: Interaction, amount: int):
    if amount > 0:
        await interaction.response.defer()
        await interaction.channel.purge(limit=amount)
        # 清理完成后发送反馈(调用defer后必须用followup)
        await interaction.followup.send(f'已清理{amount}条消息')
    else:
        # 直接通过交互响应发送提示,避免超时报错
        await interaction.response.send_message('请输入大于0的有效数字!')

if __name__ == '__main__':
    bot.run('MySecret')

额外注意事项

  • 邀请权限检查:重新邀请机器人时,必须确保邀请链接包含applications.commands权限。在开发者门户「OAuth2」→「URL Generator」中,同时勾选「bot」和「applications.commands」权限后生成邀请链接。
  • 同步方式选择:全局同步生效慢,适合正式发布;指定服务器同步可立即生效,适合测试调试。
  • 交互响应规范:原代码中clear命令的else分支使用interaction.channel.send会触发交互超时错误,必须通过interaction.response或followup发送反馈。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:52:49