Создаем Telegram бота на Python часть-1

8168

Существует множество различных статей и учебных пособий по созданию ботов для телеграмм, некоторые из них достаточно сложны, часть требует знания отдельных технологий и фреймворков. В данной статье мы рассмотрим создание чат бота в мессенджере Telegram с нуля. От нас не будет требоваться каких-то специальных знаний. Для начала достаточно будет начальных знаний языка Python в качестве языка программирования.
Часть 1: Регистрация нового Telegram Bot-а
Для начала вы должны быть зарегистрированы в Telegram- мессенджере. Далее, вы в мобильной, десктопной или web-версии мессенджера открываете общение с ботом @BotFather, либо по ссылке https://telegram.me/botfather.

После начала общения с этим ботом, нажав /start, вы получите ответ от бота с указанием его возможностей. Нас интересует создание нового бота — /newbot.
После того как мы введем /newbot нас попросят придумать имя для нашего нового бота. Пусть оно будет MyFirstTestBot.
Далее нам нужно придумать юзернэйм для нашего бота. В нашем случае это будет mft001_bot.
После этого BotFather высылает нам специальный токен:
Наш токен оказался: 851216368:AAG6_JHHsIqAK-lX2CxOWQHTAM109zdrcZM (В вашем случае токен будет другой.)
Этот токен понадобится нам при настройке нашего бота. Токен должен быть сохранён. Именно он является единственным ключем для взаимодействия с ботом.
Также мы получаем ссылку на нашего бота. В моем случае это t.me/mft001_bot.
Теперь наш Tekegram-бот создан. Мы можем начать настраивать своего бота, например, установить изображение для бота, изменить или добавить описание бота и тп.
Тема связана со специальностями:
С регистрацией бота мы закончили. Наш бот уже есть, но на данный момент он еще ничего не умеет. Теперь нам нужна его начинка – какой-то механизм, который будет обрабатывать наши запросы к этому боту и возвращать нам ответы.
Часть 2 Написание кода
Как и написано выше мы будем создавать нашего бота на языке Python. Установите его с официального сайта, если вы используете Windows или выполните команду в терминале на Linux:
Далее воспользуемся системой управления пакетами PIP, которая используется для установки и управления программными пакетами, и установим библиотеку PyTelegramBotAPI (Telebot):
Создадим логику работы нашего бота. Используя полноценный IDE или простой текстовый редактор создадим файл ourbot.py и заполним его необходимой логикой.
Для начала нам нужно выполнить импорт библиотеки PyTelegramBotAPI (Telebot), написав в нашем файле:
Теперь создадим метод, для получения сообщений.
Возможности PyTelegramBotAPI позволяют отправлять боту аудио (content_types=['audio'), видео (content_types=['video'), документы (content_types=['document'), текст (content_types=['text'), географический адрес (content_types=['location'), данные контакта (content_types=['contact') и стикеры (content_types=['sticker'). Мы, для простоты опыта, будем общаться с ботом только текстом:
Теперь рассмотрим логику обработки наших текстовых сообщений. Мы хотим захардкодить простое общение бота с пользователем: бот должен уметь здороваться, когда с ним здороваются, уметь отвечать на вопросы «Кто ты?», «Как тебя зовут?» и «Что ты умеешь?».
Видео курсы по схожей тематике:

Создаем игру типа “Pokémon Go“

SharePoint 2013 Администрирование

После тела метода, обрабатывающего наши запросы к боту, добавим вызов метода:
Задачей этого метода является создание потока, в котором бот отправляет запросы на сервер, уточняя таким способом, не писал ли ему кто-то сообщение. Параметр none_stop: False означает, что наша программа будет продолжать отправлять запросы на сервер после получения сообщения об ошибке от сервера Telegram.
Сохраним наш код:
Мы можем протестировать работу нашего бота, запустив его код в той IDE, в которой мы писали. И написав нашему боту в мессенджере.
Наш учебный Telegram-бот создан. Мы можем запустить наш файл локально, и он будет отрабатывать запросы к нему через мессенджер прямо на нашем компьютере, выступающим в роли сервера. Но это не очень удобная практика. Для нормальной работы код желательно залить на отдельный сервер и запустить его там.
Вопросы заливки нашего простого бота на сервер мы рассмотрим в следующей статье.
Резюме
Как мы увидели, создание работающего бота на Python для Telegram мессенджера достаточно просто. Для простых ботов не нужно использовать сложные решения — есть удобная библиотека PyTelegramBotAPI, позволяющая решить такие задачи. В нашем учебном примере мы рассмотрели только работу с текстом, но, благодаря этой библиотеке, бот может работать и с другими форматами данных. Попробуйте сами сделать своего бота, отвечающего на ваши вопросы.
Бесплатные вебинары по схожей тематике:

Agile трансформация в большой компании.

Scrum — быстрое знакомство с методологией гибкой разработки ПО

Как стать UI/UX дизайнером
С нашей стороны мы рекомендуем ознакомиться с курсом подготовки Python-разработчика. Знания, полученные после прохождения данного курса позволят вам не только создавать различные приложения, но и получить полноценную профессию разработчика программного обеспечения.
Введение, простой echo-бот
Приветствую тебя, читатель! Telegram Bot API – это мощный инструмент для вообще чего угодно. Автоматизация действий, работа с пользователями, онлайн-магазины, игры и много чего ещё. В этом учебнике мы научимся писать ботов для Telegram на языке Python.
Сразу оговорюсь: тот бот, который получится в итоге — это лишь прототип, цель всех этих постов — рассказать об основах ботостроения, показать, как можно за короткое время написать простого бота для своих нужд.
Язык программирования будет Python 3, но это не означает, что любители PHP, Ruby и т.д. в пролёте; все основные принципы совпадают. Я не буду особо останавливаться на описании самого языка, желающие могут ознакомиться с документацией по Python здесь.
Подготовка к запуску
Взаимодействие ботов с людьми основано на HTTP-запросах. Чтобы не мучаться с обработкой «сырых» данных, воспользуемся библиотекой pyTelegramBotAPI, которая берет на себя все нюансы отправки и получения запросов, позволяя сконцентрироваться непосредственно на логике. Установка библиотеки предельно простая:
Теперь можно выйти из режима Python-консоли (Ctrl+Z или Ctrl+D, или exit() )
Пишем простого echo-бота
Ну, довольно слов, перейдем к делу. В качестве практики к первому уроку, напишем бота, повторяющего присланное текстовое сообщение. Создадим каталог, а внутри него 2 файла: bot.py и config.py . Я рекомендую выносить различные константы и настройки в файл config.py , дабы не загромождать другие. В файл config.py впишем:
Теперь надо научить бота реагировать на сообщения. Напишем обработчик, который будет реагировать на все текстовые сообщения.
У читателя возникнет вопрос: зачем там символ “@”? Что это вообще за message_handler ? Дело в том, что после приёма сообщения от Telegram его надо обработать по-разному в зависимости от того, что это за сообщение: текст “привет” или текст “пока”, может быть, вообще стикер или музыка. Первое, что придёт в голову – написать множество конструкций if-then-else , но такой подход некрасивый и позволяет быстро запутаться.
Для решения этой проблемы автор библиотеки pyTelegramBotAPI реализовал механизм хэндлеров, которые используют питоновские декораторы (пока просто запомним это слово). В хэндлере описывается, в каком случае необходимо выполнять ту или иную функцию. Например, хэндлер @bot.message_handler(content_types=[«text»]) выполнит нижестоящую функцию, если от Telegram придёт текстовое сообщение, а хэндлер @bot.message_handler(commands=[«start»]) сработает при получении команды /start.
Теперь запустим бесконечный цикл получения новых записей со стороны Telegram:
Функция infinity_polling запускает т.н. Long Polling, бот должен стараться не прекращать работу при возникновении каких-либо ошибок. При этом, само собой, за ботом нужно следить, ибо сервера Telegram периодически перестают отвечать на запросы или делают это с большой задержкой приводя к ошибкам 5xx)
Как написать telegram-бота на python с помощью библиотеки telebot
Как написать telegram-бота на python с помощью библиотеки telebot
Установка и настройка
Для начала давайте скачаем сам python. Сделать это можно на официальном сайте. Не забудьте поставить галочку add to PATH во время установки! После установки python’a нам понадобится хороший редактор кода. На помощь приходит компания JetBrains со своим бесплатным PyCharm. Мы уже близко, осталось скачать библиотеку telebot. Для этого заходим в командную строку и пишем:
Если всё прошло успешно, мы можем продолжать!
Думаю все знают о блокировки telegram в России и единственным решением как всегда остаётся vpn. Лично я рекомендую NordVPN.
Bot Father
В поиске telegram находим Bot Farher’a и создаем своего бота с помощью команды /newbot. Затем вводим имя и юзернейм. Обратите внимание, что юзернейм должен оканчиваться на bot!

Как вы видите нам выдали специальный api токен, с помощью которого вы сможете управлять своим ботом (в моём случае это: 776550937:AAELEr0c3H6dM-9QnlDD-0Q0Fcd65pPyAiM). Свой токен Вы можете запомнить, но я рекомендую его записать.
Настал момент, которого ждали все. Открываем PyCharm и создаем новый проект.

Тут рекомендую поставить всё как у меня (название, конечно можно изменить). После создания проекта, давайте создадим файл, в котором будет наш код. Кликните правой кнопкой по папке с вашем проектом, затем New → Python File. Отлично, начнем писать код. Импортируем библиотеку telebot, с помощью:
Теперь нужно создать переменную bot. На самом деле имя переменной может быть каким угодно, но я привык писать bot.
Напишем декоратор bot.message_handler(), с помощью которого наш бот будет реагировать на команду /start. Для этого в круглых скобках пишем commands=[‘start’]. В итоге у нас должно получиться это:
Если Вы попробуете запустить своего бота (ПКМ->Run), то у вас ничего не выйдет. Во первых в конце кода мы должны прописать bot.polling(). Это нужно для того, чтобы бот не выключился сразу, а работал и проверял, нет ли на сервере нового сообщения. А во вторых наш бот если уж и будет проверять наличие сообщений, то всё равно ничего ответить не сможет. Пора это исправлять! После нашего декоратора создаем функцию start_message, которая будет принимать параметр message (название функции может быть любым). Далее давайте реализуем отправку сообщения от самого бота. В функции пропишем bot.send_message(message.chat.id, ‘Привет, ты написал мне /start’). Смотрите, что у Вас должно получиться:

Отлично, наш бот работает! Чтобы он отвечал не только на команды, но и на сообщения, создадим новый декоратор bot.message_handler(), а в круглые скобочки напишем content_types=[‘text’]. Вообще существует множество видов контента, к примеру location, photo, audio, sticker и т.д. Но нам же нужно отвечать на текст, верно? Поэтому создаём функцию send_text, принимающую параметр message. В функции пропишем условие:
Если текст сообщения будет равен «Привет», то бот отвечает «Привет, мой создатель», а если текст сообщения будет равен «Пока», то бот ответит «Прощай, создатель». Тут думаю всё понятно. Но вы скорее всего задались вопросом, а если пользователь пропишет «привет», ну или «пРиВет», как быть в этой ситуации? Всё достаточно просто! В условии, после message.text напишите функцию .lower(), а в тексте все заглавные буквы замените на строчные. Теперь наш бот отвечает не только на «привет», но и на «ПривеТ», и даже «пРиВеТ».

Вот что у вас должно получиться:
Отлично, с текстом мы разобрались, но как же отправить к примеру стикер? Всё просто! У каждого стикера есть свой id, соответственно зная id мы сможем его отправить. Получить id стикера можно двумя способами. Первый (простой) — через специального бота «What’s the sticker id?»

Ну и второй способ, для тех, кто не ищет лёгких путей. Создаем новый декоратор bot.message_handler(), вот только в скобочки пишем content_types=[‘sticker’]. Далее всё как обычно. Создаем функцию, принимающую параметр message, а вот в ней пропишем print(message). Запускаем бота.

Смотрите, как только я отправил стикер, он сразу же вывел информацию в консоль, и в самом конце будет наш id стикера (file_id). Давайте сделаем так, чтобы когда пользователь отправил боту «я тебя люблю», то бот ему ответил стикером. Создавать новый декоратор не нужно, мы просто допишем условие, которое было до этого. Вот только вместо bot.send_message() пропишем bot.send_sticker(), а вместо текста напишем id стикера.

Поздравляю, всё получилось! Думаю как отправить аудио, фото, и геолокацию, вы разберетесь сами. Я же хочу показать вам, как сделать клавиатуру, которую бот покажет вам при старте. Это уже будет сделать сложнее. Создаем переменную keyboard1, в которую запишем telebot.types.ReplyKeyboardMarkup(). Эта функция вызывает клавиатуру. Далее создадим ряды, но помните, что рядов может быть не больше 12! Для того, чтобы их создать, пишем keyboard1.row(). В круглые скобочки запишите всё что хотите, лично я напишу «Привет» и «Пока». Теперь, чтобы вызвать клавиатуру, допишем reply_markup=keyboard1 к функции отправки сообщения при старте. Вот, что у вас должно получиться:

Вы видите, что клавиатура какая-то большая. Чтобы это исправить, нужно просто в ReplyKeyboardMarkup() прописать True. Ну а если вы хотите, чтобы клавиатура скрывалась, как только пользователь нажал на нее, то напишите еще один True. Подробнее прочитать, что означают эти True вы можете в официальной документации.
Ну а на этом всё! Конечно, это не все возможно ботов в telegram, но основные возможности я вам показал. Спасибо за внимание.
Что такое message?
Наверное многие, кто писал бота по моей предыдущей статье задались вопросом, что такое message и почему к примеру, чтобы отправить сообщение мы должны указать message.chat.id в параметрах функции send_message? Для того, чтобы узнать это давайте выведем message в консоль:
Теперь когда мы вводим команду /start, наш бот присылает огромное кол-во информации. Все, что мы сейчас получили — это ответ в формате json. Json — это простой формат для хранения структурированных данных. Все выводится в формате: ‘ключ’: значение. Давайте посмотрим на то, что получил я:
К примеру из всей этой информации мы хотим получить id чата, из которого я отправлял сообщение. Для этого обратимся к ключу chat.
Смотрите, у ключа chat есть еще несколько ключей: first_name, last_name, username… и у каждого из них есть свои значения. Теперь обратимся к ключу id:
Как вы видите для того чтобы получить нужное значение необходимо просто записать название ключей через точку. А теперь смотрим на ответ от сервера:
Все идет как надо! Мы получили id чата, собственно как и хотели! А теперь получим имя отправителя. Тут, как вы заметили нужно использовать ключ from_user.
Теперь достанем значение у ключа first_name:
Ну вот и все! За пару секунд мы смогли получить id чата и мое имя в telegram. И еще раз, для тех кто не понял:

Чтобы получить значение ключа first_name, нам нужно сначала обратиться к ключу chat, а только потом уже к first_name!
Теперь смотрите, для того, чтобы отправить сообщение в какой-либо чат нам необходимо указать несколько параметров в функцию send_message. Первый параметр — это chat_id, собственно сам id чата. Второй — text, текст сообщения. И как вы догадались, вместо того, чтобы писать message.chat.id, мы можем написать свои данные! Вот так можно прислать сообщение самому себе, если указать в параметрах свой id:
Ну а когда мы пишем message.chat.id, мы подразумеваем, что бот отправит сообщение в чат, из которого его вызвали.
Заключение
Ну а на этом всё! Надеюсь вы поняли как получать данные от сервера, обрабатывать их и использовать где нужно. Спасибо за внимание.
eternnoir/pyTelegramBotAPI
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A simple, but extensible Python implementation for the Telegram Bot API.
Both synchronous and asynchronous.
Supported Bot API version: 6.2!
This API is tested with Python 3.6-3.10 and Pypy 3. There are two ways to install the library:
- Installation using pip (a Python package manager):
- Installation from source (requires git):
It is generally recommended to use the first option.
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
Writing your first bot
It is presumed that you have obtained an API token with @BotFather. We will call this token TOKEN . Furthermore, you have basic knowledge of the Python programming language and more importantly the Telegram Bot API.
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.
Note: Make sure to actually replace TOKEN with your own API token.
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.
A function which is decorated by a message handler can have an arbitrary name, however, it must have only one parameter (the message).
Let’s add another handler:
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.
Note: all handlers are tested in the order in which they were declared
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:
Alright, that’s it! Our source file now looks like this:
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
All types are defined in types.py. They are all completely in line with the Telegram API’s definition of the 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?).
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 , video_note , voice , location , contact , new_chat_members , left_chat_member , new_chat_title , new_chat_photo , delete_chat_photo , group_chat_created , supergroup_chat_created , channel_chat_created , migrate_to_chat_id , migrate_from_chat_id , pinned_message , web_app_data .
You can use some types in one function. Example:
content_types=[«text», «sticker», «pinned_message», «photo», «audio»]
All API 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.
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 must 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):
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. TeleBot supports the following filters:
| name | argument(s) | Condition |
|---|---|---|
| content_types | list of strings (default [‘text’] ) | True if message.content_type is in the list of strings. |
| regexp | a regular expression as a string | True if re.search(regexp_arg) returns True and message.content_type == ‘text’ (See Python Regular Expressions) |
| commands | list of strings | True if message.content_type == ‘text’ and message.text starts with a command that is in the list of strings. |
| chat_types | list of chat types | True if message.chat.type in your filter |
| func | a function (lambda or function reference) | True if the lambda or function reference returns True |
Here are some examples of using the filters and message handlers:
Important: all handlers are tested in the order in which they were declared
Edited Message handler
Handle edited messages @bot.edited_message_handler(filters) # <- passes a Message type object to your function
Channel Post handler
Handle channel post messages @bot.channel_post_handler(filters) # <- passes a Message type object to your function
Edited Channel Post handler
Handle edited channel post messages @bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function
Callback Query Handler
Handle callback queries
Shipping Query Handler
Handle shipping queries @bot.shipping_query_handeler() # <- passes a ShippingQuery type object to your function
Pre Checkout Query Handler
Handle pre checkoupt queries @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function
Handle poll updates @bot.poll_handler() # <- passes a Poll type object to your function
Poll Answer Handler
Handle poll answers @bot.poll_answer_handler() # <- passes a PollAnswer type object to your function
My Chat Member Handler
Handle updates of a the bot’s member status in a chat @bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function
Chat Member Handler
Handle updates of a chat member’s status in a chat @bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function Note: «chat_member» updates are not requested by default. If you want to allow all update types, set allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types
Chat Join Request Handler
Handle chat join requests using: @bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function
More information about Inline mode.
Now, you can use inline_handler to get inline queries in telebot.
Chosen Inline handler
Use chosen_inline_handler to get chosen_inline_result in telebot. Don’t forgot add the /setinlinefeedback command for @Botfather.
Answer Inline Query
Additional API features
A middleware handler is a function that allows you to modify requests or the bot context as they pass through the Telegram to the bot. You can imagine middleware as a chain of logic connection handled before any other handlers are executed. Middleware processing is disabled by default, enable it by setting apihelper.ENABLE_MIDDLEWARE = True .
There are other examples using middleware handler in the examples/middleware directory.
There are class-based middlewares. Basic class-based middleware looks like this:
Class-based middleware should have to functions: post and pre process. So, as you can see, class-based middlewares work before and after handler execution. For more, check out in examples
Also, you can use built-in custom filters. Or, you can create your own filter.
Also, we have examples on them. Check this links:
You can check some built-in filters in source code
If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.
Here is example of creating filter-class:
All send_xyz functions of TeleBot take an optional reply_markup argument. This argument must be an instance of ReplyKeyboardMarkup , ReplyKeyboardRemove or ForceReply , which are defined in types.py.
The last example yields this result:


Working with entities
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:
- type
- url
- offset
- length
- user
Here’s an Example: message.entities[num].<attribute>
Here num is the entity number or order of entity in a reply, for if incase there are multiple entities in the reply/message.
message.entities returns a list of entities object.
message.entities[0].type would give the type of the first entity
Refer Bot Api for extra details
Advanced use of the API
Using local Bot API Sever
Since version 5.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.
Important: Like described here, you have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI use bot.log_out()
Note: 4200 is an example port
New: There is an asynchronous implementation of telebot. To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
Now, every function that calls the Telegram API is executed in a separate asynchronous task. Using AsyncTeleBot allows you to do the following:
Sending large text messages
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:
Or you can use the new smart_split function to get more meaningful substrings:
Controlling the amount of Threads used by TeleBot
The TeleBot constructor takes the following optional arguments:
- threaded: True/False (default True). A flag to indicate whether TeleBot should execute message handlers on it’s polling Thread.
The listener mechanism
As an alternative to the message handlers, one can also register a function as a listener to TeleBot.
NOTICE: handlers won’t disappear! Your message will be processed both by handlers and listeners. Also, it’s impossible to predict which will work at first because of threading. If you use threaded=False, custom listeners will work earlier, after them handlers will be called. Example:
Using web hooks
When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.
There are some examples using webhooks in the examples/webhook_examples directory.
You can use the Telebot module logger to log debug info about Telebot. Use telebot.logger to get the logger of the TeleBot module. It is possible to add custom logging Handlers to the logger. Refer to the Python logging module page for more info.
You can use proxy for request. apihelper.proxy object will use by call requests proxies argument.
If you want to use socket5 proxy you need install dependency pip install requests[socks] and make sure, that you have the latest version of gunicorn , PySocks , pyTelegramBotAPI , requests and urllib3 .
You can disable or change the interaction with real Telegram server by using
parameter. You can pass there your own function that will be called instead of requests.request.
Then you can use API and proceed requests in your handler code.
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params:
API conformance limitations
- ➕ Bot API 4.5 — No nested MessageEntities and Markdown2 support
- ➕ Bot API 4.1 — No Passport support
- ➕ Bot API 4.0 — No Passport support
Asynchronous version of telebot
We have a fully asynchronous version of TeleBot. This class is not controlled by threads. Asyncio tasks are created to execute all the stuff.
Echo Bot example on AsyncTeleBot:
As you can see here, keywords are await and async.
Why should I use async?
Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks will block each other.
Differences in AsyncTeleBot
AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.
See more examples in our examples folder
How can I distinguish a User and a GroupChat in message.chat?
Telegram Bot API support new type Chat for message.chat.
- Check the type attribute in Chat object:
How can I handle reocurring ConnectionResetErrors?
Bot instances that were idle for a long time might be rejected by the server when sending a message due to a timeout of the last used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after 5 minutes without any activity.
The Telegram Chat Group
Get help. Discuss. Chat.
- Join the pyTelegramBotAPI Telegram Chat Group
Join the News channel. Here we will post releases and updates.
Template is a ready folder that contains architecture of basic project. Here are some examples of template:
Bots using this library
-
(source) by ilteoood — Monitors websites and sends a notification on changes by aRandomStranger by GabrielRF — Let me Google that for you. by mrgigabyte by Tronikart — Multifunctional Telegram Bot RadRetroRobot. (source) by i32ropie by @NeoRanger (source) — Share code snippets as beautifully syntax-highlighted HTML and/or images. (source) by alejandrocq — Telegram bot to check the menu of Universidad de Granada dining hall. — Simple Proxy Bot for Telegram. by p-hash — DonantesMalagaBot facilitates information to Malaga blood donors about the places where they can donate today or in the incoming days. It also records the date of the last donation so that it helps the donors to know when they can donate again. — by vfranch by Dmytryi Striletskyi — Timetable for one university in Kiev. by rmed — Send and receive messages to/from WhatsApp through Telegram (source) by jcolladosp — Telegram bot using the Python API that gets films rating from IMDb and metacritic (source) by GabrielRF — Send to Kindle service. (source) by GabrielRF — Bot used to track packages on the Brazilian Mail Service. (link) by EeOneDown — Bot with timetables for SPbU students. (link) by 0xVK — Telegram timetable bot, for Zhytomyr Ivan Franko State University students. (link) — A Telegram Bot created to help people to memorize other languages’ vocabulary. by rubenleon (GitHub) — Bot that provides buses coming to a certain stop and their remaining time for the city of Vigo (Galicia — Spain) (source) by airatk — bot which shows all the necessary information to KNTRU-KAI students. (source) by @FacuM — Support Telegram bot for developers and maintainers. (source) by @DesExcile — Сatalog of poems by Eduard Asadov. (source) by @LeoSvalov — words and synonyms from dictionary.com and thesaurus.com in the telegram. (source) by @irevenko — An all-round bot that displays some statistics (weather, time, crypto etc. ) (source) by @Fliego — a simple bot for food ordering (source) by @0xnu — Telegram bot for displaying the latest news, sports schedules and injury updates. (source) by @zeph1997 — A Telegram Bot to remove «join group» and «removed from group» notifications. (source) by @Pablo-Davila — A (tasks) lists manager bot for Telegram. (source) by @Pablo-Davila — An implementation of the famous Eliza psychologist chatbot. (source) by Mrsqd. A Telegram bot that will always be happy to show you the weather forecast. by ModischFabrications. This bot can start, stop and monitor a minecraft server. by dexpiper. This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show short descriptions to the rolls. by Anvaari. This Bot make «Add to google calendar» link for your events. It give information about event and return link. It work for Jalali calendar and in Tehran Time. Source code by Areeg Fahad. This bot can be used to translate texts. by Areeg Fahad. With this bot, you can now monitor the prices of more than 12 digital Cryptocurrency. by Leon Heess (source). Send any link, and the bot tries its best to remove all tracking from the link you sent. by Vishal Singh(source code) This telegram bot can do tasks like GitHub search & clone,provide c++ learning resources ,Stackoverflow search, Codeforces(profile visualizer,random problems) by Aadithya & Amol Soans This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings) (source) by TrevorWinstral — Gets live COVID Country data, plots it, and briefs the user (source) by TrevorWinstral — Notifies ETH students when their lectures have been uploaded by Resinprotein2333. This bot can help you to find The information of CVE vulnerabilities. (Source by DevAdvik — Get Live Ethereum Gas Fees in GWEI by JoachimStanislaus. This bot can help you to track your expenses by uploading your bot entries to your google sheet. by Carlosma7. This bot is a trivia game that allows you to play with people from different ages. This project addresses the use of a system through chatbots to carry out a social and intergenerational game as an alternative to traditional game development. (source) This bot lets you find difinitions of words in Spanish using RAE’s dictionary. It features direct message and inline search. by EnriqueMoran. Control your LinuxOS computer through Telegram. Query wolframalpha.com and make use of its API through Telegram. This Bot can understand spoken text in videos and translate it to English (source) Zyprexa can solve, help you solve any mathematical problem you encounter and convert your regular mathematical expressions into beautiful imagery using LaTeX. by tusharhero — Makes bincodes from text provides and also converts them back to text. Toolset for Hydrophilia tabletop game (game cards, rules, structure. ). (source) by 咕谷酱 GuXiaoJiang is a multi-functional robot, such as OSU game information query, IP test, animation screenshot search and other functions. A feedback bot for user-admin communication. Made on AsyncTeleBot, using template. by ablakely This is a Telegram to IRC bridge which links as an IRC server and makes Telegram users appear as native IRC users.
Want to have your bot listed here? Just make a pull request. Only bots with public source code are accepted.