Telegram api как установить
Перейти к содержимому

Telegram api как установить

  • автор:

 

Создаем Telegram бота на API.AI

Сегодня я опишу вам простой пример создания бота Telegram с использованием платформы для создания разговорных интерфейсов API.AI, который будет приветствовать пользователя и отвечать на вопросы о погоде. По большей части я следовал этим инструкциям, в реальной практике, можно не ограничиваться погодой и реализовать интерфейсы
для автоматизированной поддержки или продаж.

Шаг первый: Подготовка инфраструктуры.

В этом кейсе мы будем использовать только Telegram бота и API.AI, оба сервиса предоставляются бесплатно — нам остается только завести учетные записи.

Создайте бота Telegram

Чтобы создать бота — просто напишите @BotFather (это такой бот, которые умеет создавать и настраивать другие боты):

  1. Отправьте команду /newbot — так мы сообщаем @BotFather, что нам нужен новый бот
  2. Теперь @BotFather попросит нас дать имя новому боту. Это имя будут видеть наши
    будущие пользователи, поэтому название нужно давать понятное и простое.
  3. Последним шагом укажем для бота username, в конце которого нужно обязательно
    написать “bot”.
  4. Если имя не занято, получаем сообщение с подтверждением и токен доступа.

Чтобы было понятнее — ниже скриншот со всеми действиям:

image

Немного теории

Пришло время создать агента API.AI, который в сущности является проектом или контейнером (как вам удобнее называть). Агент содержит настройки контекстов, сущностей и ответов:

  • “контекст” (Intent) отражает связь между тем, что сказал пользователь и
    тем что должна сделать наша программа
  • “сущности” (Entities) — это инструмент извлечения значений параметров для
    нашей программы из естественного языка (того что сказал или написал
    пользователь)
  • “ответы” — это конечный результат работы нашей программы, который мы
    отправляем пользователю на его сообщение

Иногда для ответа пользователю достаточно информации из текущего диалога, в таком случае можно можно настроить статичные ответы в контекстах. В реальности для получения конкретного ответа нам может потребоваться внешний сервис или своя бизнес логика, например, чтобы получить информацию о погоде на завтра, нужно вызвать внешний API соответствующего сервиса. Позже я расскажу вам получать информацию из внешних систем, но для начала подготовим базу.

Создайте проект в API.AI

Для регистрации в API.AI вам потребуется аккаунт Google (достаточно завести в почту в Gmail). Теперь перейдите по адресу https://api.ai/, нажмите на кнопку “SIGN UP FOR FREE”, а за тем выберите аккаунт, от имени которого хотите авторизоваться.

Теперь переходим к созданию самого агента. Нажмите на “Create agent” и укажите как минимум Имя(Name), Язык(Language) и Часовой пояс (Time Zone).

image

Шаг второй: Настройте агента.

Контекст отражает связь между тем, что говорит пользователь, и что должен сделать наш агент. В нашем случае, рассмотрим случай с прогнозом погоды:

image

  1. Кликните на в разделе “Контекст” (Intents). В агенте уже настроены “контексты” на приветствие и ошибки, оставим их пока без изменений.
  2. Укажите название для “контекста” — любое, главное чтобы оно было понятно вам и вашим коллегам.
  3. В разделе “Реплики пользователя” (User Says) приведите примеры вопросов, который может ваш пользователь. Так как мы говорим о погоде, человек может задать вопрос в привязке ко времени и место — учтем это. Чем больше примеров вы предоставите в настройках, тем точнее будет работать агент. Некоторые примеры я привел на скриншоте:

image

В последнем примере слова “завтра” и “Нижнем Тагиле” подсвечены разными цветами — таким образом слова связываются с сущностями (Entities) (в нашем случае сущности системные). Используя эти параметры агент “поймет” в каком городе и для какой даты нужно узнавать погоду.

Добавьте еще парочку своих примеров и нажмите “Сохранить” (SAVE).

Тестируем!

Проверим работу агента на простых вопросах, например, “Погода в Перми в среду”:

image

Все это время в правой верхней части экрана маячила надпись “Try it now” — напишите в это поле или произнесите простой вопрос о погоде и нажмите “Ввод”.

Мы еще не настраивали автоматический ответ, но некоторые параметры агент уже научился определять! В разделе INTENT отражено, что по “мнению” агента пользователь интересуется погодой (настроенный нами “контекст”), в PARAMETER — дату и название города в соответствующих переменных.

Добавьте автоматические ответы

Сделаем нашего агента разговорчивей! Пока мы не научились получать информацию о погоде из внешних источников, добавим в качестве ответов простые фразы.

