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

如何为Discord机器人添加可用斜杠命令及消息回复功能

Discord机器人问题解决方案

一、创建可在/列表显示的Slash命令

要让输入/时能看到机器人命令,必须注册Slash应用命令,以常用的discord.py v2.x为例:

  • 先确认机器人邀请链接里勾选了applications.commands权限
  • 写注册命令的代码:
import discord
from discord import appcommands

# 开启必要的意图
intents = discord.Intents.default()
intents.message_content = True  # 回复普通消息需要这个

client = discord.Client(intents=intents)
tree = appcommands.CommandTree(client)

# 注册基础帮助命令
@tree.command(name="帮助", description="查看机器人基础指引")
async def help_cmd(interaction: discord.Interaction):
    await interaction.response.send_message("机器人基础命令:\n- /帮助:打开本指引\n- /你好:和我打招呼")

# 带参数的命令示例
@tree.command(name="你好", description="和机器人打招呼")
@appcommands.describe(昵称="你的称呼")
async def hello_cmd(interaction: discord.Interaction, 昵称: str):
    await interaction.response.send_message(f"哈喽,{昵称}!")

# 同步命令到服务器
@client.event
async def on_ready():
    # 全局同步(所有服务器生效,需等1-10分钟)
    await tree.sync()
    # 测试用服务器同步(仅指定服务器生效,几秒就好)
    # await tree.sync(guild=discord.Object(id=你的服务器ID))
    print(f"机器人已登录:{client.user}")

client.run("你的机器人TOKEN")

二、让机器人回复普通消息

开启message_content意图后,监听消息事件就能实现:

@client.event
async def on_message(message):
    # 别让机器人自己回复自己
    if message.author == client.user:
        return
    
    # 关键词触发回复
    if "早上好" in message.content:
        await message.channel.send(f"早呀{message.author.mention}!")
    
    # 必须加这句,不然Slash命令会失效
    await client.process_commands(message)

注意:一定要去Discord开发者后台的机器人页面,手动开启Message Content Intent,不然机器人收不到普通消息内容。

三、输入/看不到命令的解决办法

  1. 补全邀请权限:重新生成邀请链接,确保勾选applications.commands权限,再邀请一次机器人。
  2. 检查命令同步:如果用全局同步,多等几分钟;测试时用服务器ID同步,能快速生效。
  3. 核对服务器权限:机器人在服务器里要有Send Messages和Use Slash Commands的权限,检查角色设置。
  4. 排查代码问题:确认tree.sync()在on_ready里执行了,命令的名称和描述别加特殊字符,看控制台有没有报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:43:19