如何为Discord Bot新增已连接语音频道成员数的状态展示
实现方案
前置准备
- 进入Discord开发者平台对应Bot的管理页,在「Bot」选项卡下开启 Server Members Intent 和 Voice States Intent 两个权限开关,否则Bot无法读取服务器成员和语音状态数据。
- 若使用discord.py v2及以上版本,需要在初始化Bot时显式声明启用对应意图。
修改后代码
import discord from discord.ext import commands class CONFIG: PREFIX = 'k.' # 声明所需意图 intents = discord.Intents.default() intents.members = True intents.voice_states = True client = commands.Bot(command_prefix=CONFIG.PREFIX, intents=intents) client.remove_command('help') # 封装统计与状态更新逻辑,避免重复代码 async def update_presence(): total_members = 0 voice_members = 0 for guild in client.guilds: total_members += guild.member_count # 统计语音频道成员,若需要计入Bot可删除if not m.bot过滤条件 for vc in guild.voice_channels: voice_members += len([m for m in vc.members if not m.bot]) # 更新Bot在线状态 await client.change_presence(activity = discord.Activity( type = discord.ActivityType.watching, name = f'✨{total_members} ᴍᴇᴍʙᴇʀꜱ | 🎤 {voice_members} 语音活跃' )) @client.event async def on_ready(): print('1') print('2') print('3') print('GanGz Iz Here') # 启动时首次更新状态 await update_presence() # 监听语音状态变化,实时更新状态 @client.event async def on_voice_state_update(member, before, after): if before.channel != after.channel: await update_presence() client.run("你的Bot令牌")
补充说明
- 统计语音成员时默认过滤了Bot账号,如需把Bot也计入活跃数,删除
if not m.bot即可。 - 新增的语音状态监听事件会在用户进出/切换语音频道时自动更新状态,避免仅启动时统计一次导致的数据滞后问题。
内容的提问来源于stack exchange,提问作者AwJ
相关产品推荐
相关产品推荐