Перейдите в раздел “ Ответы” (Response) и введите простые ответы аналогично тому, как вы заполняли “Реплики пользователя”:

image

Как видите — в ответах можно использовать ссылки на выявленные сущности, начните набирать $ — и интерфейс предложит вам выбрать конкретную переменную.

При формировании ответа агент учитывает количество определенных сущностей и не использует ответы, данных для которых недостаточно. Например, на вопрос без указания города агент использует ответ из второй строки.

Сохраните настройки и протестируйте еще раз:

image

Теперь у нас есть еще и ответ!

Шаг третий: Добавьте внешний сервис.

Наш агент уже “понимает” в каких случая пользователь хочет узнать погоду, на какое число и в каком городе. Теперь осталось получить эти данные из подходящего сервиса и передать агенту. Для этого вам нужно написать парочку скриптов на JS и разместить их в облачном сервисе, в нашем случае — Google Cloud Project.

Создайте стартовый JS файл

Для начала, создайте и перейдите в директорию с именем вашего проекта:

Linux или Mac OS X:

mkdir %HOMEPATH%[PROJECT_NAME]
cd %HOMEPATH%[PROJECT_NAME]

Теперь создайте файл index.js со следующим содержанием:

Настройте Google Cloud Project

  • Выполните настройки “Before you
    begin” с 1 по 5 пункты

Разверните функцию в облаке выполнив в консоли:

gcloud beta functions deploy itsm365Weather —stage-bucket [BUCKET_NAME] —trigger-http

где, itsm365Weather — название функции, а [BUCKET_NAME] — наименование хранилища
данных для проекта.

После завершения операции вы увидите результат с URL http триггера:

image

Включите Webhook в API.AI

image

  1. Убедитесь, что находитесь в нужном агенте, а затем кликните “Fulfillment” в левом скрывающемся меню.
  2. Включите использование Webhook в правой верхней части экрана.
  3. Введите URL, полученный на предыдущем этапе.
  4. Сохраните изменения.

Подключите исполнение новой функции в настройках “контекста”

image

  1. Перейдите в настройки “контекста” прогноза погоды
  2. Разверните блок Fulfillment в нижней части страницы
  3. Отметьте галочкой “Использовать Webhook”
  4. Сохраните настройки и проверьте результат:

image

Настройте API для получения погоды

Для простоты, воспользуемся сервисом WWO (World Weather Online), в котором вам нужно получить ключ API (просто зарегистрируйтесь через Facebook или Github).

Обновите код стартового JS файла, не забыв ввести ключ API для получения информации о погоде:

Заново разверните функцию в облачном проекте.

Шаг четвертый: настройка ветвей диалога

Взаимодействуя с пользователем мы не можем быть уверены в том, что он предоставит нам всю информацию, необходимую для подготовки ответа во внешнем сервисе сразу в самом первом сообщении. В нашем примере для получения прогноза сервису потребуется дата и город. Если дата не известна, мы можем с успехом предположить, что пользователь подразумевает “сегодня”, но о городе мы можем узнать только от самого пользователя.

Сделайте “расположение” обязательным параметром

Откройте настройки контекста “Прогноз погоды” и укажите параметр geo-city обязательным к заполнению. Затем настройте уточняющий вопрос по ссылке в колонке “Prompts”.

Сохраните настройки и проверьте поведение агента, задав ему простой вопрос “погода”:

image

Агент задал нам уточняющий вопрос, в консоли отображены параметры текущей
ситуации.

Создайте возвращаемое уточнение для расположения

Чтобы использовать данные полученные на предыдущих этапа взаимодействия с пользователем, вам потребуется настроить соответствующие уточнения.

image

В настройка контекста “прогноз погоды” вбейте в поле “Add output context” название возвращаемого уточнения “location” и сохраните настройки.

Создайте новый контекст для уточнения

Удобно, когда по одному и тому же расположению можно задавать несколько вопросов, при этом не уточнять у пользователя, какой город он имеет ввиду. Вы уже настроили возвращаемое уточнение, которе как можно использовать для обработки уточняющих вопросов.

image

  1. Создайте новый контекст в разделе Intents или кликните по значку в строке
    Intents левого выдвигающегося меню.
  2. Назовите новый контекст “Уточнение погоды” (или любое другое понятное вам название).
  3. Установите входящие и исходящие уточнения как “location”
  4. Добавьте реплики пользователя, например, “Что на счет завтра”
  5. Добавьте параметр сущности со следующими значениями:
    Parameter Name:
    geo-city
    Value: #location.geo-city
  6. Добавьте ответ для пользователя в раздел “Response”:
    — “Извини, но я не могу получить прогноз на $date-period в #location.geo-city”
  7. Включите использование webhook в меню Fulfillment.
  8. Сохраните настройки и протестируйте в консоли:

