Discord.py封禁命令传入固定用户ID触发运行报错的问题求解
错误根因
你代码中使用的client.get_user()依赖机器人本地用户缓存,当目标用户不在缓存范围内时会返回None,将空值传入ctx.guild.ban()就会触发你截图中的属性错误。
同时你原有代码存在装饰器排版错误、冗余参数的问题,也可能触发额外报错。
修复方案
Discord.py的Guild.ban原生支持直接传入int类型的用户ID,不需要提前获取用户对象,是最简修复方案,代码如下:
@client.command() @commands.has_permissions(ban_members = True) async def niceroger(ctx): # 固定要封禁的用户ID target_user_id = 669680584376713259 reason = "Bye bye" await ctx.guild.ban(target_user_id, reason=reason) await ctx.send(f"Bye <@{target_user_id}>")
可选补充:增加异常捕获
如果需要增加错误提示避免命令无响应,可以加异常捕获逻辑:
import discord @client.command() @commands.has_permissions(ban_members = True) async def niceroger(ctx): target_user_id = 669680584376713259 reason = "Bye bye" try: await ctx.guild.ban(target_user_id, reason=reason, delete_message_days=0) await ctx.send(f"Bye <@{target_user_id}>") except discord.Forbidden: await ctx.send("机器人没有封禁该用户的权限") except discord.HTTPException: await ctx.send("封禁操作执行失败")
内容的提问来源于stack exchange,提问作者Engineer
相关产品推荐
相关产品推荐

