如何让基于 Python 的 Discord Bot 随机播放不同的声音?

Posted

技术标签:

【中文标题】如何让基于 Python 的 Discord Bot 随机播放不同的声音?【英文标题】:How to make Python-based Discord Bot to play different sounds randomly? 【发布时间】:2021-09-29 06:42:05 【问题描述】:

我正在用 Python 编写一个 Discord Bot。 我希望它加入语音频道,然后从列表中随机播放不同的声音。 它可以像每 10 秒播放一个特定的音频文件。

其他一切正常,机器人连接到频道等,但我不知道如何让它留在语音频道上并随机说话。

现在看起来像这样:

arvaus = [ *list of my files here* ]

@client.command()
async def arvaa(ctx):
   if not ctx.author.voice:
      return await ctx.send(ctx.message.author.mention + 'You need to connect to a voice channel')
    
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild=guild)
audio_source =(discord.FFmpegPCMAudio(executable="F:/ffmpeg/bin/ffmpeg.exe", source=random.choice(arvaus)))
voice_client.play(audio_source, after=None)

所以基本上现在它会播放一个音频文件,直到我再次输入命令来触发另一个文件。

【问题讨论】:

【参考方案1】:
    async def play(self, ctx, *, query):
        """Plays a file from the local filesystem"""

        source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
        ctx.voice_client.play(source, after=lambda e: print(f'Player error: e') if e else None)

        await ctx.send(f'Now playing: query')

这是示例discord_bot_voice myaybe 中的一个代码,请尝试在您的代码中实现这一点,说在机器人连接后从您拥有的文件中播放随机声音

附加:如果您不发出任何声音,机器人将在一段时间后自动断开连接,因此可能只是让机器人播放在随机时间之前没有声音的文件

也许

arvaus = [ *list of my files here* ]

@client.command()
async def arvaa(ctx):
if not ctx.author.voice:
    return await ctx.send(ctx.message.author.mention + 'You need to connect to a voice 
channel')

guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild=guild)
for i in range(len(arvaus)):
    audio_source = (discord.FFmpegPCMAudio(executable="F:/ffmpeg/bin/ffmpeg.exe", 
    source=random.choice(arvaus)))
    randomtime = random.randint(20,200)
    await asyncio.sleep(ransomint)
    voice_client.play(audio_source, after=None)

【讨论】:

以上是关于如何让基于 Python 的 Discord Bot 随机播放不同的声音?的主要内容,如果未能解决你的问题,请参考以下文章

如何让我的 Python Discord 机器人检查消息是不是由机器人本身发送?

Discord BOT with Python,如何让它在我们发送命令的频道中回复(完成)

如何让 Discord bot 使用用户选择的号码名称发送图像? (Python 3.5.x)

如何使用 discord.py 让 discord bot ping 用户 [关闭]

Python discord bot如何将消息与列表进行比较

(Discord.py)如何让机器人在一段时间后删除自己的消息?