DEV Community

LordOfPolls
LordOfPolls

Posted on

Making a NAFF Discord Bot

Preamble

So you fancy making your own bot for Discord? Got a fun idea for your community? Well let's get you started.

For this tutorial I'll be using the python library NAFF.

I'm going to skip past creating a Discord bot on the Developer Portal. If you're unsure check out this guide.

Environment

As with any python project, I strongly recommend that you make use of Virtual Environments when working on any project. This means that each project will not affect anything else on your system. Don't worry, this isn't setting up a full-fledged virtual machine, just small python environment.

cd "[your bots directory]"
python3 -m venv venv-name

# Linux
source venv/bin/activate
# Windows
venv/Scripts/activate
Enter fullscreen mode Exit fullscreen mode

It's that simple, now you're using a virtual environment. When you're donme, just type deactivate. If you want to learn more about virtual environments, check out this page

Installation

Installing python libraries is really easy! Just type this command and you're good to go

python3 -m pip install naff
Enter fullscreen mode Exit fullscreen mode

Basic Bot

Let's make something really simple first, we just want to connect to Discord, and say we've logged in.

import naff

bot = naff.Client()


@naff.listen()
async def on_ready():
    print(f"Logged in as {bot.user.username}")

bot.start("your_bot_token_here")
Enter fullscreen mode Exit fullscreen mode

Now just run your code, and you should see it login!

Commands

Its pretty boring to only see a logged in message, it would be nice to actually have commands; so lets do that now.

For this, we're going to add a ping slash command to the code we just wrote.

import naff

bot = naff.Client()


@naff.listen()
async def on_ready():
    print(f"Logged in as {bot.user.username}")

@naff.slash_command("ping", description="A ping command", scopes=[some_guild_id])
async def ping(ctx: naff.InteractionContext):
    await ctx.send("Pong")

bot.start("your_bot_token_here")
Enter fullscreen mode Exit fullscreen mode

Lets break down that decorator. @naff.slash_command tells NAFF the coroutine is a command. From there you have these parameters

Name - The first parameter, this is the name of the command, here it is "ping"
Description - When a user views commands, this is the help text they'll see
Scopes - These are the guilds this command will be available in, by default they are available everywhere. For testing its recommended to use a testing guild as it will update faster, and keep your mistakes secret 😉

There are some more parameters you can play with, but those can be left for a future guide

And there you have it, now you have a NAFF powered discord bot with slash commands. just start the bot and type /ping in your guild!

Top comments (0)