Make Your Discord Bot Read and Send Messages in Discord.py

This tutorial will show you lot how to build your own Discord bot completely in the cloud.

Y'all do not demand to install anything on your figurer, and you do not need to pay annihilation to host your bot.

We are going to use a number of tools, including the Discord API, Python libraries, and a deject computing platform called Repl.it.

There is also a video version of this written tutorial. The video is embedded below and the written version is afterwards the video.

How to Create a Discord Bot Business relationship

In lodge to work with the Python library and the Discord API, we must first create a Discord Bot account.

Here are the footstep to creating a Discord Bot account.

1. Brand sure yous're logged on to the Discord website.

ii. Navigate to the application folio.

3. Click on the "New Application" push.

image-117

4. Give the awarding a proper noun and click "Create".

image-118

5. Go to the "Bot" tab and then click "Add Bot". Yous volition accept to confirm by clicking "Aye, do information technology!"

image-119

Go along the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked).

Your bot has been created. The adjacent pace is to re-create the token.

image-122

This token is your bot's password so don't share it with anybody. It could allow someone to log in to your bot and practice all sorts of bad things.

You can regenerate the token if it accidentally gets shared.

How to Invite Your Bot to Join a Server

Now you have to become your Bot User into a server. To do this, you should create an invite URL for it.

Go to the "OAuth2" tab. So select "bot" under the "scopes" section.

image-123

Now choose the permissions you lot desire for the bot. Our bot is going to mainly use text messages so we don't need a lot of the permissions. You may need more than depending on what you lot want your bot to practice. Be careful with the "Administrator" permission.

image-124

After selecting the appropriate permissions, click the 'copy' button above the permissions. That will copy a URL which tin can be used to add the bot to a server.

Paste the URL into your browser, choose a server to invite the bot to, and click "Authorize".

To add the bot, your account needs "Manage Server" permissions.

At present that you've created the bot user, we'll starting time writing the Python code for the bot.

How to Lawmaking a Bones Discord Bot with the discord.py Library

We'll be using the discord.py Python library to write the code for the bot. discord.py is an API wrapper for Discord that makes it easier to create a Discord bot in Python.

How to Create a Repl and Install discord.py

Yous can develop the bot on your local calculator with any code editor. However, in this tutorial, we'll exist using Repl.information technology because it will brand it simpler for anyone to follow along. Repl.information technology is an online IDE that y'all can employ in your spider web browser.

Kickoff by going to Repl.it. Create a new Repl and choose "Python" every bit the language.

To use the discord.py library, simply write import discord at the top of chief.py. Repl.it will automatically install this dependency when you press the "run" push.

If you prefer to code the bot locally, you can employ this control on MacOS to install discord.py:

python3 -yard pip install -U discord.py

You may have to use pip3 instead of pip.

If you are using Windows, then you should use the following line instead:

py -3 -m pip install -U discord.py

How to Set Discord Events for Your Bot

discord.py revolves effectually the concept of events. An outcome is something y'all listen to and so reply to. For example, when a bulletin happens, y'all will receive an event well-nigh information technology that you can respond to.

Let's make a bot that replies to a specific message. This uncomplicated bot lawmaking, forth with the lawmaking explanation, is taken from the discord.py documentation. We will be adding more than features to the bot after.

Add together this code to main.py. (You can name the file something else if you like, just non discord.py.) I'll explain what all this code does shortly.

          import discord import os  client = discord.Client()  @customer.event async def on_ready():     print('We have logged in as {0.user}'.format(client))  @client.event async def on_message(message):     if bulletin.writer == client.user:         return      if message.content.startswith('$howdy'):         await message.channel.send('How-do-you-do!')  client.run(os.getenv('TOKEN'))        

When you lot created your bot user on Discord, yous copied a token. Now we are going to create a .env file to shop the token. If you are running your code locally, you don't need the .env file. Just replace os.getenv('TOKEN') with the token.

.env files are used for declaring environment variables. On Repl.it, about files yous create are visible to anyone merely .env files are only visible to yous.  Other people viewing a public repl will non exist able to run into the contents of the .env file.

And so if yous are developing on Repl.it, just include private information like tokens or keys in a .env file.

Click the "Add file" push and create a file named .env.

image-19-1

Within the file add together the following line, including your actual token you copied previously:

          TOKEN=[paste token here]        

