Building a Discord Bot for ChatOps, Pentesting or Server Automation (Part 2)
In this step by step tutorial we will create fully functional bot from scratch in which you can execute any command or cli program you like on your server or integrate with any API that you have access for example Jira. This is the part #2 of the series.
You can access the explanation of the discord setup in the Part #1 of this series here:
Prerequisites
- A discord client: web, desktop app or mobile app
- A discord server. You can create one inside your discord client of choice
- A discord bot configured and added to the server
- The Bot Token
- A code editor of your choice. If you don’t have one use Visual Studio Code
- Some programming knowledge
- Python 3 and the module pip installed in your machine
Part #2: Playing with our bot
We will need some python libraries, let’s install it
Open your terminal and type
For security reasons we will save our secrets in the .env file and include in the file .gitignore so if we push our code to github/gitlab, our credentials don’t persist in the cloud and available to anyone.
Trending Chatbot Articles:
1. Publishing your Chatbot on Microsoft Teams
2. 🤖 How to talk to Computers: A Framework for building Conversational Agents — Part 1
Create a file called “.env” without double quotes, en inside we will call our constant DISCORD_TOKEN and assign the value of our Bot Token that we saved in the Part #1
For example
Connection to the server
The first thing that we will do is start our bot and print a message in console when its connected to the server and its ready. Create a file called bot_test_1.py and write this code
Let’s run it
If we look our discord client app we will see the bot connected
A more object oriented way to do the same will be
Let’s run it
List guild members
For discord a guild is the same as a server.
Add to the file “.env” the constant DISCORD_GUILD with the value of the name of your server
Create a new file called bot_test_3.py
Let’s run it
Or we can do it this way with utils.find function and a lambda
Or with the utils.get function
Greet on member join
Create a new file called bot_test_4.py
Let’s run it
When you share a link to your server and a person logs in, they will see a private message sended by our bot greeting them.
Talking with the bot
Create a new file called bot_test_5.py
Let’s run it
If you direct message the bot and write “echo” you will get the response
We are all set for this step. In the Part #3 we will create custom commands for accessing command line tools installed in the bot machine.
Note:
If you encounter typos or something doesn’t work no more write me a comment and I will keep this guide updated. Last update June 11 2020.