Getting started - sdallaboratory/advanced-telegram-bot GitHub Wiki
Importing
To use the library firstly you need to import it:
from advancedbot import TelegramBot
Bot class initializing
You need to pass into bot class as parameters the following:
- your telegram bot token;
- roles that will exist in the application;
- states that will exist in the application;
- other parameters that you can use (read the docs for more);
- storage parameters.
Ways of storing your data
MongoDB
To use MongoDB as a storage you have to provide its data for authorization to the class in parameters:
db_address
(database IP address);db_port
(database port);db_username
(database username);db_password
(database user's password);db_name
(database name).
Local Storage (JSONs)
To use local storage based on JSONs you have to provide the folder path in parameter:
storage_folder
.
So final initialization would look like this:
bot = TelegramBot(bot_token='your_token',
roles={ 'admin': { 'password': '12345' } },
states=['telling name'],
db_address='0.0.0.0',
db_port=21217,
db_username='your_name',
db_password='pass',
db_name='bot_db')
Creating some actions
Let's create two functions that will start a dialog. We can start with answering on /start
command.
To connect our function to command we will use route
decorator. Pay attention that function must have **kwargs
in its parameters.
@bot.route(commands=['start'])
def ask_name(self, **kwargs):
bot.sender.send_text(user_id=kwargs['user_id'],
text='Tell me your name, please :D')
bot.state_manager.set_state(kwargs['user_id'], 'telling_name')
We also set state to user so we can understand in the future that we asked him to do something (in our case - tell his name).
Now, let's create a reply for him sending his name. For that we will also use the route
decorator.
@bot.route(states=['telling_name'])
def say_hello(self, **kwargs):
bot.sender.send_text(user_id=kwargs['user_id'],
text=f'Hello, {kwargs['message']}! I'm advanced telegram bot!')
bot.state_manager.set_free(kwargs['user_id'])
We need to set his state to free
so we know that he did what we asked.
Congratulations! Your first advanced telegram bot has been created!