Discord.py队列操作后提及用户角色及队列展示角色需求实现
解决方案:在Discord队列命令中添加角色提及功能
我帮你调整了代码,实现了!addme执行后显示带角色的提示,以及查询队列时展示成员的角色提及。下面是修改后的完整代码,关键改动点我都做了标注:
修改后的addme命令
@commands.command(pass_context=True) async def addme(self, ctx): ''': Add yourself to the queue!''' author = ctx.message.author # 替换成你的服务器中实际的氏族角色名称,比如"Red Clan" CLAN_ROLE_NAME = "{clan}" # 获取用户对应的氏族角色 clan_role = discord.utils.get(author.roles, name=CLAN_ROLE_NAME) if self.qtoggle: if author.id not in self.queue: self.queue.append(author.id) # 根据是否找到角色格式化消息 if clan_role: await ctx.send(f'{author.mention}(来自{clan_role.mention})已加入Tablet Crafting队列') else: await ctx.send(f'{author.mention}已加入Tablet Crafting队列(未找到氏族角色)') else: await ctx.send(f'{author.mention}你已经在Tablet Crafting队列中了!') else: await ctx.send('Tablet Crafting队列已关闭。')
修改后的removeme命令(优化了用户提及)
@commands.command(pass_context=True) async def removeme(self, ctx): ''': Remove yourself from the queue''' author = ctx.message.author if author.id in self.queue: self.queue.remove(author.id) await ctx.send(f'{author.mention}你已从Tablet Crafting队列中移除。') else: await ctx.send(f'{author.mention}你不在Tablet Crafting队列中哦。')
修改后的queue命令(修复角色未定义问题)
@commands.command(name='queue', pass_context=True) async def _queue(self, ctx): ''': See who's up next!''' server = ctx.message.guild # 同样替换成实际的氏族角色名称 CLAN_ROLE_NAME = "{clan}" message = '' for place, member_id in enumerate(self.queue): member = discord.utils.get(server.members, id=member_id) if member: # 获取当前成员的氏族角色 clan_role = discord.utils.get(member.roles, name=CLAN_ROLE_NAME) role_text = clan_role.mention if clan_role else "无氏族角色" message += f'**#{place+1}** : {member.mention} : {role_text}\n' else: # 处理成员已离开服务器的情况,避免报错 message += f'**#{place+1}** : 成员ID {member_id}(已离开服务器)\n' if message != '': await ctx.send(f'当前Tablet Crafting队列:\n{message}') else: await ctx.send('Tablet Crafting队列是空的!')
重要提示
- 一定要把代码中的
CLAN_ROLE_NAME替换成你Discord服务器里实际的氏族角色名称,大小写和拼写必须完全一致,否则会找不到角色 - 代码中加入了容错逻辑:如果用户没有对应的氏族角色,或者成员已经离开服务器,命令不会崩溃,而是显示友好的提示信息
- 所有交互消息都使用了用户提及,让通知更直观,用户能快速注意到
内容的提问来源于stack exchange,提问作者The Casual Gamers 1080p
相关产品推荐
相关产品推荐

