如何用Python获取Discord机器人的斜杠命令名称并调用对应函数
在Discord.py中通过on_message()获取斜杠命令名称并调用对应函数
Discord的斜杠命令消息在on_message()中不会以普通文本形式存在,而是通过message.interaction对象识别和获取相关信息。以下是实现的具体步骤和代码示例:
第一步:判断消息是否为斜杠命令
检查消息的interaction属性是否存在,且交互类型为应用命令(discord.InteractionType.application_command)。第二步:提取斜杠命令名称
通过message.interaction.command.name可直接获取命令的名称字符串。第三步:建立命令与函数的映射
用字典存储命令名和对应执行函数的映射关系,实现快速匹配调用。第四步:根据命令名调用对应函数
通过字典匹配执行对应函数,同时处理命令不存在的异常情况。
完整代码示例
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 定义各命令对应的处理函数 def handle_ping(): print("执行ping命令逻辑") def handle_hello(): print("执行hello命令逻辑") # 命令-函数映射字典 command_mapping = { "ping": handle_ping, "hello": handle_hello } @bot.event async def on_message(message): # 忽略机器人自身消息 if message.author.bot: return # 判断是否为斜杠命令 if message.interaction and message.interaction.type == discord.InteractionType.application_command: command_name = message.interaction.command.name print(f"收到斜杠命令:{command_name}") # 调用对应处理函数 if command_name in command_mapping: command_mapping[command_name]() # 如需给用户发送回复,可使用以下方式 # await message.interaction.response.send_message(f"已执行{command_name}命令") else: print(f"未找到对应处理函数的命令:{command_name}") # 必须保留该行,避免影响其他命令执行 await bot.process_commands(message) bot.run("你的机器人Token")
注意事项
- 确保机器人开启了
message_content和guild_messages等必要Intents,否则无法正常接收消息。 - 若处理函数需要异步操作,需将函数定义为
async类型,调用时加上await关键字。 - 回复用户时建议使用
message.interaction.response.send_message(),避免出现交互超时问题。
内容的提问来源于stack exchange,提问作者nub_discordDev
相关产品推荐
相关产品推荐

