如何通过Discord.py获取封禁用户名称与ID列表并实现!banlist命令
我来帮你搞定这个需求!要实现!banlist命令查看服务器里被封禁用户的名称和ID列表,用Discord.py的API就能轻松做到,下面是完整的实现方案:
实现
!banlist封禁列表查询命令(Discord.py) 前提准备
- 确保你的Discord Bot已拥有Ban Members权限,否则无法读取服务器的封禁列表
- 项目使用Discord.py v2.x版本(v1.x API逻辑略有不同,以下代码基于v2.x开发)
完整代码实现
import discord from discord.ext import commands # 初始化Bot,开启必要意图 intents = discord.Intents.default() intents.message_content = True # 必须开启该意图才能读取用户发送的命令 bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"已登录为 {bot.user} (ID: {bot.user.id})") print("------") # 限制仅拥有封禁权限的用户可执行该命令 @commands.has_permissions(ban_members=True) @bot.command(name="banlist", help="查看服务器内所有被封禁用户的名称与ID列表") async def ban_list(ctx): ban_records = [] # 异步遍历服务器封禁记录(Discord API要求异步操作) async for ban_entry in ctx.guild.bans(): user = ban_entry.user # 兼容新旧Discord用户名格式:旧版带#标签,新版无标签 user_detail = f"{user.name}{f'#{user.discriminator}' if user.discriminator != '0' else ''} (ID: {user.id})" ban_records.append(user_detail) # 处理无封禁用户的情况 if not ban_records: await ctx.send("当前服务器没有被封禁的用户哦~") return # 分批次发送长列表(避免超过Discord消息2000字符限制) batch_size = 10 total_pages = (len(ban_records) - 1) // batch_size + 1 for page in range(total_pages): start_idx = page * batch_size end_idx = start_idx + batch_size current_batch = ban_records[start_idx:end_idx] # 用Embed美化展示效果 embed = discord.Embed( title="服务器封禁用户列表", description="\n".join(current_batch), color=discord.Color.red() ) embed.set_footer(text=f"第 {page+1}/{total_pages} 页") await ctx.send(embed=embed) # 替换为你的Bot Token bot.run("YOUR_BOT_TOKEN_HERE")
代码细节说明
- 权限校验:
@commands.has_permissions(ban_members=True)确保只有服务器管理员或拥有封禁权限的成员才能使用该命令,防止滥用。 - 异步遍历封禁列表:
ctx.guild.bans()返回异步迭代器,必须用async for遍历,否则会阻塞Bot运行。 - 兼容用户名格式:适配Discord新版无 discriminator(#1234)的用户名,避免展示多余内容。
- 长列表分页:用Embed分批次发送内容,解决Discord单条消息长度限制问题,同时提升可读性。
额外实用提示
如果需要解除特定用户的封禁,你可以在命令里或单独写一个解封命令,使用以下代码:
@commands.has_permissions(ban_members=True) @bot.command(name="unban", help="通过ID解除用户封禁") async def unban_user(ctx, user_id: int): try: await ctx.guild.unban(discord.Object(id=user_id)) await ctx.send(f"已解除ID为 {user_id} 的用户封禁") except discord.NotFound: await ctx.send("该用户未被封禁或不存在")
内容的提问来源于stack exchange,提问作者Tsumugi




