使用discord.py编写解封命令时触发AttributeError错误的求助
discord.py编写解封命令时触发AttributeError错误的求助
我在尝试用&unban donut_exe_命令解封用户时,遇到了这个错误:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'
我的代码如下:
import discord import time from discord.ext import commands client = commands.Bot(command_prefix="&", help_command=None, intents=discord.Intents.all()) @client.event async def on_ready(): print("Huligan online") # Приветствие @client.command(pass_context=True) async def greeting(ctx): await ctx.send("Пр") # Очистка чата @client.command(pass_context=True) @commands.has_permissions(manage_messages=True) async def clear(ctx, amount=100): await ctx.channel.purge(limit=amount + 1) # Кик @client.command(pass_context=True) @commands.has_permissions(kick_members=True) async def kick(ctx, member: discord.Member, *, reason=None): await member.kick(reason=reason) await ctx.send(f"Участник {member.mention} был кикнут по причине «{reason}» администратором {ctx.message.author.mention}") # Бан @client.command(pass_context=True) @commands.has_permissions(ban_members=True) async def ban(ctx, member: discord.Member, *, reason=None): await member.ban(reason=reason) await ctx.send(f"Участник {member.mention} был забанен по причине «{reason}» администратором {ctx.message.author.mention}") # Разбан @client.command(pass_context=True) @commands.has_permissions(ban_members=True) async def unban(ctx, id: str): user = id await ctx.guild.unban(user) await ctx.send(f"Участник {member.mention} был разбанен администратором {ctx.message.author.mention}") token = open("token.txt", r)readline() client.run(token)
我觉得可能是参数指定错了,希望能得到帮助。
问题分析与解决办法
你遇到这个错误的核心原因是:ctx.guild.unban()方法需要接收discord.User对象或者整数类型的用户ID,但你直接传入了字符串格式的内容,而且代码里还有两处明显的小问题:
- 参数类型不匹配:你把
id定义为str类型,直接传给unban方法,但该方法无法识别字符串格式的用户名或ID;另外用用户名donut_exe_解封是不可靠的——封禁记录只绑定用户ID,用户名可能被修改或重复。 - 未定义变量错误:解封命令的消息发送代码里用了
member.mention,但这个member变量在当前函数里根本没定义,执行到这行也会触发报错。
下面是修复后的完整解封命令,同时支持用户ID和用户名两种输入方式(优先推荐用ID,准确性更高):
# Разбан @client.command(pass_context=True) @commands.has_permissions(ban_members=True) async def unban(ctx, *, user_input: str): try: # 先尝试按用户ID查找(推荐方式) user_id = int(user_input) user = await client.fetch_user(user_id) except ValueError: # 如果输入不是数字ID,尝试按用户名匹配封禁列表 banned_users = [entry.user async for entry in ctx.guild.bans()] matching_users = [user for user in banned_users if user.name.lower() == user_input.lower()] if not matching_users: await ctx.send("找不到被封禁的用户,请确认输入的是正确的用户ID或用户名!") return user = matching_users[0] await ctx.guild.unban(user) await ctx.send(f"Участник {user.mention} был разбанен администратором {ctx.message.author.mention}")
另外还要修正你的token读取代码的语法错误:
token = open("token.txt", "r").readline().strip() # 补上引号,用strip()去掉换行符避免登录失败
备注:内容来源于stack exchange,提问作者Илья Шадрин
相关产品推荐
相关产品推荐

