Reputation: 9
I'm creating a simple bot that should enter the voice channel on the !play
command and play a random track from the "music" directory. But there is a problem in the line vc = await voice_channel.connect()
, I think. Because he reacts to the command and enters the voice channel, but the program does not go further at all. Those. the print does not print, the music does not play, and so on. Here is the code itself:
import discord
from discord.ext import commands
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)
# Bot readiness check
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
# Command to play music
@bot.command(name='play')
async def play(ctx):
voice_channel = ctx.author.voice.channel
vc = await voice_channel.connect()
print('Connected')
# Picking a random file from a directory
music_files = os.listdir('music')
random_song = os.path.join('music', random.choice(music_files))
# Playing an audio file
vc.play(discord.FFmpegPCMAudio(random_song), after=lambda e: print('Error:', e) if e else None)
await ctx.send(f'Now playing: {random_song}')
# Waiting for the end of the track
while vc.is_playing():
await asyncio.sleep(1)
# Disconnecting from a voice channel
await vc.disconnect()
await ctx.send(f'Finished playing: {random_song}')
bot.run('token')
If I understand correctly, then await
stops the execution of the current program and waits until the function following it is executed. So the problem is in the connection function itself, but the bot enters the channel, which is strange. There is an idea that it doesn’t go all the way, because in the discord, when you enter the channel, you can see many different connections. Could it be that the python environment is preventing it from connecting?
Upvotes: 0
Views: 548
Reputation: 62
I think the problem is with line vc = await voice_channel.connect()
This line is asynchronous, which means that it will return immediately and continue executing the rest of the code, even though the connect() method has not yet finished. May be try using async with in order to ensure that asynchronous operation is completed before rest of code gets executed
Upvotes: -1