如何检查不和谐机器人是不是在语音或已连接

Posted

技术标签:

【中文标题】如何检查不和谐机器人是不是在语音或已连接【英文标题】:How to check is discord bot is in voice or already connected如何检查不和谐机器人是否在语音或已连接 【发布时间】:2021-03-07 21:52:33 【问题描述】:

我正在构建一个机器人,该机器人需要连接到语音通道,这是我的代码:

import discord
from discord.ext import commands
from discord.utils import get

b = commands.Bot(command_prefix=".")

@b.event
async def on_ready():
    print("Bot is logged in")

@b.command(pass_context=True, aliases=['j'])
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(b.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
        await ctx.send("Moved to the voice channel")

    elif #Check if the user is in the voice channel and the bot is not:
        voice = await channel.connect()
        await ctx.send("Connected to the voice channel")

    elif #Check if the user is in the voice channel
        await ctx.send("**Get in a voice channel**")

    elif #Check if the bot is already in the channel
        await ctx.send("**Already in the channel**")

b.run("stack overflow")

所以在进入语音通道之前我想检查几件事,我想出了如何连接并从不同的语音通道移动但被困在那里,我是 python 的新手,所以如果我的代码可以简化任何建议将不胜感激。

【问题讨论】:

第一个问题,检查人是否有VoiceState,检查机器人是否也有VoiceState,如果用户没有语音状态,请他加入语音频道,第三个,同if voice and voice.is_connected(): 【参考方案1】:
@b.command(aliases=['j'])
async def join(ctx):
    bot_voice = ctx.guild.voice_client
    author_voice = ctx.author.voice

    if bot_voice and bot_voice.is_connected():
        await voice.move_to(author_voice.channel)
        await ctx.send("Moved to the voice channel")

    elif author_voice and not bot_voice: # Author connected but bot not connected
        voice = await author_voice.channel.connect()
        await ctx.send("Connected to the voice channel")

    elif not author_voice: # Author not connected
        await ctx.send("**Get in a voice channel**")

    elif ctx.bot.user in author_voice.channel.members # Bot and Author both connected
        await ctx.send("**Already in the channel**")

顺便说一句,请不要命名你的机器人 b,它是 bad practice

【讨论】:

以上是关于如何检查不和谐机器人是不是在语音或已连接的主要内容,如果未能解决你的问题,请参考以下文章

有没有办法让我的不和谐机器人在播放完歌曲后断开与语音频道的连接?

如何检查字符串是不是包含在数组中?不和谐.js

不和谐.JS |检查频道是不是存在票务机器人

如果在某个语音频道中,需要帮助断开成员的连接

如何在频道列表中指定语音频道的位置?不和谐.py

如何让不和谐的机器人获取昵称而不是用户名?