Discord Bot Python Tutorial – Play Music and Send Gifs

By Tanner Abraham •  Updated: 09/07/22 •  12 min read

Do you find it surprising that Discord has become well-known in the digital and business world? There are good reasons why it currently dominates the social media scene. It enhances social media interaction, chatting, gaming, or simply interacting with business organizations.

Millions of people use Discord daily, and a considerable percentage regularly automate tasks using bots. These bots are making Discord one of the best social messaging platforms for different industries. 

 Let’s dive in!

Table of Contents

What is Discord?

Discord is a social application that offers free phone, video, and text communication. It is one of the most well-known social networking sites used by millions of people to communicate and hang out with their friends and neighbors

People frequently use Discord to talk about a range of subjects, such as family vacations, homework assistance, NFTs, cryptocurrencies, the Metaverse, and mental health support. Any sized group of people can call it home, but the tiniest, chattiest groups use it the most regularly.

It gives public communities the platform to interact. People have complete control over who they interact with and how they use Discord because all discussions are opt-in.

It includes servers that are exclusive and private channels where communities and friendship circles can communicate and socialize and hold events. 

Discord, however, swiftly gained popularity among gamers after its initial 2015 release by Jason Citron and Stanislav Vishnevskiy. The two co-founders wanted to create a better communication tool while working in the video game industry.

Even though it has been seeing yearly user growth since its launch in 2015, Discord’s popularity increased in 2018 as streaming and online gaming began to expand quickly.

Discord’s connection with Xbox was the second significant action following its launch. It was a truly great experience for users to connect their Xbox Live accounts with their Discord servers. But by 2020, everyone was familiar with Discord.

Its fast popularity is due to the convenience it provides to players and streamers worldwide. Since then, Discord has become a well-liked platform for connecting with loved ones and having simple conversations.

Discord achieved quick popularity, unlike many other similar messaging applications. Because it serves as a home for all communities and friendship groups, people adore Discord. They may be themselves there while socializing with others who appreciate the same things they do.

On Discord, conversations are stimulated by common interests from people who share a similar view on a topic. Discord provides different communication options for like minds to interact in the best way they can use to understand themselves.

Terms Associated With Discord

Discord users occasionally utilize some terminology when referring to some of the activities on the platform. Below are examples of some of these terminologies.  

Is Discord Free?

Discord is without communication limitations. Access to communities is unrestricted, and starting your server is also cost-free.

You’ve probably heard of Discord bots if you use the platform for business purposes. With the help of these AI-powered bots, you can carry out different tasks, such as welcoming new users or people in search of your service.

It is a helpful tactic for online marketers who are learning how to use it to their advantage. Discord bots may be the way to go if you’re searching for a distinctive and interesting approach to interacting with your community.

What is a Discord Bot?

Discord bots are top A.I.s used by marketers and business owners to perform a range of automated tasks on the server. Discord bots can manage the discussion, filter material, automatically welcome new users, and ban disruptive individuals. Some bots even add music or games to your server.

They are amiable AI that supports server management or service enhancement. Discord bots are pre-made and free to download — no computer skills necessary. 

You can back up your business information that the bot emulates in a database.

MongoDB is a popular database you can use for this purpose, although storing data in MongoDB is an activity among experienced programmers coding these bots. So this may require that only top programmers handle this process.

Benefits of Discord Bots

Steps to Creating a Discord Bot With Python using Nextcord.py

First, you need to enable the bot from the Discord application. Make your Python environment function going there next. Then go to your Python environment to make it functional.

To set everything up, you do need a basic understanding of programming, although the complexity of the code may vary depending on the type of bot you’re building.

Let’s look at some of the prerequisites for getting started. You must first have a Discord account, which you undoubtedly already do. If not, visit the Discord webpage to create one at no cost. The Discord client is also available for download, and you may use it on a phone or your gaming laptop.

To start with the bots creation, let’s enable it first from the server. 

So that’s it, you can log in to your newly created bot account.

Even though you created a bot user, it isn’t truly present in any servers. We need to do one more thing.

It’s time to finish developing your app. To test the functionality of your bot, open the Python source code.

Sample Codes for Discord Bots in Python

A. Sample Codes to make Discord Bots Respond to Greetings

from nextcord.ext import commands

bot = commands.Bot(command_prefix="!")

# make the bot to greet the user

async def SendMsg(ctx):
  await ctx.send('Hello, Who is am i with on the best chat platform?')

  async def on_ready():
    print(f"logged in as: {bot.user.name}")

    if __name__ == '__main__':
      #please paste your own special token here

