Getting Started with Tourmaline#
Time to create your first bot with Tourmaline!
This guide assumes that you have Crystal installed and are at least semi-familiar with the syntax. The first thing we are going to need is a fresh Crystal project, so go ahead and run
crystal init app your_bot_name, making sure to replace "your_bot_name" with whatever you want to call your bot. I'm going to use the famous echo_bot example. Once it's finished,
cd into the project directory.
shard.yml and add the following lines anywhere in the file (probably at the end):
1 2 3
Save the file, and run
shards install. That's it! Tourmaline is now installed.
Creating Your Bot#
Now it's time to write some code. Open
src/echo_bot.cr or whatever file was generated for you, and paste in the following code. The code is annotated so you can understand what's going on every step of the way.
1 2 3 4 5 6 7 8 9 10 11 12
- First we have to import Tourmaline into our code. In Crystal this is done with the
- Next we create a new
Clientobject. This is the main object that we will be using to interact with the Telegram Bot API. Into the
Clientwe pass our bot's API token, which we will be getting from the BotFather. We will be storing this in an environment variable, so we use
ENV["BOT_TOKEN"]to get the value of the
BOT_TOKENenvironment variable. If you are not familiar with environment variables, you can read more about them here.
- Tourmaline uses a system of handlers to handle different types of events. In this case we are creating a
CommandHandlerwhich will handle the
/echocommand. The first argument to the
CommandHandleris the name of the command, and the second argument is a block of code that will be executed when the command is received. The block of code is passed a
Contextobject, which contains information about the command and the message that triggered it.
Contextobject has a
textproperty which contains the text of the message that triggered the command. We can use this to get the text of the message and reply with it. We use the
replymethod to send a message back to the chat that the command was sent in. We also check to make sure that the message isn't empty, because if the user just sends
/echowithout any text, the message will be empty.
- Now that we have created our handler, we need to register it with the
Clientso that it can be used. This is done with the
- Finally, we call the
pollmethod on the
Clientto start the bot. This method will block the current thread, so it is important that you call it at the end of your code.
And that's really all their is to it. Now we can run our code!
export LOG_LEVEL=info # by default you won't see any logs, so we set the log level to info
crystal run ./src/echo_bot.cr
If all goes well, you should see something like this:
2023-03-23T00:17:53.778090Z INFO - tourmaline.poller: Polling for updates...