Discord机器人如何检测所有语音频道人数并加入人数最多的频道播放音频
Discord机器人语音频道检测逻辑实现方案
import discord from discord.ext import commands from discord.player import FFmpegPCMAudio import datetime import asyncio # 开启所需权限意图 intents = discord.Intents.default() intents.voice_states = True intents.members = True bot = commands.Bot(command_prefix="<", intents=intents) @bot.event async def on_ready(): print("Bot is ready") MINUTE = 0 @bot.command() async def start(ctx): global MINUTE while not bot.is_closed(): # 替换原有的字符串判断逻辑,直接用数值判断更稳定 current_minute = datetime.datetime.now().minute if current_minute != MINUTE and current_minute == 0: MINUTE = current_minute hour = datetime.datetime.now().hour number = hour while number > 0: # 核心逻辑:获取所有语音频道,按成员数排序取最大值 voice_channels = ctx.guild.voice_channels # 过滤掉没有人的语音频道 valid_channels = [c for c in voice_channels if len(c.members) > 0] if not valid_channels: print("当前没有有人的语音频道,跳过本次播放") await asyncio.sleep(60) break # 取成员数最多的频道 target_channel = max(valid_channels, key=lambda x: len(x.members)) # 处理机器人已经在语音频道的情况,先断开 if ctx.voice_client is not None: await ctx.voice_client.disconnect() # 连接频道播放音频 voice = await target_channel.connect() source = FFmpegPCMAudio('audio source') voice.play(source) # 等待音频播放完成再进行下一次 while voice.is_playing(): await asyncio.sleep(1) await voice.disconnect() number -= 1 # 每次循环休眠1秒,降低CPU占用 await asyncio.sleep(1) bot.run("my bot token")
- 注意事项:
- 请先在Discord开发者平台的机器人管理页面开启
Server Members Intent和Voice State Intent权限,否则无法正常获取语音频道的成员数据 - 代码替换了原有的字符串判断分钟的逻辑,改用数值判断稳定性更高,同时新增了休眠逻辑避免死循环占用过高CPU
- 新增了无人频道的异常处理,以及机器人已连接语音频道的重连处理,避免运行时报错
- 请先在Discord开发者平台的机器人管理页面开启
内容的提问来源于stack exchange,提问作者redaido114
相关产品推荐
相关产品推荐

