【问题标题】:How can I make the bot leave the voice channel when there is only itself?当只有它自己时,如何让机器人离开语音通道?
【发布时间】:2022-06-10 19:59:09
【问题描述】:

我想创建一个机器人,它可以在没有其他人的情况下加入语音通道并离开语音通道。当不活动时,我也希望它离开频道。另外,当机器人已经在语音通道中时,我第二次键入 join 命令时,它给了我错误,我该如何解决这个问题?

import os
import discord
from discord.ext import commands
import asyncio
import youtube_dl

intents = discord.Intents.default()
intents.members = True


bot = commands.Bot(command_prefix='?', intents=intents)


@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')


@bot.command()
 async def add(ctx, left: int, right: int):
 """Adds two numbers together."""
 await ctx.send(left + right)

@bot.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
@bot.command()
async def leave(ctx):
await ctx.voice_client.disconnect()

@bot.command
async def on_voice_state_update(member, before, after):

**voice_state = member.guild.voice_client
if voice_state is None:
   # Exiting if the bot it's not connected to a voice channel
   return 

 if len(voice_state.channel.members) == 1:
  await member.send("I can't stay alone!")
  await voice_state.disconnect()**

 @bot.Cog.listener() 
 async def on_voice_state_update(self, member, before, after)
 if not member.id == self.bot.user.id:
 return

 **elif before.channel is None:
  voice = after.channel.guild.voice_client
  time = 0
    while True:
    await asyncio.sleep(1)
    time = time + 1
    if voice.is_playing() and not voice.is_paused():
        time = 0
    if time == 600:
        await voice.disconnect()
    if not voice.is_connected():
        break**


@bot.command(name='play_song', help='To play song')
async def play(ctx):
  try :
   server = ctx.message.guild
   voice_channel = server.voice_client
   async with ctx.typing():**strong text**
       filename = await       youtube_dl.from_url('https://www.youtube.com/watch?v=NAHRpEqgcL4', loop=bot.loop)
                  voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename))
await ctx.send('**Now playing:** {}'.format(filename))
   except:
       await ctx.send("The bot is not connected to a voice channel.")

    bot.run('TOKEN')

【问题讨论】:

  • 这能回答你的问题吗Link
  • 你得到什么错误?你能发送完整的回溯吗?

标签: python discord discord.py


【解决方案1】:

我不认为这会帮助你回答这个问题,但这是我如何在只有机器人留在语音频道时自动断开连接的方式。如果您需要在等待断开连接时让机器人休眠,只需将 asyncio.sleep(time) 放在 await channel.disconnect 之前即可

@tasks.loop(seconds=10)
async def autodc(self):
    channel_lsit = self.client.voice_clients
    try:
        for channel in channel_lsit:
            total = len(channel.channel.members)
            if total == 1:
                await channel.disconnect()
    except:
        pass

【讨论】:

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