Serverless discord bot with aws

Discord bots are great whether it's for moderation(with Dyno, Carl Bot) or utility (music player with Fredboat or ticketing system with Tickets). However, back in the day, if you wanted to create a discord bot, you'd have to provision your own server or use a no-code hosting service with something like BotGhost, they are great and all but they can be costly or limited in functionality.

Interactions Endpoint and slash command

With the introduction of Discord slash command and interaction in 2021, bots developers can now configure a custom endpoint so that we can receive interactions from Discord without having a server that's listening 24/7.

Serverless discord bot

By only using aws API gateway, lambda function we can create a very simple serverless discord bot.

Here's a quick demonstration of it

The way it works is that we set up an API gateway that allows Discord to send interactions to and the api gateway will redirect the request to a lambda function. Then the lambda function will read the request, do something with the request and return something back to Discord.

Here are some sample code (not completed code):

import random
def lambda_handler(event, context):
    body = event.get('body-json')
    data = body.get('data')

    if data.get('name') == 'rand':
        rand_dict = {"num1" : None, "num2" : None}

        # get the options from the request
        for option in data.get('options'):
            # add the options to the dict
            rand_dict[option.get("name")] = option.get("value")
        # generate the random number
        rand = random.randint(rand_dict["num1"],rand_dict["num2"] )

        message = {
            "type": 4,
            "data": {
                "tts": False,
                "content": f"The random number between {rand_dict['num1']} and {rand_dict['num2']} is {rand}",
                "embeds": [],
                "allowed_mentions": []
        print(f"[INFO]: {message}")

        return message

Although this is a very simple demonstration, it does show the potential of creating a fully functional Discord bot without a server whatsoever. On my next article I’ll explore adding persistence storage to my Discord bot