如何在discord.py V2.0的Cog中指定Guild以测试斜杠命令
在discord.py V2.0的Cog中指定服务器创建斜杠命令
我正在学习discord.py V2.0,发现创建未指定服务器(Guild)的斜杠命令时,Discord更新机器人的斜杠命令列表需要很长时间。想请教:如何在Cog文件中指定服务器?
原始代码
main.py
import os import asyncio #--- import discord from discord import app_commands from discord.ext import commands #--- MY_GUILD = discord.Object(id=1041079018713260173) TOKEN = "token goes here" intents = discord.Intents.default() bot = commands.Bot(command_prefix="!", intents=intents) class abot(discord.Client): def __init__(self, *, intents: discord.Intents): super().__init__(intents=intents) self.bot = bot self.synced = False self.tree = app_commands.CommandTree(self.bot) async def on_ready(self): await self.tree.sync(guild=MY_GUILD) self.synced = True async def load(): print("---Cogs---") for filename in os.listdir("./cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") print(f'[i]: Loaded "{filename}" into cogs') async def main(): await load() await bot.start(TOKEN) asyncio.run(main())
cogs/event.py
import asyncio import os #--- import discord from discord import app_commands from discord.ext import commands status = "testar bara..." MY_GUILD = discord.Object(id=1041079018713260173) class events(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print("---Info---") print(f'Logged in as | "{self.bot.user}" | and is now online!') await self.bot.change_presence(status=discord.Status.online, activity=discord.Game(status)) print(f'Updated status to -> "{status}"') print("Running and listening for commands....") print(f"----") @app_commands.command(name = "latency", description="brrarar testar") async def latencyf(self, interaction: discord.Interaction): await interaction.response.send_message(f"test... test...") async def setup(bot): await bot.add_cog(events(bot))
解决方案
首先修正main.py的冗余问题:你同时创建了commands.Bot和自定义abot类,而commands.Bot本身已继承discord.Client,无需额外定义abot,否则会导致命令树同步异常。
下面是两种在Cog中指定服务器的实用方法:
方法1:给斜杠命令添加guilds参数
在定义@app_commands.command时,直接通过guilds参数指定目标服务器,该命令只会注册到这些服务器中。
方法2:使用@app_commands.guilds装饰器
给命令单独添加该装饰器,同样可以指定命令生效的服务器。
修正后的完整代码
main.py
import os import asyncio import discord from discord import app_commands from discord.ext import commands MY_GUILD = discord.Object(id=1041079018713260173) TOKEN = "你的机器人Token" intents = discord.Intents.default() bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"已登录为 {bot.user}") # 同步指定服务器的命令,全局命令去掉guild参数 await bot.tree.sync(guild=MY_GUILD) print("服务器专属命令已同步完成") async def load_cogs(): print("---加载Cogs---") for filename in os.listdir("./cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") print(f'已加载 "{filename}"') async def main(): await load_cogs() await bot.start(TOKEN) asyncio.run(main())
cogs/event.py
import discord from discord import app_commands from discord.ext import commands status = "测试中..." MY_GUILD = discord.Object(id=1041079018713260173) class Events(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print("---信息---") print(f'登录账号:"{self.bot.user}",已上线!') await self.bot.change_presence(status=discord.Status.online, activity=discord.Game(status)) print(f'状态已更新为 -> "{status}"') print("正在运行并监听命令....") print("----") # 方法1:使用command的guilds参数指定服务器 @app_commands.command( name="latency", description="测试机器人延迟", guilds=[MY_GUILD] ) async def latencyf(self, interaction: discord.Interaction): await interaction.response.send_message(f"测试中... 当前延迟:{round(self.bot.latency*1000)}ms") # 方法2:使用app_commands.guilds装饰器指定服务器 @app_commands.guilds(MY_GUILD) @app_commands.command(name="hello", description="跟机器人打招呼") async def hello(self, interaction: discord.Interaction): await interaction.response.send_message(f"你好呀!{interaction.user.mention}") async def setup(bot): await bot.add_cog(Events(bot))
注意事项
- 指定服务器的斜杠命令同步速度极快,通常几秒内就能生效;而全局命令需要Discord的全局同步流程,可能需要1小时甚至更久。
- 确保你的机器人在目标服务器中拥有
applications.commands权限。
内容的提问来源于stack exchange,提问作者Snabba_Snigeln
相关产品推荐
相关产品推荐

