【问题标题】:When using Discord.py to create a bot, how to make my music bot leave when the audience left?使用 Discord.py 创建机器人时,如何让我的音乐机器人在观众离开时离开?
【发布时间】:2020-09-01 18:08:55
【问题描述】:

今天我开始使用 discord.py 创建自己的音乐机器人来处理不和谐。 我正在使用命令扩展以获得更简单的结构。

到目前为止,我已经创建了加入和离开语音频道的命令(删除了安全检查):

@bot.command()
async def join(ctx):
  v_channel = ctx.message.author.voice.channel
  await v_channel.connect()

@bot.command()
async def leave(ctx):
  player = ctx.message.guild.voice_client
  await player.disconnect()

现在我想实现一个功能,如果“观众”(非机器人成员)离开语音频道,机器人也会离开。如果“召唤”机器人的用户离开但其他成员仍在语音频道中,则机器人不得离开。

我想过使用这样的东西:

@bot.event
async def on_voice_state_update():
    If len(ctx.channel.members) == 1 and ctx.channel.members[0].bot:
       ctx.channel.disconnect()

但我不确定如何将它们放在一起以及如何获取频道上下文。我更愿意准确检查音乐机器人语音客户端,因为服务器上有多个机器人。 on_voice_state_update() 似乎是全局的,您获得的唯一上下文是用户 X 在服务器某处留下了一个频道。

你有什么好主意吗?

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    我会这样做:

    @bot.event
    async def on_voice_state_update(member, prev, cur):
        if bot.user in prev.channel.members and len([m for m in prev.channel.members if not m.bot]) == 0:
            channel = discord.utils.get(bot.voice_clients, channel=prev.channel)
            await channel.disconnect()
    

    参考资料:

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2019-04-08
      • 1970-01-01
      • 2021-06-16
      • 2020-11-22
      • 2016-11-07
      • 2021-04-04
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多