Hello I tried making a Discord bot with ChatGPT for funn and dont have any knowledge of Python. Can anybody tell me what the problem with my code is.
So the bot runs normal and vs Code is not giving me any errors but if i type *play url... in my discord nothing happens.
this is my Code:
import discord from discord.ext import commands import youtube_dl
intents = discord.Intents.default() intents.members = True
bot = commands.Bot(command_prefix='*', intents=intents)
@bot.command() async def play(ctx, *, query): voice_channel = ctx.author.voice.channel if not voice_channel: await ctx.send("You are not connected to a voice channel") return
permissions = voice_channel.permissions_for(ctx.me)
if not permissions.connect or not permissions.speak:
await ctx.send("I don't have permission to join or speak in that voice channel.")
return
voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if not voice_client:
await voice_channel.connect()
voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)
with youtube_dl.YoutubeDL() as ydl:
info = ydl.extract_info(query, download=False)
url = info['url']
title = info['title']
ffmpeg_options = {
'options': '-vn'
}
voice_client.play(discord.FFmpegPCMAudio(url, **ffmpeg_options), after=lambda e: print(f'Finished playing: {e}'))
await ctx.send(f'**Now playing:** {title}')
bot.run('my token')
So as Peterrrrrrr said you need to format your code right and dont use chat gpt since its data is limited and it provides too much errors. I made some changes to your code so it can join the voice channel when a user is already in a voice channel. If not the user gets a message. For the playing part i also made some changes, but you will most likely get a error since youtube_dl isnt working anymore due to a youtube update, so uninstall youtube_dl with pip uninstall youtube_dl
then install the master branch from github with pip install git+https://github.com/ytdl-org/youtube-dl.git@master#egg=youtube_dl
(you need git for this, download it here). In order to let the bot play music you need to install PyNaCl
and discord.py[voice]
. Also make sure to install asyncio
we need this for the music part.
pip install PyNaCl
pip install discord.py[voice]
pip install asyncio
Last but not least you need a ffmpeg executable on your computer. Download ffmpeg here. Extract the zip and search for ffmpeg.exe inside the bin folder then move it to the same directory where your bot file is located. Here is your updated code with comments:
import discord
from discord.ext import commands
import youtube_dl
import asyncio
intents = discord.Intents.default()
intents.members = True
intents.message_content = True #needed for your bot
bot = commands.Bot(command_prefix='*', intents=intents)
#These are options for the youtube dl, not needed actually but are recommended
ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0',
'force-ipv4': True,
'preferredcodec': 'mp3',
'cachedir': False
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdlopts)
@bot.command()
async def play(ctx, *, query):
try:
voice_channel = ctx.author.voice.channel #checking if user is in a voice channel
except AttributeError:
return await ctx.send("No channel to join. Make sure you are in a voice channel.") #member is not in a voice channel
permissions = voice_channel.permissions_for(ctx.me)
if not permissions.connect or not permissions.speak:
await ctx.send("I don't have permission to join or speak in that voice channel.")
return
voice_client = ctx.guild.voice_client
if not voice_client:
await voice_channel.connect()
voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)
loop = asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url=query, download=False)) #extracting the info and not downloading the source
title = data['title'] #getting the title
song = data['url'] #getting the url
if 'entries' in data: #checking if the url is a playlist or not
data = data['entries'][0] #if its a playlist, we get the first item of it
try:
voice_client.play(discord.FFmpegPCMAudio(source=song,**ffmpeg_options, executable="ffmpeg")) #playing the audio
except Exception as e:
print(e)
await ctx.send(f'**Now playing:** {title}') #sending the title of the video
bot.run('my token')
I've tested this code and it should work for you. If there are any errors etc. let me know.