Skip to content

Writing Your First Bot

Lort533 edited this page May 29, 2023 · 15 revisions

This tutorial will walk you through the steps required to get a simple bot up and running. If you have not already created a bot account, you must do this: see Setting up a Discord application. If you have not already installed Discordia, you must do this: see Installing Discordia.

Step 1: Learn Lua

This tutorial assumes that you already know how to use the Lua programming language. If you do not, you will need to learn the basics before you write a Discord bot. Here are some resources that you can use to learn more about Lua, LuaJIT, and Luvit:

Step 2: Find a good text editor

Any text editor will work, but simple ones like Notepad on Windows may not be sufficient. A popular alternative to Notepad is Notepad++. You might also want to consider VSCode, or Sublime. There is also Emacs, Vim, and a ton of others. Pick your favorite and install it.

Step 3: Create a Lua File

All Lua files have the extension .lua. In the same directory where you installed Luvit earlier, make a new file with the name bot.lua and open it with the text editor you installed above. The name can be anything, but we'll use "bot" for simplicity.

Step 4: Start Creating Your first Code

These are your dependencies; do not delete these. They initialize Discordia and allow you to interact with it.

local discordia = require('discordia')
local client = discordia.Client()

This code prints a success message and your bot's name to the console once your bot token has been authenticated and a connection to the Discord gateway has been established.

client:on('ready', function()
	-- client.user is the path for your bot
	print('Logged in as '.. client.user.username)
end)

This is the method that will create your first command. It listens for a message event, and checks if the content of the message is "!ping". If so, it then sends "Pong!" to the channel from which the invoking message originated.

client:on('messageCreate', function(message)
	if message.content == '!ping' then
		message.channel:send('Pong!')
	end
end)

This is what Authenticates your bot with the Discord Gateway and Discordia; replace TOKEN with your bot's token. Note that all tokens MUST be prefixed with "Bot "! (including the space)

client:run('Bot TOKEN')

Step 5: Starting up your bot

After doing this go into your folder/area with your bot.lua file and type
luvit bot.lua

If all goes to plan, your bot should start and connect to the Discord gateway.


Prev: Installing Discordia | Next: Writing a Ban Command

Clone this wiki locally