DEV Community

loading...
Cover image for Build a Chuck Norris Discord Bot in Python [Discord.Py] for beginners

Build a Chuck Norris Discord Bot in Python [Discord.Py] for beginners

bekbrace profile image Bek Brace ・5 min read

This is a quick guide on how to create a Chuck Norris jokes Discord bot, using the Chuck Norris jokes API in Python, using discord.py package.

Alt Text

I have a video on the matter, if you want to check it out

https://www.youtube.com/watch?v=-bsfhUn62YM&t=17s

Here, I demonstrate how to create a Discord bot in JavaScript, and Python but I also explain everything I know about coroutines, callbacks, async/await syntax and event loops in the Discord context of course.
I also have touched briefly on the Asyncio library in Python; some great late addition to Python.

Ok, back to business; so how can you create this awesome discord bot ?

The prerequisites are :
Python 3.5 +
A Discord account
A Discord server

Then you will need to create a Bot, to do that is very straightforward:
1- Got to developers portal : https://discord.com/developers/applications

2- Then click on New Application on the right top corner of the page
Alt Text

3- Give it a name (ex: DEVBot)
Alt Text

4- Add A Bot !
So you want to got to Bot and add a bot, then click on Yes Do It!

Alt Text

5- The Bot is created !
Now, be careful, you don't want to share the token with anyone.
We will copy it later for the code; and now we need to go to OAuth2

Alt Text

6- Here you want to go to OAUTH2, in order to give your bot permissions to do what you want
Alt Text

7- As my bot is going to respond to the user by telling him/her a joke, we want to give permissions to send message, and also notice above I have specified that it is a bot

Alt Text

Then copy that link, open a new tab paste it then hit return (enter), and authorize the bot to join your server and you're good to go!

Alt Text

Alt Text

You will find your bot offline on the right side of the screen below your name, it will only go online when we will type our Python code.

Alt Text

So, go ahead and install discord.py via :

pip install -U discord.py

'''An event is something you listen to and then respond to.
For example, when a message happens, you will receive an event about it that you can respond to.
Discord.py is an asynchronous library, supports Async/Await syntax which handles callbacks.
Callbacks are functions which are called when something else happens in programming in general, there are 2 types of threading, single threading and multi-threading:
Java and C# are multithreading, which means they can perform multiple tasks without blocking or without running slow
JavaScript and Python are single threaded languages, which means they can only run one task at a time.
JavaScript and Python rely on “asynchronous programming” using callbacks and a single event queue, what that simply means is that Python (and also JS) can only do one thing at a time, and maybe you have heard of the stack or stack queue, and different tasks can be accumulated in the queue waiting for a response for a each task, [ and we're talking about IO tasks such reading in the file system, sending HTTP requests to a website, reading in the database ] so when a task is done and response is received, this task is removed from the stack and goes to the next task and so on, and this can result in a slow performance which naturally results in blocking, and blocking simply means slow code, and the code is slow not because of the processor but because you're doing a lot of IO.
And the solution for that is using coroutines or “asynchronous programming” or concurrent code, and a coroutine is just a function that is preceded by async keyword, and async will stop the coroutine from being executed until we wait for other requests in the coroutine to receive some sort of approval of the operating system
'''
Here is the full code :

import discord
import requests
import json

class myClient(discord.Client):
    # function to login so we're going to use onready event here, remember when we said that discord.py revolves around the concept of events.
    async def on_ready(self):
        print(f' Howdy 👋 ! logged in as {client.user}'.format(client))

    # function to answer message
    async def on_message(self, ctx):
        if ctx.author == client.user:
            return
        elif ctx.content.startswith('hello'):
            await ctx.channel.send('Howdy, friend 👋 ')
        elif ctx.content.startswith('make me laugh'):
            await ctx.channel.send('Hello! Would you like to hear a Chuck Norris joke 😛 ?')
            # wait_for takes an event and a check argument that is a lambda function that takes the arguments of the event - in this case message - you're waiting for and determines whether or not the new message comes from the same person who invoked the currently running command.
            # For example, the on_message event takes a ctx argument, so if we wanted to check the author of a message we could do:
            res = await client.wait_for('message', check=lambda message: ctx.author == message.author)
            if res.content.lower() == ('yes'):
                # creation and invoking the joke function here
                # and Python code is going to block the coroutine until tasks requested are fulfilled and returned with a response; then it will unblock and goes to the next task, and so on.
                async def get_joke(self):
                    response = requests.get(
                        'https://api.chucknorris.io/jokes/random')

                    joke = json.loads(response.text)
                    # print(joke['value'])
                    return(joke['value'])
                the_joke = await get_joke(self)
                await ctx.channel.send(the_joke)
            else:
                await ctx.channel.send('no problem!')

        elif ctx.content.startswith('thanks'):
            await ctx.channel.send('You are welcome!')
        elif ctx.content.startswith('salut'):
            await ctx.channel.send('salut mon ami :D')
# Creating a client
# using myClient class which represents a client connection that connects to Discord API.
# This class is used to interact with the Discord WebSocket and API.
client = myClient()
# Run the token for connection
client.run("YOUR TOKEN")
Enter fullscreen mode Exit fullscreen mode

Let me know if you like it, or if you have any comments feel free to share them with me.
Also, if you've ever created a Discord bot, what was it doing and how long did it take you to build it - Cheers

Discussion (2)

pic
Editor guide
Collapse
rmaurodev profile image
Ricardo

Very nice. Thanks for sharing.

Collapse
bekbrace profile image
Bek Brace Author

My pleasure, Ricardo