如何修改Discord机器人脚本,使其支持/rollmap和/rollagent Slash命令?
把Discord机器人指令改为Slash命令的修改方案
要实现/rollmap、/rollagent这类Slash命令,你需要使用支持Discord应用命令的库,这里以discord.py 2.x+版本为例,以下是完整修改方案:
第一步:安装/更新依赖
确保你安装了最新版的discord.py:
pip install --upgrade discord.py
第二步:替换原有脚本
将你原来的代码替换为以下内容,注意把YOUR_BOT_TOKEN替换成你的Discord机器人令牌:
import random import discord from discord import appcommands # 保留原有地图和特工列表 MAPS = ('Ascent' , 'Bind' , 'Breeze' , 'Fracture' , 'Haven' , 'Icebox' , 'Lotus' , 'Pearl' , 'Split') AGENTS = ('Brimstone' , 'Chamber', 'Cypher' , 'Deadlock' , 'Fade' , 'Gekko', 'Harbor' , 'Jett' , 'KAY/O' , 'Killjoy' , 'Neon' , 'Omen' , 'Phoenix' , 'Raze' , 'Reyna' , 'Skye' , 'Sova' , 'Viper' , 'Yoru' , 'Astra' , 'Breach') # 创建Bot实例,开启必要权限 intents = discord.Intents.default() bot = discord.Client(intents=intents) tree = appcommands.CommandTree(bot) # 定义/rollmap Slash命令 @tree.command(name="rollmap", description="随机抽取一张Valorant地图") async def rollmap(interaction: discord.Interaction): await interaction.response.send_message(f"随机选中的地图:{random.choice(MAPS)}") # 定义/rollagent Slash命令 @tree.command(name="rollagent", description="随机抽取一名Valorant特工") async def rollagent(interaction: discord.Interaction): await interaction.response.send_message(f"随机选中的特工:{random.choice(AGENTS)}") # 机器人就绪后同步命令 @bot.event async def on_ready(): # 全局同步命令(生效需1-2小时),测试时可替换为指定服务器同步(立即生效) await tree.sync() # 指定服务器同步示例:await tree.sync(guild=discord.Object(id=你的服务器ID)) print(f"已登录为 {bot.user},Slash命令已同步") # 启动机器人 bot.run("YOUR_BOT_TOKEN")
核心说明
- 权限设置:必须开启默认Intents,否则机器人无法正常接收事件
- 命令同步:首次运行会同步Slash命令到Discord,测试阶段建议用指定服务器ID的方式同步,能立即生效
- 交互响应:Slash命令必须通过
interaction.response.send_message()回复,这是Discord要求的交互响应规范
内容的提问来源于stack exchange,提问作者xukosa
相关产品推荐
相关产品推荐

