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
- First we have to import Tourmaline into our code. In Crystal this is done with the
- Next we extend
Tourmaline::Clientand use it to create our own class.
- In this example we're going to go with the annotation approach to creating bots. Annotations use the
@[Annotation(params)]syntax and can decorate classes and methods. In this case, we're annotating the
echo_commandmethod with the
Commandannotation, which turns the method into a command handler.
- Within the
echo_commandmethod we're just going to echo whatever the user said back to them, so we use the
replymethod which exists on the
Messageobject and send
ctx.text(the user's message text minus the command) back to them.
- Almost done. Now we need to create a new instance of our
EchoBot. Since we extended
Tourmaline::Clientand didn't provide a custom initializer our bot takes the same arguments, so we can provide it with our API Key as an environment variable.
- The last step is to start our bot. We can do that by "long polling" using the
And that's really all their is to it. Now we can run our code!
export API_KEY=YOUR_BOT_API_TOKEN crystal run ./src/echo_bot.cr
You should be greeted with a log message in your console telling you that your bot is running, and if you visit your bot on Telegram and run the
/echo command with some text (eg
/echo hello world), you should receive a message in reply.