This repository provides a python library to make it easy to create telegram bots using the python telegram API.
The basic idea is that you can define a function similar to the way you would with the click framework and then automatically convert that into a form suitable for telegram.
Ideally, creating commands in a telegram bot should but just as easy as writing a python function.
The following describes how to get started as quickly as possible.
Do the usual pip install tbotg.
First, use the botfather to create a bot:
- Go to
BotFatherin a Telegram chat. - Type
/newbotto request a new bot. - Type the desired name when
BotFatherasks you for it. - Save the token
BotFathergives you in~/.ox_secrets.csvas
name,category,values,notes token,YOUR_BOT_NAME,YOUR_TOKEN
- The
~/.ox_secrets.csvfile is a simple CSV file used to manage secret information such as your telegram bot token.
Next, create a python file for your bot. For example, you could create
a python file named mybot.py as shown below:
"Example to show how to use tbotg"
import click
from tbotg.core.main_bot import TelegramMainBot
from tbotg.core.bcmds import ClickCmd
@click.command()
@click.option('--say', '/say', help='What to say')
@click.option('--count', '/count', type=int, help='How many times to repeat.')
def repeatntimes(say, count):
"Repeat something N times."
return 'I will repeat it %i times: %s' % (
count, ', '.join([say.upper()] * count))
class MyBot(TelegramMainBot):
"""Example bot.
"""
@classmethod
def make_cmds(cls):
"Make commands for bot."
return [ClickCmd(repeatntimes)]Run the serve using the tcli script provided by tbotg via the
following command line:
tcli serve --bot_cls MyBot --module 'mybot' --with_name ${YOUR_BOT_NAME}where ${YOUR_BOT_NAME} is the name of the bot you created with BotFather
Note that you will need your PYTHONPATH set properly for python to
find your mybot.py module. For example, you could do something like
export PYTHONPATH=${PYTHONPATH}:`dirname /path/to/mybot.py`
To test your command,
- Start a chat with your bot on telegram.
- Do
/helpto see available commands. - Do
/repeatntimesto run your command - Click on the parameter buttons to set the values of
sayandcount. - Click the
confirmbutton to run the command.
Note that you can also include command line arguments when calling a command in Telegram via something like:
/repeatntimes /say hi
and that option will be automatically filled in. Note that it is best
to use a leading slash (/) for these kinds of options and not the usual
double hyphen (--) since some versions of Telegram auto-replace
double hyphens with a “long dash”.