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

求Python版Discord Slash Command Bot可运行示例与结构参考

Python Discord Slash Command Bot 可运行示例

我完全懂你的感受——Discord官方文档确实严重偏向JavaScript生态,找Python相关的Slash命令示例确实费劲。不过别担心,用nextcord(discord.py的活跃分支,完美支持Slash命令)就能快速搭建一个可运行的示例,下面是完整步骤和代码:

第一步:安装依赖

先安装nextcord库,打开终端运行:

pip install nextcord

第二步:完整可运行代码

把下面的代码保存成slash_bot.py,替换掉你的机器人Token:

import nextcord
from nextcord.ext import commands
from nextcord import Interaction, SlashOption

# 初始化机器人,开启所需意图
intents = nextcord.Intents.default()
intents.message_content = True  # 如需处理消息内容可开启
bot = commands.Bot(command_prefix="!", intents=intents)

# 机器人上线时的控制台提示
@bot.event
async def on_ready():
    print(f"Logged in as {bot.user} (ID: {bot.user.id})")
    print("机器人已就绪,可以测试Slash命令啦!")

# 定义简单的Slash命令:/hello
@bot.slash_command(name="hello", description="让机器人跟你打招呼")
async def hello(interaction: Interaction):
    await interaction.response.send_message(f"哈喽 {interaction.user.mention}! 👋")

# 定义带参数的Slash命令:/greet
@bot.slash_command(name="greet", description="给指定用户发送自定义问候")
async def greet(
    interaction: Interaction,
    user: nextcord.User = SlashOption(description="要问候的用户"),
    message: str = SlashOption(description="自定义问候语", required=False, default="嗨呀!")
):
    await interaction.response.send_message(f"{message} {user.mention}!")

# 运行机器人,替换成你的机器人Token
bot.run("YOUR_BOT_TOKEN_HERE")

第三步:OAuth2权限设置(必须!)

你之前提到的步骤是对的,一定要在Discord开发者平台的OAuth2页面:

  • 勾选bot和applications.commands这两个选项
  • 给机器人分配基础权限(比如Send Messages、Embed Links等,根据命令需求调整)
  • 生成邀请链接,把机器人邀请到你的服务器

第四步:运行机器人

在终端运行:

python slash_bot.py

之后你就能在服务器里输入/hello或者/greet来测试命令了!

关于开发结构的说明

这个示例覆盖了Python Slash机器人的核心结构:

  1. 客户端初始化:设置机器人意图(控制机器人能获取的服务器数据),前缀仅用于兼容传统命令,Slash命令不需要前缀
  2. 事件监听:on_ready事件用于确认机器人上线状态,方便调试
  3. Slash命令定义:用@bot.slash_command()装饰器创建命令,支持自定义名称、描述和参数
  4. 命令响应:通过interaction.response.send_message()回复用户,这是Slash命令的标准回复方式

如果之后需要扩展,还可以添加子命令组、权限控制、错误处理等功能,nextcord的官方文档里有详细的进阶说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:24:11