Now permit'south go over what each line of code is doing in your Discord bot code.

  1. The beginning line imports the discord.py library.
  2. The second line imports the os library, but this is merely used for getting the TOKEN variable from the .env file. If you are not using a .env file, you lot do not need this line.
  3. Next, we create an instance of a Client. This is the connection to Discord.
  4. The @customer.event() decorator is used to register an event. This is an asynchronous library, so things are done with callbacks. A callback is a office that is chosen when something else happens. In this lawmaking, the on_ready() upshot is called when the bot is fix to start existence used. So, when the bot receives a message, the on_message() upshot is called.
  5. The on_message() event triggers each fourth dimension a message is received but we don't want it to practice annihilation if the message is from ourselves. Then if the Message.author is the same equally the Client.user the code just returns.
  6. Side by side, we check if the Message.content starts with '$howdy'. If and so, then the bot replies with 'Hello!' to the channel it was used in.
  7. At present that the bot is gear up up, the final line runs the bot with the login token. It gets the token from out .env file.

We have the code for the bot and so now nosotros but have to run information technology.

How to Run the Bot

Now click run button on the meridian to run your bot in repl.it.

If you are writing the bot locally, you can use these commands in the concluding to run the bot:

On Windows:

py -three main.py

On other systems:

python3 main.py

Now go to your Discord room and type "$how-do-you-do". Your bot should render "Hello!".

image-141

How to Amend the Bot

Now that we have a basic bot working, we'll meliorate information technology. It is called "Encourage Bot" for a reason.

This bot will reply with a message of encouragement whenever someone sends a message containing a sad or depressing word.

Anyone volition be able to add encouraging letters for the bot to employ and the user-submitted messages will be stored in the Repl.information technology database.

The bot will as well return a random inspirational quote from an API when someone types the message "$inspire" into the chat.

We'll start with adding the "$inspire" feature.

How to Add together Inspirational Quotes to the Bot

Nosotros will get inspirational quotes from an API called zenquotes.io. Nosotros need to import a couple more Python modules, add a get_quote() function, and update our bot code to call the function.

Hither is the updated code. After the code, I'll explain the new parts.

          import discord import os import requests import json  client = discord.Client()  def get_quote():   response = requests.get("https://zenquotes.io/api/random")   json_data = json.loads(response.text)   quote = json_data[0]['q'] + " -" + json_data[0]['a']   return(quote)  @customer.upshot async def on_ready():   print('Nosotros take logged in as {0.user}'.format(client))  @client.event async def on_message(message):   if bulletin.author == customer.user:     return    if message.content.startswith('$inspire'):     quote = get_quote()     await message.channel.ship(quote)  customer.run(bone.getenv('TOKEN'))        

We now have to import the requests module. This module allows our code to make an HTTP asking to become data from the API. The API returns JSON, so the json module makes it easier to piece of work with the data returned.

The get_quote() function is pretty straightforward. First, it uses the requests module to request data from the API URL. The API returns a random inspirational quote. This function could easily be rewritten to become quotes from a unlike API, if the current one stops working.

Side by side within the function, nosotros use json.loads() to convert the response from the API to JSON. Through trial and error I figured out how to get the quote from the JSON into the string format I wanted. The quote is returned from the function as a string.

The final part updated in the code is toward the end. Previously it looked for a bulletin that started with "$hi". Now it looks for "$inspire". Instead of returning "Hello!", information technology gets the quote with quote = get_quote() and returns the quote.

At this indicate yous tin can run your code and try information technology out.

How to Add Encouraging Letters to the Bot

Now we will implement the feature where the bot responds with encouraging messages when a user posts a message with a pitiful discussion.

How to Add Sorry Words to the Bot

First we need to create a Python list that contains the sad words that the bot volition answer to.

Add the following line subsequently the client variable is created:

sad_words = ["sad", "depressed", "unhappy", "aroused", "miserable"]

Feel costless to add more words to the list.

How to Add together Encouraging Messages to the Bot

At present we'll add together a listing of encouraging messages that the bot will respond with.

Add the following list after the sad_words list you created:

          starter_encouragements = [   "Cheer upward!",   "Hang in there.",   "Yous are a great person / bot!" ]        

