Pycord Discord机器人角色授予功能报错,求修复方案
Pycord机器人/money命令报错修复方案
常见报错原因及解决办法
- 权限不足
确保机器人拥有Manage Roles权限,且“Rich”角色的位置要低于机器人的最高角色(Discord规则:机器人无法给用户添加等级比自己高的角色)。 - 在DM中触发命令
斜杠命令如果在私聊窗口执行,ctx.guild会是None,获取角色时会抛出属性错误。可以在命令开头判断是否处于服务器内,不在就提示用户。 - 未处理超时情况
默认wait_for没有超时限制,用户长时间不回复会导致任务挂起甚至报错。给wait_for加timeout参数,并捕获超时异常。 - 消息匹配过于严苛
原代码严格匹配“100,000”,用户输入无逗号、带空格都会匹配失败。可以做宽松处理,比如去掉逗号、忽略前后空格后再比较。 - 目标角色不存在
如果服务器里没有“Rich”角色,discord.utils.get会返回None,调用add_roles会报错。需要先判断角色是否存在,不存在则提示。
修复后的完整代码
import asyncio import discord from discord.ext import commands @bot.slash_command() async def money(ctx): # 检查是否在服务器内执行命令 if not ctx.guild: await ctx.send("此命令仅支持在服务器内使用!") return await ctx.send("How much money you have?") def check(m): # 宽松匹配:去除逗号和前后空格,同时验证消息来源和频道 cleaned_content = m.content.replace(",", "").strip() return cleaned_content == "100000" and m.author == ctx.author and m.channel == ctx.channel try: # 设置60秒超时时间 role_input = await bot.wait_for('message', check=check, timeout=60) except asyncio.TimeoutError: await ctx.send(f"{ctx.author.mention},你超时未回复,请重新触发命令!") return role = discord.utils.get(ctx.guild.roles, name="Rich") if not role: await ctx.send("当前服务器不存在名为'Rich'的角色,请先创建该角色!") return try: await role_input.author.add_roles(role) await ctx.send(f"{role_input.author.mention}, you have been given the 'Rich' role.") except discord.Forbidden: await ctx.send("我没有权限为你添加角色,请管理员检查我的权限设置!")
内容的提问来源于stack exchange,提问作者34-4
相关产品推荐
相关产品推荐

