如何让random.choice循环执行 实现Discord bot每隔几秒随机更换列表值
实现Discord Bot定时随机切换音频的解决方案
问题根因
你当前代码中的随机音频选择逻辑x=random.choice(Audio)仅会在程序启动时执行一次,后续运行过程中不会主动重新执行,因此x的值会一直保持首次生成的结果。要实现定时更新x并切换播放的音频,需要借助discord.py自带的后台定时任务模块实现。
解决方法
修改后完整代码
from discord.ext import commands, tasks from discord import FFmpegPCMAudio import random Audio=['AUDIO_1.mp3','AUDIO_2.mp3','AUDIO_3.mp3'] # 初始赋值,后续会被定时任务更新 x=random.choice(Audio) client = commands.Bot(command_prefix = '!') # 定时切换音频任务,seconds参数为切换间隔,可自行修改 @tasks.loop(seconds=10) async def change_audio(): global x # 重新随机选择音频 x = random.choice(Audio) # 检测所有已加入的语音频道,切换播放内容 for guild in client.guilds: voice_client = guild.voice_client if voice_client and voice_client.is_connected(): # 停止当前播放的音频 voice_client.stop() # 加载并播放新音频 source = FFmpegPCMAudio(x) voice_client.play(source) @client.event async def on_ready(): # 启动定时切换任务 change_audio.start() print("The bot is now ready for use.") print(".............................") @client.command(pass_context=True) async def join(ctx): if (ctx.author.voice): channel = ctx.message.author.voice.channel voice = await channel.connect() source = FFmpegPCMAudio(x) player = voice.play(source) else: await ctx.send("User not in a voice channel, unable to connect.") @client.command(pass_context=True) async def leave(ctx): if (ctx.voice_client): await ctx.guild.voice_client.disconnect() await ctx.send("I have left the voice channel.") else: await ctx.send("I am not in a voice channel.") client.run('TOKEN')
参数调整说明
- 你可以修改
@tasks.loop(seconds=10)中的seconds参数,自定义切换音频的间隔时长 - 如果需要避免连续两次选中同一个音频,可以在随机选择时增加排除上一次选中值的逻辑
- 注意确保所有音频文件和代码文件在同一目录下,或者在Audio列表中填写音频的完整路径
内容的提问来源于stack exchange,提问作者Evan Fisher
相关产品推荐
相关产品推荐