Like earlier, feel gratis to add together more than phrases of your choice to the list. I'thou only using three items for now because later we'll add the ability for users to add more encouraging phrases for the bot to utilize.

How to Reply to Letters

Now nosotros need to update our bot to use the 2 lists nosotros created. First, import the random module considering the bot will choose encouraging messages randomly. Add the following line to the import statements at the height of the code: import random.

At present we volition update the on_message() function to check all messages to see if they contain a word from the sad_words list. If a lamentable word is constitute, the bot will ship a random message of encouragement.

Here is the updated code:

          async def on_message(message):   if bulletin.writer == client.user:     render    msg = bulletin.content    if msg.startswith('$inspire'):     quote = get_quote()     await bulletin.channel.transport(quote)        if whatsoever(discussion in msg for word in sad_words):     await bulletin.channel.send(random.choice(starter_encouragements))        

This is a good fourth dimension to test the bot. You know enough now to create your ain bot. But next you'll learn how to implement more advanced features and store information using the Repl.it database.

How to Enable User-submitted Messages

The bot is completely functional, but at present let'south brand it possible to update the bot correct from Discord. A user should be able to add more encouraging messages for the bot to use when information technology detects a sad word.

Nosotros are going to use Repl.it's built-in database to shop user-submitted messages. This database is a key-value store that's built into every repl.

At the peak of the lawmaking, under the other import statements, add from replit import db. This volition allow u.s.a. to utilise the Repl.information technology database.

Users volition exist able to add custom encouraging letters for the bot to use directly from the Discord chat. Earlier we add together new commands for the bot, let's create ii helper functions that will add together custom messages to the database and delete them.

Add together the following code after the get_quote() function:

          def update_encouragements(encouraging_message):   if "encouragements" in db.keys():     encouragements = db["encouragements"]     encouragements.append(encouraging_message)     db["encouragements"] = encouragements   else:     db["encouragements"] = [encouraging_message]  def delete_encouragment(index):   encouragements = db["encouragements"]   if len(encouragements) > alphabetize:     del encouragements[index]   db["encouragements"] = encouragements        

The update_encouragements() function accepts an encouraging message as an statement.

First information technology checks if "encouragements" is a key in the database. If then, it gets the list of encouragements already in the database, adds the new one to the list, and stores the updated listing back in the database nether the "encouragements" key.

If the database does non already incorporate "encouragements", a new key by that name is created and the new encouraging message is added as the offset chemical element in the list.

The delete_encouragement() office accepts an index as an statement.

It gets the list of encouragements from the database stored under the "encouragements" key. If the number of items in the encouragements list is greater than the index, then the list item at that index is deleted.

Finally, the updated listing is stored back in the database nether the "encouragements" key.

Here is the updated lawmaking for the on_message() office. Later on the lawmaking, I'll explicate the new sections.

          async def on_message(message):   if message.author == client.user:     return    msg = message.content     if msg.startswith("$inspire"):     quote = get_quote()     wait message.channel.ship(quote)    options = starter_encouragements   if "encouragements" in db.keys():     options = options + db["encouragements"]    if whatsoever(discussion in msg for give-and-take in sad_words):     await message.channel.send(random.choice(options))    if msg.startswith("$new"):     encouraging_message = msg.split("$new ",i)[1]     update_encouragements(encouraging_message)     await message.aqueduct.send("New encouraging message added.")    if msg.startswith("$del"):     encouragements = []     if "encouragements" in db.keys():       index = int(msg.split("$del",one)[1])       delete_encouragment(index)       encouragements = db["encouragements"]     await message.channel.send(encouragements)        

The starting time new line of code from above is options = starter_encouragements. We are making a re-create of starter_encouragements because we are going to add the user-submitted messages to that list before choosing a random message for the bot to send.

We bank check if "encouragements" is already in the database keys (meaning that a user has submitted at to the lowest degree ane custom bulletin). If so, we add the user messages to the starter encouragements.

Then, instead of sending a random message from starter_encouragements, the bot at present sends a random message from options.

The next new section of code is used to add together a new user-submitted bulletin to the database. If a Discord bulletin starts with "$new", and so the text later "$new" will be used as a new encouraging message.

The code msg.split("$new ",i)[1] splits off the message from the "$new" control and stores the message in a variable. In that line of code, take note of the space in "$new ". We desire everything later the space.

