求助:Discord.py 2.0斜杠命令与Cog配置,求代码示例
Discord.py 2.0 斜杠命令+Cog配置示例
main.py 核心文件
import discord from discord.ext import commands from discord import app_commands # 配置机器人权限意图,按需调整 intents = discord.Intents.default() intents.message_content = True intents.guilds = True # 初始化机器人,前缀命令可选(斜杠命令无需前缀) bot = commands.Bot(command_prefix="!", intents=intents) # 机器人就绪事件 @bot.event async def on_ready(): print(f"登录成功:{bot.user} (ID: {bot.user.id})") print("------") # 同步斜杠命令到全局(首次运行生效慢,测试可指定服务器ID加速) # 全局同步:await bot.tree.sync() # 指定服务器同步:await bot.tree.sync(guild=discord.Object(id=你的服务器ID)) await bot.tree.sync() # 加载Cog(确保cogs文件夹存在,且内含空的__init__.py文件) async def load_cogs(): await bot.load_extension("cogs.example") # 启动机器人 if __name__ == "__main__": import asyncio asyncio.run(load_cogs()) bot.run("你的机器人Token")
Cog示例文件(cogs/example.py)
import discord from discord.ext import commands from discord import app_commands import random class ExampleCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot # 基础斜杠命令 @app_commands.command(name="hello", description="发送问候消息") async def hello(self, interaction: discord.Interaction): # 3秒内必须响应交互,否则会超时 await interaction.response.send_message(f"你好呀,{interaction.user.mention}!") # 带参数的斜杠命令 @app_commands.command(name="say", description="让机器人重复内容") @app_commands.describe(text="要重复的文本") async def say(self, interaction: discord.Interaction, text: str): await interaction.response.send_message(f"{interaction.user} 说:{text}") # 带多选项的斜杠命令 @app_commands.command(name="choose", description="让机器人帮你做选择") @app_commands.describe(option1="第一个选项", option2="第二个选项") async def choose(self, interaction: discord.Interaction, option1: str, option2: str): result = random.choice([option1, option2]) await interaction.response.send_message(f"我选:{result}") # 将Cog注册到机器人 async def setup(bot: commands.Bot): await bot.add_cog(ExampleCog(bot))
关键注意事项
- 确保安装最新版Discord.py:
pip install -U discord.py - 机器人Token需从Discord开发者平台获取,邀请机器人时需勾选
applications.commands权限 - 斜杠命令同步:全局同步生效慢,测试阶段推荐指定服务器ID同步
- Cog所在文件夹必须有
__init__.py空文件,否则无法正常加载 - 所有斜杠命令处理函数必须是
async类型,交互响应需使用interaction.response相关方法
内容的提问来源于stack exchange,提问作者Snabba_Snigeln
相关产品推荐
相关产品推荐

