pyTelegramBotAPI/README.md

410 lines
16 KiB
Markdown
Raw Normal View History

2015-08-23 21:01:09 +03:00
# <p align="center">pyTelegramBotAPI
2015-08-23 20:32:23 +03:00
2015-08-23 21:01:09 +03:00
<p align="center">A simple, but extensible Python implementation for the [Telegram Bot API](https://core.telegram.org/bots/api).
2015-08-23 20:32:23 +03:00
2015-08-23 21:01:09 +03:00
<p align="center">[![Build Status](https://travis-ci.org/eternnoir/pyTelegramBotAPI.svg?branch=master)](https://travis-ci.org/eternnoir/pyTelegramBotAPI)
2015-08-23 20:32:23 +03:00
* [Getting started.](#getting-started)
* [Writing your first bot](#writing-your-first-bot)
* [Prerequisites](#prerequisites)
* [A simple echo bot](#a-simple-echo-bot)
* [General API Documentation](#general-api-documentation)
* [Types](#types)
* [Methods](#methods)
* [General use of the API](#general-use-of-the-api)
* [Message handlers](#message-handlers)
* [TeleBot](#telebot)
* [Reply markup](#reply-markup)
* [Advanced use of the API](#advanced-use-of-the-api)
* [Asynchronous delivery of messages](#asynchronous-delivery-of-messages)
* [Sending large text messages](#sending-large-text-messages)
* [Controlling the amount of Threads used by TeleBot](#controlling-the-amount-of-threads-used-by-telebot)
* [The listener mechanism](#the-listener-mechanism)
* [Using web hooks](#using-web-hooks)
* [Logging](#logging)
2015-08-23 21:01:09 +03:00
* [F.A.Q.](#faq)
* [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat)
2015-08-23 20:32:23 +03:00
* [The Telegram Chat Group](#the-telegram-chat-group)
* [More examples](#more-examples)
## Getting started.
This API is tested with Python 2.6, Python 2.7, Python 3.4, Pypy and Pypy 3.
There are two ways to install the library:
2015-08-23 21:01:09 +03:00
* Installation using pip (a Python package manager)*:
2015-06-28 17:34:27 +03:00
2015-08-23 20:32:23 +03:00
```
$ pip install pyTelegramBotAPI
```
* Installation from source (requires git):
2015-06-26 17:52:09 +03:00
```
$ git clone https://github.com/eternnoir/pyTelegramBotAPI.git
$ cd pyTelegramBotAPI
$ python setup.py install
```
2015-08-23 20:32:23 +03:00
It is generally recommended to use the first option.
2015-06-26 17:52:09 +03:00
2015-08-23 21:01:09 +03:00
**While the API is production-ready, it is still under development and it has regular updates, do not forget to update it regularly by calling `pip install pytelegrambotapi --upgrade`*
2015-08-23 20:32:23 +03:00
## Writing your first bot
2015-06-26 17:52:09 +03:00
2015-08-23 20:32:23 +03:00
### Prerequisites
2015-06-26 09:58:20 +03:00
2015-08-23 20:32:23 +03:00
It is presumed that you [have obtained an API token with @BotFather](https://core.telegram.org/bots#botfather). We will call this token `TOKEN`.
Furthermore, you have basic knowledge of the Python programming language and more importantly [the Telegram Bot API](https://core.telegram.org/bots/api).
2015-06-26 13:05:23 +03:00
2015-08-23 20:32:23 +03:00
### A simple echo bot
The TeleBot class (defined in \__init__.py) encapsulates all API calls in a single class. It provides functions such as `send_xyz` (`send_message`, `send_document` etc.) and several ways to listen for incoming messages.
Create a file called `echo_bot.py`.
Then, open the file and create an instance of the TeleBot class.
2015-06-26 09:58:20 +03:00
```python
import telebot
2015-08-23 23:06:11 +03:00
bot = telebot.TeleBot("TOKEN")
2015-08-23 20:32:23 +03:00
```
2015-08-23 21:01:09 +03:00
*Note: Make sure to actually replace TOKEN with your own API token.*
2015-06-26 09:58:20 +03:00
2015-08-23 20:32:23 +03:00
After that declaration, we need to register some so-called message handlers. Message handlers define filters which a message must pass. If a message passes the filter, the decorated function is called and the incoming message is passed as an argument.
Let's define a message handler which handles incoming `/start` and `/help` commands.
```python
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
2015-06-26 09:58:20 +03:00
```
2015-08-23 20:32:23 +03:00
A function which is decorated by a message handler __can have an arbitrary name, however, it must have only one parameter (the message)__.
2015-06-26 13:05:23 +03:00
2015-08-23 20:32:23 +03:00
Let's add another handler:
```python
2015-08-23 23:23:18 +03:00
@bot.message_handler(func=lambda m: True)
2015-08-23 20:32:23 +03:00
def echo_all(message):
bot.reply_to(message, message.text)
```
2015-08-23 23:06:11 +03:00
This one echoes all incoming text messages back to the sender. It uses a lambda function to test a message. If the lambda returns True, the message is handled by the decorated function. Since we want all messages to be handled by this function, we simply always return True.
2015-06-26 13:05:23 +03:00
2015-08-23 21:01:09 +03:00
*Note: all handlers are tested in the order in which they were declared*
2015-08-23 23:23:18 +03:00
We now have a basic bot which replies a static message to "/start" and "/help" commands and which echoes the rest of the sent messages. To start the bot, add the following to our source file:
2015-06-26 13:05:23 +03:00
```python
2015-08-23 20:32:23 +03:00
bot.polling()
```
Alright, that's it! Our source file now looks like this:
```python
import telebot
2015-06-26 13:05:23 +03:00
2015-08-23 23:06:11 +03:00
bot = telebot.TeleBot("TOKEN")
2015-06-26 13:05:23 +03:00
2015-08-23 20:32:23 +03:00
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
2015-06-26 13:05:23 +03:00
2015-08-23 23:23:18 +03:00
@bot.message_handler(func=lambda message: True)
2015-08-23 20:32:23 +03:00
def echo_all(message):
bot.reply_to(message, message.text)
2015-06-26 13:05:23 +03:00
2015-08-23 20:32:23 +03:00
bot.polling()
2015-06-26 13:05:23 +03:00
```
2015-08-23 20:32:23 +03:00
To start the bot, simply open up a terminal and enter `python echo_bot.py` to run the bot! Test it by sending commands ('/start' and '/help') and arbitrary text messages.
## General API Documentation
### Types
2015-06-26 16:56:49 +03:00
2015-08-23 22:56:42 +03:00
All types are defined in types.py. They are all completely in line with the [Telegram API's definition of the types](https://core.telegram.org/bots/api#available-types), except for the Message's `from` field, which is renamed to `from_user` (because `from` is a Python reserved token). Thus, attributes such as `message_id` can be accessed directly with `message.message_id`. Note that `message.chat` can be either an instance of `User` or `GroupChat` (see [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat)).
The Message object also has a `content_type`attribute, which defines the type of the Message. `content_type` can be one of the following strings:
'text', 'audio', 'document', 'photo', 'sticker', 'video', 'location', 'contact', 'new_chat_participant', 'left_chat_participant', 'new_chat_title', 'new_chat_photo', 'delete_chat_photo', 'group_chat_created'.
2015-06-27 05:25:22 +03:00
2015-08-23 20:32:23 +03:00
### Methods
All [API methods](https://core.telegram.org/bots/api#available-methods) are located in the TeleBot class. They are renamed to follow common Python naming conventions. E.g. `getMe` is renamed to `get_me` and `sendMessage` to `send_message`.
### General use of the API
Outlined below are some general use cases of the API.
#### Message handlers
A message handler is a function that is decorated with the `message_handler` decorator of a TeleBot instance. Message handlers consist of one or multiple filters.
Each filter much return True for a certain message in order for a message handler to become eligible to handle that message. A message handler is declared in the following way (provided `bot` is an instance of TeleBot):
2015-09-08 11:44:31 +03:00
```python
@bot.message_handler(filters)
def function_name(message):
bot.reply_to(message, "This is a message handler")
```
`function_name` is not bound to any restrictions. Any function name is permitted with message handlers. The function must accept at most one argument, which will be the message that the function must handle.
`filters` is a list of keyword arguments.
A filter is declared in the following manner: `name=argument`. One handler may have multiple filters.
2015-09-08 11:44:31 +03:00
TeleBot supports the following filters:
2015-09-08 12:29:35 +03:00
2015-09-08 11:44:31 +03:00
|name|argument(s)|Condition|
|:---:|---| ---|
|content_types|list of strings (default `['text']`)|`True` if message.content_type is in the list of strings.|
2015-09-08 20:47:55 +03:00
|regexp|a regular expression as a string|`True` if `re.search(regexp_arg)` returns `True` and `message.content_type == 'text'` (See [Python Regular Expressions](https://docs.python.org/2/library/re.html)|
2015-09-08 11:44:31 +03:00
|commands|list of strings|`True` if `message.content_type == 'text'` and `message.text` starts with a command that is in the list of strings.|
|func|a function (lambda or function reference)|`True` if the lambda or function reference returns `True`
2015-09-08 11:44:31 +03:00
Here are some examples of using the filters and message handlers:
2015-06-27 05:25:22 +03:00
```python
import telebot
2015-08-23 20:32:23 +03:00
bot = telebot.TeleBot("TOKEN")
2015-06-27 05:25:22 +03:00
2015-08-23 20:32:23 +03:00
# Handles all text messages that contains the commands '/start' or '/help'.
@bot.message_handler(commands=['start', 'help'])
def handle_start_help(message):
pass
# Handles all sent documents and audio files
@bot.message_handler(content_types=['document', 'audio'])
def handle_docs_audio(message):
pass
# Handles all text messages that match the regular expression
@bot.message_handler(regexp="SOME_REGEXP")
def handle_message(message):
pass
2015-06-27 05:25:22 +03:00
2015-08-23 20:32:23 +03:00
#Handles all messages for which the lambda returns True
@bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', content_types=['document'])
def handle_text_doc(message):
pass
2015-07-07 06:51:11 +03:00
2015-08-23 20:32:23 +03:00
#Which could also be defined as:
def test_message(message):
return message.document.mime_type == 'text/plan'
2015-07-07 06:51:11 +03:00
2015-08-23 20:32:23 +03:00
@bot.message_handler(func=test_message, content_types=['document'])
def handle_text_doc(message)
pass
```
2015-09-08 11:44:31 +03:00
**Important: all handlers are tested in the order in which they were declared**
2015-08-23 20:32:23 +03:00
#### TeleBot
```python
import telebot
TOKEN = '<token_string>'
tb = telebot.TeleBot(TOKEN) #create a new Telegram Bot object
2015-07-24 04:22:02 +03:00
# Upon calling this function, TeleBot starts polling the Telegram servers for new messages.
# - none_stop: True/False (default False) - Don't stop polling when receiving an error from the Telegram servers
# - interval: True/False (default False) - The interval between polling requests
# Note: Editing this parameter harms the bot's response time
# - block: True/False (default True) - Blocks upon calling this function
tb.polling(none_stop=False, interval=0, block=True)
2015-06-27 05:25:22 +03:00
# getMe
user = tb.get_me()
2015-09-05 13:12:52 +03:00
# getUpdates
updates = tb.get_updates()
updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout):
2015-06-27 05:25:22 +03:00
# sendMessage
tb.send_message(chatid, text)
# forwardMessage
tb.forward_message(to_chat_id, from_chat_id, message_id)
2015-08-23 22:56:42 +03:00
# All send_xyz functions which can take a file as an argument, can also take a file_id instead of a file.
# sendPhoto
2015-06-27 05:25:22 +03:00
photo = open('/tmp/photo.png', 'rb')
tb.send_photo(chat_id, photo)
2015-08-23 22:56:42 +03:00
tb.send_photo(chat_id, "FILEID")
2015-06-27 05:25:22 +03:00
# sendAudio
2015-08-21 18:09:35 +03:00
audio = open('/tmp/audio.mp3', 'rb')
2015-06-27 05:25:22 +03:00
tb.send_audio(chat_id, audio)
2015-08-23 22:56:42 +03:00
tb.send_audio(chat_id, "FILEID")
2015-08-23 20:32:23 +03:00
2015-08-21 18:09:35 +03:00
## sendAudio with duration, performer and title.
tb.send_audio(CHAT_ID, file_data, 1, 'eternnoir', 'pyTelegram')
2015-06-27 05:25:22 +03:00
2015-08-21 18:09:35 +03:00
# sendVoice
voice = open('/tmp/voice.ogg', 'rb')
tb.send_voice(chat_id, voice)
2015-08-23 22:56:42 +03:00
tb.send_voice(chat_id, "FILEID")
2015-08-21 18:09:35 +03:00
2015-06-27 05:25:22 +03:00
# sendDocument
doc = open('/tmp/file.txt', 'rb')
tb.send_document(chat_id, doc)
2015-08-23 22:56:42 +03:00
tb.send_document(chat_id, "FILEID")
2015-06-27 05:25:22 +03:00
# sendSticker
sti = open('/tmp/sti.webp', 'rb')
tb.send_sticker(chat_id, sti)
2015-08-23 22:56:42 +03:00
tb.send_sticker(chat_id, "FILEID")
2015-06-27 05:25:22 +03:00
# sendVideo
video = open('/tmp/video.mp4', 'rb')
tb.send_video(chat_id, video)
2015-08-23 22:56:42 +03:00
tb.send_video(chat_id, "FILEID")
2015-06-27 05:25:22 +03:00
2015-06-27 17:11:18 +03:00
# sendLocation
tb.send_location(chat_id, lat, lon)
2015-06-28 12:58:15 +03:00
# sendChatAction
# action_string can be one of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video',
# 'record_audio', 'upload_audio', 'upload_document' or 'find_location'.
2015-06-28 12:58:15 +03:00
tb.send_chat_action(chat_id, action_string)
# getFile
# Downloading a file is straightforward
# Returns a File object
import requests
file_info = tb.get_file(file_id)
file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(API_TOKEN, file_info.file_path))
2015-08-23 20:32:23 +03:00
```
#### Reply markup
All `send_xyz` functions of TeleBot take an optional `reply_markup` argument. This argument must be an instance of `ReplyKeyboardMarkup`, `ReplyKeyboardHide` or `ForceReply`, which are defined in types.py.
2015-06-28 12:58:15 +03:00
2015-08-23 20:32:23 +03:00
```python
2015-07-01 04:55:25 +03:00
from telebot import types
2015-08-23 22:56:42 +03:00
# Using the ReplyKeyboardMarkup class
2015-08-23 20:32:23 +03:00
# It's constructor can take the following optional arguments:
# - resize_keyboard: True/False (default False)
# - one_time_keyboard: True/False (default False)
# - selective: True/False (default False)
# - row_width: integer (default 3)
# row_width is used in combination with the add() function.
# It defines how many buttons are fit on each row before continuing on the next row.
markup = types.ReplyKeyboardMarkup(row_width=2)
2015-06-30 08:20:44 +03:00
markup.add('a', 'v', 'd')
2015-08-23 22:56:42 +03:00
tb.send_message(chat_id, "Choose one letter:", reply_markup=markup)
# or add strings one row at a time:
2015-06-30 08:20:44 +03:00
markup = types.ReplyKeyboardMarkup()
markup.row('a', 'v')
markup.row('c', 'd', 'e')
2015-08-23 22:56:42 +03:00
tb.send_message(chat_id, "Choose one letter:", reply_markup=markup)
```
The last example yields this result:
2015-08-23 23:23:18 +03:00
2015-08-23 22:56:42 +03:00
![ReplyKeyboardMarkup](https://pp.vk.me/c624430/v624430512/473e5/_mxxW7FPe4U.jpg "ReplyKeyboardMarkup")
2015-06-30 08:20:44 +03:00
2015-08-23 22:56:42 +03:00
```python
# ReplyKeyboardHide: hides a previously sent ReplyKeyboardMarkup
2015-08-23 20:32:23 +03:00
# Takes an optional selective argument (True/False, default False)
markup = types.ReplyKeyboardHide(selective=False)
tb.send_message(chat_id, message, reply_markup=markup)
2015-08-23 22:56:42 +03:00
```
2015-08-01 16:03:40 +03:00
2015-08-23 22:56:42 +03:00
```python
# ForceReply: forces a user to reply to a message
2015-08-23 20:32:23 +03:00
# Takes an optional selective argument (True/False, default False)
markup = types.ForceReply(selective=False)
2015-08-23 22:56:42 +03:00
tb.send_message(chat_id, "Send me another word:", reply_markup=markup)
2015-06-28 12:35:47 +03:00
```
2015-08-23 23:23:18 +03:00
ForceReply:
2015-08-01 16:03:40 +03:00
2015-08-23 22:56:42 +03:00
![ForceReply](https://pp.vk.me/c624430/v624430512/473ec/602byyWUHcs.jpg "ForceReply")
2015-08-23 20:32:23 +03:00
## Advanced use of the API
2015-08-01 16:03:40 +03:00
2015-08-23 20:32:23 +03:00
### Asynchronous delivery of messages
There exists an implementation of TeleBot which executes all `send_xyz` and the `get_me` functions asynchronously. This can speed up you bot __significantly__, but it has unwanted side effects if used without caution.
To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
```python
2015-08-23 20:32:23 +03:00
tb = telebot.AsyncTeleBot("TOKEN")
```
Now, every function that calls the Telegram API is executed in a separate Thread. The functions are modified to return an AsyncTask instance (defined in util.py). Using AsyncTeleBot allows you to do the following:
```python
import telebot
2015-08-23 23:23:18 +03:00
tb = telebot.AsyncTeleBot("TOKEN")
2015-08-23 20:32:23 +03:00
task = tb.get_me() # Execute an API call
# Do some other operations...
a = 0
for a in range(100):
a += 10
2015-08-23 20:32:23 +03:00
result = task.wait() # Get the result of the execution
```
2015-08-23 20:32:23 +03:00
*Note: if you execute send_xyz functions after eachother without calling wait(), the order in which messages are delivered might be wrong.*
2015-08-01 16:03:40 +03:00
2015-08-23 20:32:23 +03:00
### Sending large text messages
2015-08-23 23:23:18 +03:00
Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:
```python
from telebot import util
2015-08-23 20:32:23 +03:00
large_text = open("large_text.txt", "rb").read()
2015-08-23 23:23:18 +03:00
# Split the text each 3000 characters.
# split_string returns a list with the splitted text.
splitted_text = util.split_string(large_text, 3000)
2015-08-23 20:32:23 +03:00
for text in splitted_text:
tb.send_message(chat_id, text)
```
2015-08-23 20:32:23 +03:00
### Controlling the amount of Threads used by TeleBot
The TeleBot constructor takes the following optional arguments:
2015-08-23 23:23:18 +03:00
- create_threads: True/False (default True). A flag to indicate whether
TeleBot should execute message handlers on it's polling Thread.
2015-08-23 20:32:23 +03:00
- num_threads: integer (default 4). Controls the amount of WorkerThreads created for the internal thread pool that TeleBot uses to execute message handlers. Is not used when create_threads is False.
2015-08-01 16:03:40 +03:00
2015-08-23 20:32:23 +03:00
### The listener mechanism
As an alternative to the message handlers, one can also register a function as a listener to TeleBot. Example:
```python
2015-08-23 21:07:06 +03:00
def handle_messages(messages):
2015-08-23 20:32:23 +03:00
for message in messsages:
# Do something with the message
2015-08-23 21:07:06 +03:00
bot.reply_to(message, 'Hi')
2015-08-23 20:32:23 +03:00
bot.set_update_listener(handle_messages)
bot.polling()
```
2015-06-28 12:35:47 +03:00
2015-08-23 20:32:23 +03:00
### Using web hooks
If you prefer using web hooks to the getUpdates method, you can use the `process_new_messages(messages)` function in TeleBot to make it process the messages that you supply. It takes a list of Message objects. This function is still incubating.
2015-07-20 05:38:33 +03:00
2015-08-23 20:32:23 +03:00
### Logging
2015-08-23 23:23:18 +03:00
You can use the Telebot module logger to log debug info about Telebot. Use `telebot.logger` to get the logger of the TeleBot module.
2015-09-08 20:56:05 +03:00
It is possible to add custom logging Handlers to the logger. Refer to the [Python logging module page](https://docs.python.org/2/library/logging.html) for more info.
2015-07-20 05:38:33 +03:00
```python
2015-09-08 20:56:05 +03:00
import logging
2015-07-20 05:38:33 +03:00
logger = telebot.logger
2015-09-08 20:56:05 +03:00
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.
2015-07-20 05:38:33 +03:00
```
2015-08-23 21:01:09 +03:00
## F.A.Q.
### How can I distinguish a User and a GroupChat in message.chat?
There are two ways to do this:
- Checking the instance of message.chat with `isinstance`:
```python
def is_user(chat):
return isinstance(chat, types.User)
print is_user(message.chat) # True or False
```
- Checking whether the chat id is negative or positive. If the chat id is negative, the chat is a GroupChat, if it is positive, it is a User. Example:
```python
def is_user(chat):
return chat.id > 0
print is_user(message.chat) # True or False
```
2015-08-23 20:32:23 +03:00
## The Telegram Chat Group
2015-07-17 16:40:33 +03:00
Get help. Discuss. Chat.
2015-08-23 21:01:09 +03:00
Join the [pyTelegramBotAPI Telegram Chat Group](https://telegram.me/joinchat/067e22c60035523fda8f6025ee87e30b).
2015-07-17 16:40:33 +03:00
2015-08-23 20:32:23 +03:00
## More examples
2015-07-09 05:38:35 +03:00
* [Echo Bot](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/echo_bot.py)
* [Deep Linking](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/deep_linking.py)
2015-08-23 21:03:46 +03:00
* [next_step_handler Example](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py)