Adding Buttons to Discord Messages Using Python Pycord

Adding Buttons To Discord Messages In Python

Buttons are an important part of messaging nowadays. In discord, the button feature of in a message was added recently to make some tasks like playing or pausing music easier. When adding bots, using the discord developer’s portal and python, we now have the provision of adding buttons to our messages after bot creation.

Also, the updated python version makes it simpler to use the discord.py library. The pycord library also provides a huge range of functionality in discord. Let’s look at how we can add the button feature to our bot in our favorite server!

Prerequisites for setup

After the 2021 update of discord, it has made bot feature creations easier. We cannot include buttons directly in our messages on discord but it can be done using a bot. Hence to make use of the newly added feature we need updated modules in our system.

Run the following code in your command prompt to install/update the discord.py module in your system. it is advisable to run the command prompt in the administrator mode.

pip install discord

The discord.py is a free to use API that helps in connecting python to discord. It has await() and async() functions that makes the life of all programmers easier. It increase the speed of a program and also optimizes memory usage.

Also read : Python Twilio – Automate WhatsApp Business API Messages.

Setting up the environment

I have used the online cloud based IDE called replit to code the bot shown in this tutorial. You can use any IDE or editor of your choice.

Now, we will have to visit the discord developer portal and create a new application for our bot. Then follow the standard procedure to create a discord bot. Follow this step by step tutorial to know how to create a discord bot. In addition to bot creation, make sure you check the “use slash command” box in the OAuth2 tab so that we can use the commands function from discord.py .

Use Slash Commands
Use Slash Commands

The code for implementing a button in our discord bot

So, after creating the bot and successfully adding it to our respective server, we will look into the code for implementing the code.

I have my own “robot python server” where my bot “LP” has been added. I will modify that bot and add buttons to its messages. The button will redirect us to join the server where the bot has been added.

Let us look at the code for the same.

#importing required modules
import os
import discord
from discord.ext import commands

#enabling all intents 
intent = discord.Intents().all()
#deciding when the bot responds
bot = commands.Bot(command_prefix="!", intents=intent)
 
#first event :logging in
@bot.event
async def on_ready():
  #displaying that the bot has logged in
  print("successful login as {0.user}".format(bot))

#defining the class for creating a button
class Invitebutton(discord.ui.View):
  #creating the button function
  def __init__(self, inv: str):
    super().__init__()
    #collecting the url of the current server
    self.inv=inv
    self.add_item(discord.ui.Button(label="Invite link", url=self.inv))
  #features of the button
  @discord.ui.button(label="Invite", style=discord.ButtonStyle.blurple)
  async def invite(self, interaction: discord.Interaction , button : discord.ui.Button):
    await interaction.response.send_message(self.inv,ephemeral=True)

#defining command of the bot
@bot.command()
async def invite(ctx: commands.Context):
  inv=await ctx.channel.create_invite()
  await ctx.send("click to invite!", view=Invitebutton(str(inv)))
 
#getting the secret token
bot.run(os.getenv('token'))

The flow of the code can be described by the bullet points as given below;

  • The first part of the code imports the required modules.
  • The second part enables all the message intents to enable permissions.
  • Making sure that the bot responds to messages which start with the exclamation mark followed by the word “invite”, since the bot is going to send a button redirecting a user with an invite to the server.
  • Next, we make sure that the bot is online.
  • The class invitebutton() defines the entire structure of our button object starting from its characteristics to its functionality. It contains the required functions and features of the message that will be sent by our bot.
  • The next part defines the slash commands that will be used by our bot for proper functioning.
  • And the last line is for extracting the “token” or the address of the bot in order to access it.

After running the code, there should be a message displayed in our terminal as shown below:

2023-02-24 07:47:06 INFO     discord.client logging in using static token
2023-02-24 07:47:07 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 07bc35e1a46501ef615a0c19b40b6c17).
successful login as LP69#9180
Running The Code And Console Display
Running The Code And Console Display

If you open your server with your bot in it in discord, you can see that your bot is online. I have marked its status with a light blue arrow for you to easily locate it.

Bot Is Online
Bot Is Online

Now, if you type the message “!invite” the bot should respond with a message containing a button and a message invitation. Upon clicking the Invite button, you should see something as shown below:

Message With Button!
Message With Button!

VOILA! you have successfully incorporated buttons in your bot in discord!

Summary

This tutorial is meant to make the process of adding buttons to discord simpler. Since the launch of this new feature on discord in 2021, adding buttons with the help of discord.py has increasingly become easier and hassle free. We have provided you with the code for button creation and it is relatively easy. We hope you found the solution you were looking for!