#run your program and go back to discord

B. Sample Codes to Make a Discord Bots Send Gifs

from nextcord.ext import commands

bot = commands.Bot(command_prefix="dog ")

#The aim is to make our bot send dog pictures whenever we enter dog pic
#We will be visiting the Dog API website to copy the APi address that returns a JSON containing the link
# we will be using a python module called request to make this request from the dog server

  async def Dog(ctx):
    response = request.get("https://dog.ceo/api/breeds/image/random")
    Pic_link = response.json()["message"]
    await ctx.send(Pic_link)

#run your program and go back to discord to test, on discord type dog pic

C. Sample Codes to make Discord Bots Play Music

import nextcord
import asyncio
import youtube_dl
from nextcord.ext import commands

#remember to do pip install youtube_dl if you have not

youtube_dl.utils.bug_reports_message = lambda: ""

#this acts like a schema for youtube files, just copy and paste on this format 
ytdl_format_options = {
  "format": "bestaudio/best",

  "outtmpl": "%(extractor)s-%(id)s-%(title)s.%(ext)s",

  "restrictfilename": True,

  "noplaylist": True,

  "nocheckcertificate": True,

  "ignoreerrors": False,

  "logtostderr": False,

  "quiet": True,

  "no_warning": True,

  "default_search": "auto",

  "source_address": "",


ffmpeg_options = {"options": "-vn"}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)

#this function will get a download from a Url to allow the bot get youtube Url and download that and play it through the bot
class YTDLSource(nextcord.PCMVolumeTransformer):
  def__init__(self, source: *, data, volume = 0.5):
    super().__init__(source, volume)

    self.data = data
    self.title = data.get("title")
    self.url = data.get("url")

#this method is basically returning the file so it can be played through the bot
  async def from_url(cls, url, *, loop=None, stream=False):
    loop = loop or asyncio.get_event_loop()
    data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

    if "entries" in data:
      data = data["entries"][0]

    filename = data["url"] if stream else ytdl.prepare_filename(data)
    return cls(nextcord.FFmpegAudio(filename, **ffmpeg_options), data=data)

#this class holds all the commands for the music bot
class Music(commands.Cog):
  def __init__(self, bot):
    self.bot = bot

#this method joins the command and makes the connection to the channel(on your bot enter $join to join channel) 
  async def join(self, ctx, *, channel: nextcord.VoiceChannel):
    if ctx.voice_client is not None:
      return await ctx.voice_client.move_to(channel)
    await channel.connect()

#method to automate the bot to play the file it fetches
  async def play(self, ctx, *, query):
    source = nextcord.PCMVolumeTransformer(nextcord.FFmpegPCMAudio(query))
    ctx.voice_client.play(source, after= lambda e: print(f"player error": {e}") if e else None)

    await ctx.send(f"Now playing: {query}")
#this command gets the YouTube link and makes the download before the music plays
  async def yt(self, ctx, *, url):
    player = await YTDLSource.from_url(url, loop=self.bot.loop)
        player, after=lambda e: print(f"Player error: {e}") if e else None

    await ctx.send(f"Now playing...: {player.title}")

#the stream command ensures that the bot do not make downloads before playing the songs if it receives a stream command
  async def stream(self,ctx, *, url):
    async with ctx.typing():
      player = await YTDLSource.from_url(url, loop=self.bot.loop, stream= True)
          player, after=lambda e: print(f"player error: {e}") if e elase None

    await ctx.send(f"now playing: {player.title}")
#this method stops the music 
  async def stop(self, ctx):
    await ctx.voice_client.disconnect()

#check if the user gets is connected or not
  async def e_voice(self, ctx):
    if ctx.voice_client id None:
      if ctx.author.voice:
        await ctx.author.voice.channel.connect()
        await ctx.send("oppps, you are not connected to a voice channel currently")
        raise commands.CommandError("Author is absent on a voice channel")
    elif ctx.voice_client.is_playing():

#set up the bot so that we can actually run it
intents = nextcord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix = "!", intents= intents) 

#copy the secret keys for the hot app and paste here 

#at the end of the code, a file will be downloaded on your visit when you run the code for the first time


Using Discord bots is a cutting-edge and effective digital marketing tactic. Discord bots make your discord server lively and active. Additionally, they operate round-the-clock.

Dive deeper into creating Discord Bots in Python using Discord.py.

Tanner Abraham

Data Scientist and Software Engineer with a focus on experimental projects in new budding technologies that incorporate machine learning and quantum computing into web applications.