Hello everyone. Welcome back to the Blog of Chamodh today I will show you how to send and receive discord messages with your bot. Before getting started, I remind you that this is the second episode of the series How to make Discord bot in 2023 and if you haven't read the previous one, please read that first as I explain how to create your bot application and add it to a server there.
READ: https://blogofchamodh.blogspot.com/2023/02/how-to-make-your-own-discord-bot-2023.html
We don't gonna use virtual environments, IDEs, or any other utility because we can use Replit for our coding purposes.
Let's Get Started.
STEP1: Set up Replit
It is really simple. Just go to https://replit.com/~ and sign up if you have never used its service before and create a new Repl. I don't hope to guide you in this as this is an intermediate tutorial.
Make sure to select Python as you create the new Repl because we are going to use Python for our back end.
STEP 2: Get your token.
To run our bot we have to use a token. You can find your token here: https://discord.com/developers/applications/ and select the application
Then select the Bot Menu from the left sidebar and then you can see your token. If you cannot see it you will be able to see a Reset Token Button, after clicking it, you will be able to see your token.
Then copy the token. To hide my token I am going to create a new file called credintials.py and create a string variable called token so that I can import it later.
STEP 3: Install Dependencies.
To run our discord bot, we want some packages. We only need discord.py to get started and we may need some other packages to add extra functionalities to our bot.
To install discord.py run this command in the Repl's Shell.
~/GlisteningMemorableLanguage$ pip install discord.py
STEP 4: Let's Code
To handle the events we use the following code chunk. As I mentioned before I don't expect to explain the code line by line as this is not a beginner-level tutorial. If you find something difficult to understand, please let me know in the comment section.
To receive and send messages when a user sends a message to the server, we use the on_message function.
You can simply add the method to the MyClient as follows.
When we set up our on_meesage method, we have to check whether the message is sent by a user other than our bot. Unless it becomes an infinite loop of messages. To do this we can either check for the message's author or tell our bot to respond to messages which start with a specific character like $ or!
If we choose the first option, the on_message method will be the above code which checks if the message's author is not the bot. If so, it will send a reply
function
which returns true if a string starts with a
specific character. The following code will give you a better idea.
When you use the second method don't forget not to send a message
starting with the character you defined from the bot, as it will result in
an infinite loop.
Comments
Post a Comment