Getting Started with Tourmaline#
Time to create your first bot with Tourmaline!
Installing 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.
Now, open 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
require
statement. - Next we create a new
Client
object. This is the main object that we will be using to interact with the Telegram Bot API. Into theClient
we 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 useENV["BOT_TOKEN"]
to get the value of theBOT_TOKEN
environment 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
CommandHandler
which will handle the/echo
command. The first argument to theCommandHandler
is 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 aContext
object, which contains information about the command and the message that triggered it. - The
Context
object has atext
property 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 thereply
method 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/echo
without any text, the message will be empty. - Now that we have created our handler, we need to register it with the
Client
so that it can be used. This is done with theregister
method. - Finally, we call the
poll
method on theClient
to 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
export BOT_TOKEN=YOUR_BOT_API_TOKEN
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...