voltifer
voltifer

Reputation: 19

I am trying to make a bot that plays an mp3 file by a command but it doesn't work with no error

I made so it connects to the voice channel by the command .join and it supposed to play a sound that i saved. This is made for a voice channel with chill music so that they don't have to copy and paste a YouTube link. I am using python 3.9

import discord
from discord.ext import commands

bot = discord.Client()
bot = commands.Bot(command_prefix=".") 

@bot.command()
async def join(ctx):

    if ctx.author.voice is None:
        await ctx.send("You are not in a voice channel")
    voice_channel = ctx.author.voice.channel

    if ctx.voice_client is None:
        await voice_channel.connect()
        guild = ctx.guild
        voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
        audio_source = discord.FFmpegPCMAudio('music.mp3')
    
        if not voice_client.is_playing():
            voice_client.play(audio_source, after=None)
    else:
        await ctx.voice_client.move_to(voice_channel)

bot.run("token")

Upvotes: 0

Views: 105

Answers (1)

Aditya Tomar
Aditya Tomar

Reputation: 1639

Try this instead:

import discord
from discord.ext import commands
from youtube_dl import YoutubeDL

bot = discord.Client()
bot = commands.Bot(command_prefix=".")

@bot.command()
async def join(ctx):

    if ctx.author.voice is None:
        await ctx.send("You are not in a voice channel")
        return
    
    voice_channel = ctx.author.voice.channel

    if ctx.voice_client is None:
        await voice_channel.connect()
    else:
        await ctx.voice_client.move_to(voice_channel)

    audio_source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio('music.mp3'))

    if not ctx.voice_client.is_playing():
        ctx.voice_client.play(audio_source, after=lambda e: print('Player error: %s' % e) if e else None)

bot.run("token")

Upvotes: 1

Related Questions