Шаг пятый: Приветствие и обработка непредвиденных ситуаций

Основной костяк агента готов, теперь неплохо сделать так, чтобы робот
приветствовал пользователя, а также знал что отвечать на непредвиденные вопросы.

Настройте ответы “по умолчанию” для непредвиденных ситуаций

Если пользовать задаст непредвиденный вопрос (в нашем случае — не о погоде) агент включит в работу контекст для обработки непредвиденных ситуаций (Default Fallback Intent):

image

Перейдите в настройке этого контекста, при необходимости настройте свои варианты ответов.

Настройте контекст приветствия

Приветствие можно настроить аналогичным способом в соответствующем контенте —
Default Welcome Intent

image

Шаг шестой: запустите бота

Подключите Telegram бота к агенту

Перейдите в настройки “Интеграций” (Integrations) и включите бота в разделе
“One-click integrations”:

image

Скопируйте в поле “Telegram token” токен, который вы получили у @botFather и
нажмите на START.

Проверьте работу бота

Перейдите в своего бота и попробуйте ему что-нибудь написать, в моем случае это
@itsm365_weather_bot (я пользовался бесплатными аккаунтами погоды, поэтому после 500 запросов в день бот превратится в тыкву).

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:

ReplyKeyboardMarkup

ForceReply

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.

Основы создания Telegram бота на Python

Как создать Telegram bot на Python основы

В этой статье мы разберём, как создать простой Telegram bot на языке программирования Python, но тут будут только основы, которые скорее для новичков, чем для профессионалов.

Также если вас интересует разработка ботов, но на JavaScript, то можете посмотреть статью: «Telegram bot на JavaScript», ещё скажу, что по сути мы будем делать бота из этой статьи, только на Python.

Установка Telegram API:

Для начала нужно скачать нужный API, для создания бота, но перед этим рекомендуется сделать виртуальное окружение, для этого прочитайте статью «Создание Virtual Environments Python».

После того как это сделали скачиваем telegram bot API на Python, это делается как обычно через pip install.

На этом установка закончилась.

Регистрация Telegram бота:

Перед созданием, нужно получить токен для бота, для этого напишите боту @BotFather.

botFather

Там пишем команду «/newbot», после вам нужно будет выбрать имя бота, которое будет отображается в списке чатов, потом имя для обращения к чату, которое через знак собаки, после этого получите токен.

Получение токена для API, чтобы создать Telegram bot на Python

Там где замазано, это и есть токен который вы получаете.

Создание Telegram bot на Python:

Теперь перейдём к самому интересному, это к написанию кода, для этого создадим файл где всё будет хранится, я его назову «main.py», в начале в нём делаем импорт и создаём переменную для токена.

Здесь мы подключаем API и специальную библиотеку «types», которая нам нужна для создания кнопок к сообщениям, но кроме этого у неё есть и другие возможности.

Потом объявляем переменную для токена, и создаём бота.

Следующие, пишем не большую функцию для создания кнопок.

Здесь первым делом мы должны сделать специальный массив, для хранения кнопок, используя types.InlineKeyboardMarkup() , потом делаем две кнопки, тут самое интересное, то какие параметры используются при создание, первый, это текст кнопки, а второе, callback_data , то какое значение оно будет возвращать при нажатие.

После через метод add() , добавляем их в массив и возвращаем его. После можно создать функцию, которая будет срабатывать при запуске бота.

Первым делом у нас идёт декоратор, который срабатывает при получение команды «/start», которые обозначаются в параметре commands, который является списком и можно обозначить таким образом несколько команд.

Потом создаём функцию для отправки сообщения, в ней первым делом получаем наши кнопки, потом через функцию send_message() , мы отправляем сообщение.

Примечание:

Название функции после декоратора может быть любое, это не имеет значение.

Последняя функция которая осталось сделать, это для получения значений их кнопки, она делается точно таким же способом.

Здесь мы уже в качестве декоратора обозначаем получение информации от кнопок, но это может быть и что-то другое не обязательно кнопки.

Внутри функции мы создаём кнопки и проверяем, есть ли вообще сообщение, если да, то идёт проверка, что значение сообщения рано одному, это параметр callback_data, который мы использовали при создание кнопок.

Если все верно, то открываем картинку и отправляем её с помощью функции send_photo() , тут все такие же параметры как и при отправки обычного сообщения, только есть photo, которому задаём картинку и вместо text , для текста сообщения, используем caption , дальше закрываем картинку.

Если же первое условие не верно, то проверяем второе, то там нужно значение два, если правильно, то делаем всё также, единственное вместо картинки с водой, используем картинку с блинчиками.

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *