discord.py命令同步失败:执行!sync无响应且未完成同步
Discord.py 命令同步超时问题排查与解决
问题描述
使用以下代码尝试同步应用命令时,执行!sync指令后机器人耗时极久仍未完成同步:
@bot.tree.command(name="test", description="My first application Command") async def my_command(interaction: discord.Interaction) -> None: await interaction.response.send_message("Hello from my command!") @bot.command(name="sync") async def sync(ctx): try: fmt = await ctx.bot.tree.sync(guild=ctx.guild) await ctx.send( f"Synced {len(fmt)} command(s) to the current server" ) except Exception as e: await ctx.send(f"Error while syncing commands: {e}") return
解决步骤
校验核心权限:
- 确保机器人在Discord开发者门户的OAuth2权限中勾选了
applications.commands,且邀请机器人到服务器时的链接包含该权限。 - 服务器内机器人角色需拥有
管理服务器和发送消息权限,避免权限不足导致API请求挂起。
- 确保机器人在Discord开发者门户的OAuth2权限中勾选了
修正同步代码的潜在问题:
直接使用ctx.guild可能存在缓存失效的情况,改为手动传入服务器ID对象,并添加所有者校验防止滥用:
@bot.command(name="sync")
@commands.is_owner() # 仅机器人所有者可执行同步
async def sync(ctx):
try:
# 显式创建服务器对象,避免缓存问题
target_guild = discord.Object(id=ctx.guild.id)
synced_commands = await ctx.bot.tree.sync(guild=target_guild)
await ctx.send(f"已同步 {len(synced_commands)} 条命令到当前服务器")
except Exception as e:
await ctx.send(f"同步失败:{str(e)}")
- **检查Intents配置**: 同步服务器命令需要`guilds` Intent支持,初始化机器人时必须启用: ```python intents = discord.Intents.default() intents.guilds = True bot = commands.Bot(command_prefix="!", intents=intents)
排查API限流与网络问题:
- Discord API存在速率限制,若短时间内多次执行同步会被限流,需等待5-10分钟后重试。
- 检查机器人所在环境的网络,确保能正常访问Discord API(无防火墙拦截、代理配置错误等)。
尝试全局同步(测试场景):
若服务器同步持续卡住,可先尝试全局同步(去掉guild参数),虽然全局同步需1小时左右生效,但能排查是否为服务器特定问题:
@bot.command(name="sync_global")
@commands.is_owner()
async def sync_global(ctx):
synced = await ctx.bot.tree.sync()
await ctx.send(f"已全局同步 {len(synced)} 条命令")
内容的提问来源于stack exchange,提问作者user20750684
相关产品推荐
相关产品推荐