Nosotros telephone call the update_encouragements helper office with the new message, and and so the bot sends a message to the discord chat confirming that the message was added.

The tertiary new section (at the stop of the code above) checks if a new Discord message starts with "$del". This is the command to delete an item from the "encouragements" list in the database.

Showtime a new variable called encouragements is initialized equally an empty array. The reason for this is that this department of lawmaking will send a message with an empty array if the database does not include an "encouragement" key.

If the "encouragement" key is in the database, the alphabetize volition be split off from the Discord bulletin starting with "$del". Then, the delete_encouragement() function is chosen passing in the alphabetize to delete. The updated list of encouragements is loaded into the encouragements variable, and so the bot sends a bulletin to Discord with the current list.

Concluding Bot Features

The bot should work so this is a proficient time to test information technology. Nosotros volition at present add a few final features.

We will add together the ability to get a list of user-submitted messages correct from Discord and we volition add the ability to turn off and on whether the bot responds to sad words.

I will give you the full final code of the plan, and so I'll discuss the updates below the code.

          import discord import os import requests import json import random from replit import db  client = discord.Customer()  sad_words = ["sad", "depressed", "unhappy", "angry", "miserable"]  starter_encouragements = [   "Cheer up!",   "Hang in in that location.",   "Y'all are a great person / bot!" ]  if "responding" not in db.keys():   db["responding"] = Truthful  def get_quote():   response = requests.get("https://zenquotes.io/api/random")   json_data = json.loads(response.text)   quote = json_data[0]["q"] + " -" + json_data[0]["a"]   return(quote)  def update_encouragements(encouraging_message):   if "encouragements" in db.keys():     encouragements = db["encouragements"]     encouragements.suspend(encouraging_message)     db["encouragements"] = encouragements   else:     db["encouragements"] = [encouraging_message]  def delete_encouragment(index):   encouragements = db["encouragements"]   if len(encouragements) > alphabetize:     del encouragements[index]   db["encouragements"] = encouragements  @client.issue async def on_ready():   impress("We have logged in as {0.user}".format(client))  @customer.event async def on_message(bulletin):   if message.writer == client.user:     return    msg = bulletin.content    if msg.startswith("$inspire"):     quote = get_quote()     await message.channel.send(quote)    if db["responding"]:     options = starter_encouragements     if "encouragements" in db.keys():       options = options + db["encouragements"]      if whatsoever(give-and-take in msg for word in sad_words):       await message.channel.send(random.choice(options))    if msg.startswith("$new"):     encouraging_message = msg.split("$new ",1)[1]     update_encouragements(encouraging_message)     await bulletin.channel.send("New encouraging message added.")    if msg.startswith("$del"):     encouragements = []     if "encouragements" in db.keys():       index = int(msg.carve up("$del",1)[1])       delete_encouragment(index)       encouragements = db["encouragements"]     await message.aqueduct.send(encouragements)    if msg.startswith("$listing"):     encouragements = []     if "encouragements" in db.keys():       encouragements = db["encouragements"]     await message.channel.send(encouragements)        if msg.startswith("$responding"):     value = msg.split("$responding ",1)[i]      if value.lower() == "true":       db["responding"] = True       look message.aqueduct.transport("Responding is on.")     else:       db["responding"] = Imitation       await message.channel.transport("Responding is off.")  client.run(bone.getenv("TOKEN"))        

The showtime department added to the code is right under the starter_encouragements list:

          if "responding" not in db.keys():   db["responding"] = Truthful        

We create a new cardinal in the database called "responding" and set it to "True". Nosotros'll use this to make up one's mind if the bot should respond to sad words or not. Since the database is saved even subsequently the program stops running, nosotros only create the new central if it doesn't already be.

The next new role of the code is that the section that responds to distressing words is now within this if statement: if db["responding"]:. The bot will only respond to sad words if db["responding"] = Truthful. The ability to update this value comes after this adjacent section.

Side by side, later the code to make the bot respond to the "$del" command, there is new lawmaking to respond to the "$list" command when sent as a Discord message.

This section starts with creating an empty list called encouragements. Then, if there are already encouragements in the database, those encouragements replace the empty list that was just created.

Finally, the bot sends the list of encouragements as a Discord message.

The terminal new section comes adjacent. This code makes the bot respond to the "$responding" control. This command takes an argument of either "true" or "imitation". Hither is a usage example: "$responding true".

