【发布时间】: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