How Code Discord Bot To Play Youtube Python
In this tutorial, we'll make a Python Discord bot that can play music in the voice channels and send GIFs. Discord is an instant messaging and digital distribution platform designed for creating communities. Users can easily enter chat rooms, initiate video calls, and create multiple groups for messaging friends.
Nosotros'll skip the basics and jump straight over to the music playing. Check out this Medium article to catch upwards on the basics of setting up your bot. In the cease, our Python Discord bot will expect like the cover image of this article!
Before we dive in: remember to allow Ambassador permissions for the bot.
Thanks to Rohan Krishna Ullas, who wrote this guest tutorial! Make sure to check out his Medium profile for more manufactures from him. If you want to write for Python Land too, please contact united states.
Part 1: Importing all the libraries
Starting time, create a virtual environs and install the requirements:
discord==1.0.1 discord.py==one.6.0 python-dotenv==0.15.0 youtube-dl==2021.2.10
Next, let's prepare the.env file for our project. Create a.env file then that we can separate the environs configuration variables (these are variables whose values are set outside the program) from the main lawmaking:
discord_token = "copy_paste_your_bot_token_here"
Then use Python import to load all the needed modules in the main file app.py:
import discord from discord.ext import commands,tasks import os from dotenv import load_dotenv import youtube_dl
The module youtube_dl is an open up-source download manager for video and sound content from YouTube and other video hosting websites.
Now we need to gear up intents for our bot. Intents permit a bot to subscribe to specific buckets of events, allowing developers to choose which events the bot listens to and to which it doesn't. For example, sometimes we desire the bot to heed to but messages and nothing else.
Thank you for reading my tutorials. I write these in my free time, and it requires a lot of time and attempt. I use ads to go along writing these free articles, I promise yous empathize! Support me by disabling your adblocker on my website or, alternatively, buy me some coffee. Information technology's much appreciated and allows me to keep working on this site!
load_dotenv() # Get the API token from the .env file. DISCORD_TOKEN = os.getenv("discord_token") intents = discord.Intents().all() client = discord.Client(intents=intents) bot = commands.Bot(command_prefix='!',intents=intents) Function 2: Using youtube_dl to download audio
The next step in building our Python Discord bot is dealing with the office that really downloads the audio file from the video link we provide. Delight note that this bo is merely a demonstration. It'due south non illegal to download from YouTube for personal employ co-ordinate to this article, simply information technology might be against the YouTube Terms Of Service. Please be sensible and use this for personal use only.
youtube_dl.utils.bug_reports_message = lambda: '' ytdl_format_options = { 'format': 'bestaudio/all-time', 'restrictfilenames': True, 'noplaylist': True, 'nocheckcertificate': True, 'ignoreerrors': Imitation, 'logtostderr': False, 'tranquillity': True, 'no_warnings': True, 'default_search': 'automobile', 'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses crusade issues sometimes } ffmpeg_options = { 'options': '-vn' } ytdl = youtube_dl.YoutubeDL(ytdl_format_options) class YTDLSource(discord.PCMVolumeTransformer): def __init__(self, source, *, information, volume=0.5): super().__init__(source, volume) cocky.data = data self.title = information.get('title') self.url = "" @classmethod async def from_url(cls, url, *, loop=None, stream=False): loop = loop or asyncio.get_event_loop() information = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=non stream)) if 'entries' in data: # accept showtime particular from a playlist data = information['entries'][0] filename = data['title'] if stream else ytdl.prepare_filename(data) return filename The from_url() method of YTDLSource class takes in the URL every bit a parameter and returns the filename of the audio file which gets downloaded. You lot can read the youtube_dl documentation at their GitHub repository.
Part three: Adding commands to the Python Discord bot
At present let'southward add the bring together() method to tell the bot to bring together the voice channel and the leave() method to tell the bot to disconnect:
@bot.command(proper noun='bring together', help='Tells the bot to join the voice channel') async def bring together(ctx): if not ctx.message.author.phonation: await ctx.send("{} is not continued to a voice aqueduct".format(ctx.message.author.name)) return else: channel = ctx.message.author.vocalism.channel await channel.connect() @bot.command(name='exit', help='To make the bot exit the vocalism channel') async def leave(ctx): voice_client = ctx.message.guild.voice_client if voice_client.is_connected(): await voice_client.disconnect() else: await ctx.send("The bot is non connected to a vox channel.") Here we beginning check if the user who wants to play music has already joined the voice channel or not. If not, we tell the user to join first.
Awesome! Requite yourself a pat on the dorsum if you've reached this far! You're doing great. In the side by side footstep, we'll add the post-obit methods:
- play()
- pause()
- resume()
- end()
@bot.control(name='play_song', help='To play song') async def play(ctx,url): try : server = ctx.bulletin.guild voice_channel = server.voice_client async with ctx.typing(): filename = await YTDLSource.from_url(url, loop=bot.loop) voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename)) wait ctx.transport('**Now playing:** {}'.format(filename)) except: wait ctx.send("The bot is not connected to a voice channel.") @bot.command(name='interruption', help='This command pauses the song') async def pause(ctx): voice_client = ctx.message.gild.voice_client if voice_client.is_playing(): await voice_client.interruption() else: await ctx.send("The bot is not playing annihilation at the moment.") @bot.control(proper name='resume', assistance='Resumes the song') async def resume(ctx): voice_client = ctx.bulletin.guild.voice_client if voice_client.is_paused(): wait voice_client.resume() else: await ctx.send("The bot was not playing anything before this. Use play_song control") @bot.command(name='stop', help='Stops the vocal') async def stop(ctx): voice_client = ctx.message.guild.voice_client if voice_client.is_playing(): await voice_client.finish() else: await ctx.send("The bot is not playing anything at the moment.") At this point, nosotros demand to have the ffmpeg binary in the base directory. Information technology tin can be downloaded from https://ffmpeg.org/. In this case, I used the exe since I'm using a Windows automobile.
Part 4: Running the Python Discord bot locally
Add the final piece of code to commencement the bot and it's done:
if __name__ == "__main__" : bot.run(DISCORD_TOKEN)
To deploy the bot locally, activate the virtual environs and run the app.py file:
(venv1) C:\Github\Discord-Bot>python app.py
Bonus: send GIFs on start-upwardly and print server details
In this bonus section, nosotros will fix our bot to listen to events such equally start-up. This example sends a previously downloaded GIF epitome to the text channel when the bot is activated:
@bot.event async def on_ready(): for guild in bot.guilds: for aqueduct in gild.text_channels : if str(aqueduct) == "general" : await channel.send('Bot Activated..') wait channel.transport(file=discord.File('add_gif_file_name_here.png')) print('Active in {}\due north Member Count : {}'.format(guild.name,social club.member_count)) To print server details such as owner name, the number of users, and a server id, we can add a bot command 'where_am_i':
@bot.command(help = "Prints details of Server") async def where_am_i(ctx): owner=str(ctx.guild.possessor) region = str(ctx.club.region) guild_id = str(ctx.order.id) memberCount = str(ctx.guild.member_count) icon = str(ctx.guild.icon_url) desc=ctx.social club.clarification embed = discord.Embed( title=ctx.order.name + " Server Data", clarification=desc, colour=discord.Color.blue() ) embed.set_thumbnail(url=icon) embed.add_field(name="Owner", value=owner, inline=True) embed.add_field(name="Server ID", value=guild_id, inline=True) embed.add_field(proper noun="Region", value=region, inline=True) embed.add_field(name="Member Count", value=memberCount, inline=True) await ctx.send(embed=embed) members=[] async for fellow member in ctx.lodge.fetch_members(limit=150) : expect ctx.ship('Name : {}\t Status : {}\north Joined at {}'.format(member.display_name,str(member.status),str(member.joined_at))) @bot.command() async def tell_me_about_yourself(ctx): text = "My name is WallE!\n I was congenital past Kakarot2000. At nowadays I have limited features(notice out more past typing !help)\due north :)" await ctx.ship(text) This is what this volition look like:
Y'all can view and clone the complete results from my Discord-Bot GitHub Repository.
That's it! Nosotros made a Python Discord bot. Cheers for reading, and don't hesitate to leave a reply or enquire your questions in the comments section.
My Python course for beginners 👊
Practice you enjoy these free articles? Please have a look at my premium Python course for beginners for the best experience! Information technology includes:
Like shooting fish in a barrel to digest lessons
Quizzes to examination your knowledge
PDF document of completion
Source: https://python.land/build-discord-bot-in-python-that-plays-music
Posted by: browningfroppres.blogspot.com

0 Response to "How Code Discord Bot To Play Youtube Python"
Post a Comment