Discord Bot Python Tutorial – Play Music and Send Gifs

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

How To Install & Use Rythm Musi...
How To Install & Use Rythm Music Bot on your Discord Channel

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.

Why is Discord Popular?

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.  

  • Channel: Text and voice channels are servers Discord relies on to transmit information. Users can exchange photographs, upload files, and publish messages in text channels at any time for other people to see. Additionally, users can go “live” in voice channels, where they can show their screen with peers and interact through voice or video chat in real-time.
  • DMs and GDMs: Users can initiate voice or video calls as well as send private messages to other users as direct messages (DM). Group Direct Messages are private and accessible only by invitation from a group member.
  • Server: Discord’s spaces are called servers. Particular communities and cliques create them. A new server can be set up by any user for no cost, and they can invite their friends to join.
  • Nitro: Nitro is Discord’s premium subscription service. It enables users to customize Discord Tag, use custom emotes on every server, have a higher file upload cap, and discounted Server Boosts. 
  • Server Boosts:  Dual to Nitro, Server Boosts grant servers exclusive benefits, including more personalized emotes, improved voice and video quality, and the capacity to set a personalized invite link.
  • Student Hubs: Students can choose servers for study groups or classes, connect with other verified students, and share their own servers with other students using Discord Hubs for Students. 

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

  • Developing an active community is made simpler by Discord bots.
  • When you’re briefly unavailable online, it takes your place. It acquaints new players with your server and moderately satisfies some of their needs.
  • You can utilize them to include games, music, memes, and other fun material.
  • Discord bots help to enhance your server and foster a better community, making users stay and engage with you more.

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. 

  • Visit the official website of Discord to register; or log in if you are an old user
  • Select “New Application” and then enter a name for the program before clicking “Create.”
  • Create a Bot User by visiting the “Bot” page and clicking “Add Bot.”
  • To move forward, click “Yes, go ahead!”
  • Check the Public Bot button.
  • Do not check the OAuth2 Code button unless you’re developing a service that requires you to. If you’re unsure of its functionality, leave it unchecked.
  • If you don’t already have a token, just hit the Reset button to create one. Keep this token ID safe because we’ll need it later.

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.

  • Visit the application page, and click on your newly created bot page
  • Select the “OAuth2” tab.
  • To discover your CLIENT ID, locate the OAuth2 option in the menu on the left sidebar and click on it. Ensure you copy the lengthy string of numbers and paste them into the URL.
  • You’ll notice a message verifying the bot’s arrival after you add it to your server. The bot icon appears on the right-hand side of your Discord application.

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

@bot.command(name="hi")
async def SendMsg(ctx):
  await ctx.send('Hello, Who is am i with on the best chat platform?')

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

    if __name__ == '__main__':
      #please paste your own special token here
      bot.run("OTYwrdgffhhHHVGYFTFgjh.YuygTY.urPO_JSSDvbHFJBVssdfdgbJ")

#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

  @bot.command(name="pic")
  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": "0.0.0.0",

}

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
  @classmethod
  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) 
  @commands.command()
  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
  @commands.command()
  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
  @commands.command()
  async def yt(self, ctx, *, url):
    player = await YTDLSource.from_url(url, loop=self.bot.loop)
    ctx.voice_client.play(
        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
  @commands.command()
  async def stream(self,ctx, *, url):
    async with ctx.typing():
      player = await YTDLSource.from_url(url, loop=self.bot.loop, stream= True)
      ctx.voice_client.play(
          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 
  @commands.command()
  async def stop(self, ctx):
    await ctx.voice_client.disconnect()

  @play.before_invoke
  @yt.before_invoke
  @stream.before_invoke
#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()
      else:
        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():
      ctx.voice_client.stop()


#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) 
bot.add_cog(Music(bot))

#copy the secret keys for the hot app and paste here 
bot.run("OTYwrdgffhhHHVGYFTFgjh.YuygTY.urPO_JSSDvbHFJBVssdfdgbJ")


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

Conclusion

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.

Leave a Comment

Your email address will not be published.