The code first pulls off the argument with value = msg.split("$responding ",one)[1] (like before, note the infinite in "$responding "). And then there is an if/else statement that accordingly sets the "responding" key in the database and sends a notification message dorsum to Discord. If the argument is anything simply "true", the code assumes "false".

The code for the bot is consummate! Yous can now run the bot and try it out. Just there is one more important pace that we volition discuss next.

How to Set Up the Bot to Run Continuously

If you lot run your bot in repl.it and then close the tab it is running in, your bot volition stop running.

But there are two means you can keep your bot running continuously, even after you shut your web bowser.

The first mode and simplest way is to sign up for paid plan in Repl.information technology. Their cheapest paid plan is called the Hacker Plan and it includes five always-on repls.

You tin get three months free using this link (limited to first chiliad people):  https://repl.it/claim?code=tryalwayson2103

Once you accept signed upward for that plan, open your Repl and click the name at the top. And so select the "E'er On" option.

image-35-1

There is some other manner to keep your lawmaking running fifty-fifty on the complimentary tier simply it is a picayune more complicated. Repl.it will keep running a web server even later on the tab is airtight. Merely fifty-fifty a web server will only run for upwardly to an hour without whatever use.

Here is what the repl.it docs say:

One time deployed, the server volition continue to run in the groundwork, fifty-fifty after you close the browser tab. The server will stay awake and agile until an hour after its last request, later on which it will enter a sleeping stage. Sleeping repls will be woken up as soon every bit it receives another request; at that place is no demand to re-run the repl. However, if you make changes to your server, you will need to restart the repl in order to see those changes reflected in the live version.

To continue the bot running continuously, we'll employ another complimentary service called Uptime Robot at https://uptimerobot.com/.

Uptime Robot tin exist prepare to ping the bot's web server on repl.it every 5 minutes. With abiding pings, the bot will never enter the sleeping stage and will just continue running.

So nosotros accept to practice 2 more than things to get our bot to run continuously:

  1. create a web server in repl.information technology and
  2. fix up Uptime Robot to continuously ping the web server.

How to Create a Web Server in repl.it

Creating a web server is simpler than you may think.

To exercise it, create a new file in your project called keep_alive.py.

And so add the following code:

          from flask import Flask from threading import Thread  app = Flask('')  @app.route('/') def domicile():     render "Hello. I am alive!"  def run():   app.run(host='0.0.0.0',port=8080)  def keep_alive():     t = Thread(target=run)     t.start()                  

In this code, we employ Flask to showtime a spider web server. The server returns "Hello. I am live." to anyone who visits it. The server volition run on a separate thread from our bot. We won't talk over everything here since the residuum is not really relevant to our bot.

Now nosotros just need the bot to run this spider web server.

Add together the following line toward the peak of master.py to import the server.

          from keep_alive import keep_alive        

To start the spider web server when main.py is run, add the following line as the second-to-concluding line, correct before the bot runs.

keep_alive()

When you run the bot on repl.it later adding this code, a new web server window will open up. There is a URL shown for the spider web server. Copy the URL and then you can utilize it in the side by side section.

image-20-1

How to Set Up Uptime Robot

Now we demand to prepare up Uptime Robot to ping the spider web server every five minutes. This will cause the bot to run continuously.

Create a costless business relationship on https://uptimerobot.com/.

Once you are logged in to your business relationship, click "Add New Monitor".

image-21-1

For the new monitor, select "HTTP(due south)" every bit the Monitor Type and name it whatever you like. Then, paste in the URL of your web server from repl.information technology. Finally, click "Create Monitor".

image-22-1

We're done! At present the bot will run continuously and then people tin can always interact with information technology on Repl.it.

Decision

You at present know how to create a Discord bot with Python, and run it continuously in the cloud.

In that location are a lot of other things that the discord.py library tin can practice. So if you want to requite a Discord bot fifty-fifty more than features, your next stride is to bank check out the docs for discord.py.

Acquire to lawmaking for free. freeCodeCamp'south open source curriculum has helped more than xl,000 people go jobs as developers. Get started

hathawayagaingly.blogspot.com

Source: https://www.freecodecamp.org/news/create-a-discord-bot-with-python/

0 Response to "Make Your Discord Bot Read and Send Messages in Discord.py"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel