π² Your First Command: the dice roller¶
This tutorial starts where getting started left off. Youβll build a simple D&D-style dice roller for your Telegram bot using django-telegram-app.
By the end, your bot will:
- respond to
/roll - let the user choose a die (
d4,d6,d8,d10,d12,d20) - display the result
- offer a βRoll againβ and "Choose another die" button
This assumes you already:
- have a Django project
- configured
django_telegram_app(installed app,TELEGRAMsettings, webhook set) - can send
/startor some basic command to the bot successfully
1. Create a new Django app for dice¶
From your project root:
Add it to INSTALLED_APPS in settings.py:
Weβll keep everything for this tutorial inside the dice app.
2. Create the telegrambot command structure¶
Inside the dice app, create the following directories:
Your file tree should now look like:
Commands are discovered from dice/telegrambot/commands/, so we just need to add a roll.py module there.
3. Implement the /roll command¶
Create dice/telegrambot/commands/roll.py:
At this point, you have a working command:
/rollβ shows a list of dice- tapping a die β rolls that die and shows the result
Roll againβ rolls the same die againChoose another dieβ goes back to the die selection
4. Understanding the /roll command¶
The Command class¶
- Commands subclasses
BaseBotCommandand represents a single bot command, here/roll. - The command name is inferred from the module name (
roll.pyβ/roll). descriptionis used in help contexts, so itβs good to keep it short and clear.steps(property) is a list ofStepsubclasses, they define the flow of the command.- The command always starts with the first step in the list.
translateis True by default and is used to activate the user's language. Steps can override this behaviour (see below)
The steps¶
- Steps are subclasses of
Stepand represent a single step in the command. translateis None by default, which means the command'stranslateflag is used. If the step'stranslateflag is True or False, this value will be used instead.- The
__call__method of step is used as an entrypoint to start a step. It essentially activates translation and calls thehandlemethod. - Steps can:
- request callback data based on the telegram_update's callback token,
- create new callback data with data for the current step,
- create a keyboard with buttons that contain this new callback data,
- send feedback to the user using
bot.send_message. - The new callback data can make the bot:
- call the next step
- call the previous step
- call the current step again
- cancel the command
- finish the command
Note
For more info on how callbacks work, see the CallbackData topic
Next steps¶
Continue to: