banner



How To Set Up Logger Bot

PyPi Package Version Supported Python versions Documentation Status Build Status PyPi downloads PyPi status

pyTelegramBotAPI

A elementary, but extensible Python implementation for the Telegram Bot API.

Both synchronous and asynchronous.

Supported Bot API version: 6.0!

Official documentation

Contents

  • Getting started
  • Writing your first bot
    • Prerequisites
    • A unproblematic echo bot
  • General API Documentation
    • Types
    • Methods
    • Full general use of the API
      • Bulletin handlers
      • Edited Message handler
      • Channel Post handler
      • Edited Channel Postal service handler
      • Callback Query handlers
      • Shipping Query Handler
      • Pre Checkout Query Handler
      • Poll Handler
      • Poll Respond Handler
      • My Conversation Fellow member Handler
      • Conversation Member Handler
      • Chat Bring together request handler
    • Inline Mode
      • Inline handler
      • Chosen Inline handler
      • Answer Inline Query
    • Boosted API features
      • Middleware handlers
      • Custom filters
      • TeleBot
      • Respond markup
  • Advanced utilize of the API
    • Using local Bot API Server
    • Asynchronous TeleBot
    • Sending big text messages
    • Controlling the amount of Threads used by TeleBot
    • The listener mechanism
    • Using web hooks
    • Logging
    • Proxy
    • Testing
  • API conformance
  • AsyncTeleBot
  • F.A.Q.
    • How can I distinguish a User and a GroupChat in bulletin.chat?
    • How can I handle reocurring ConnectionResetErrors?
  • The Telegram Chat Group
  • Telegram Channel
  • More than examples
  • Code Template
  • Bots using this API

Getting started

This API is tested with Python 3.vi-three.10 and Pypy three. There are ii ways to install the library:

  • Installation using pip (a Python package manager):
          $ pip install pyTelegramBotAPI                  
  • Installation from source (requires git):
          $ git clone https://github.com/eternnoir/pyTelegramBotAPI.git $ cd pyTelegramBotAPI $ python setup.py install                  

or:

          $ pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git                  

Information technology is more often than not recommended to apply the commencement 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

          pip install pytelegrambotapi --upgrade                  

Writing your first bot

Prerequisites

It is presumed that y'all have obtained an API token with @BotFather. We will phone call this token TOKEN. Furthermore, you have basic knowledge of the Python programming language and more than importantly the Telegram Bot API.

A unproblematic echo bot

The TeleBot class (divers 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 up the file and create an instance of the TeleBot class.

          import          telebot          bot          =          telebot          .          TeleBot          (          "TOKEN"          ,          parse_mode          =          None          )          # You can set parse_mode by default. HTML or MARKDOWN        

Note: Make sure to really replace TOKEN with your ain API token.

Later on that declaration, we need to register some so-called message handlers. Bulletin handlers ascertain filters which a message must pass. If a bulletin passes the filter, the decorated part is called and the incoming message is passed as an argument.

Let's ascertain a bulletin handler which handles incoming /start and /help commands.

          @bot          .          message_handler          (          commands          =          [          'start'          ,          'assist'          ])          def          send_welcome          (          message          ):          bot          .          reply_to          (          message          ,          "Hi, how are you doing?"          )        

A office which is busy by a bulletin handler can accept an arbitrary name, all the same, it must have only i parameter (the message).

Allow'southward add some other handler:

          @bot          .          message_handler          (          func          =          lambda          m          :          True          )          def          echo_all          (          message          ):          bot          .          reply_to          (          message          ,          message          .          text          )        

This one echoes all incoming text letters back to the sender. It uses a lambda office to test a message. If the lambda returns True, the message is handled by the busy function. Since we want all letters to be handled past this function, we just e'er return Truthful.

Note: all handlers are tested in the order in which they were alleged

We at present have a bones bot which replies a static message to "/first" and "/assistance" commands and which echoes the residuum of the sent messages. To kickoff the bot, add together the following to our source file:

          bot          .          infinity_polling          ()        

Alright, that's it! Our source file now looks like this:

          import          telebot          bot          =          telebot          .          TeleBot          (          "YOUR_BOT_TOKEN"          )          @bot          .          message_handler          (          commands          =          [          'beginning'          ,          'aid'          ])          def          send_welcome          (          bulletin          ):          bot          .          reply_to          (          message          ,          "Howdy, how are yous doing?"          )          @bot          .          message_handler          (          func          =          lambda          message          :          Truthful          )          def          echo_all          (          bulletin          ):          bot          .          reply_to          (          bulletin          ,          message          .          text          )          bot          .          infinity_polling          ()        

To start the bot, just open up a terminal and enter python echo_bot.py to run the bot! Test it by sending commands ('/start' and '/aid') and arbitrary text letters.

General API Documentation

Types

All types are defined in types.py. They are all completely in line with the Telegram API'south 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 straight with message.message_id. Annotation that message.chat can exist either an case of User or GroupChat (meet How tin I distinguish a User and a GroupChat in message.chat?).

The Message object also has a content_typeattribute, which defines the type of the Message. content_type tin can exist one of the following strings: text, sound, certificate, photo, sticker, video, video_note, phonation, 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.

Yous tin employ some types in one function. Example:

content_types=["text", "sticker", "pinned_message", "photo", "sound"]

Methods

All API methods are located in the TeleBot class. They are renamed to follow common Python naming conventions. East.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 must return True for a certain message in order for a bulletin handler to become eligible to handle that message. A bulletin handler is declared in the following style (provided bot is an instance of TeleBot):

          @bot          .          message_handler          (          filters          )          def          function_name          (          message          ):          bot          .          reply_to          (          bulletin          ,          "This is a bulletin handler"          )        

function_name is non bound to any restrictions. Any function proper name is permitted with bulletin handlers. The function must accept at most ane argument, which will be the bulletin that the function must handle. filters is a list of keyword arguments. A filter is alleged in the post-obit way: proper name=argument. One handler may have multiple filters. TeleBot supports the following filters:

proper name argument(s) Condition
content_types list of strings (default ['text']) Truthful if message.content_type is in the list of strings.
regexp a regular expression as a cord True if re.search(regexp_arg) returns True and message.content_type == 'text' (Run across Python Regular Expressions)
commands list of strings True if bulletin.content_type == 'text' and message.text starts with a control that is in the list of strings.
chat_types list of chat types Truthful if message.chat.type in your filter
func a part (lambda or role reference) Truthful if the lambda or office reference returns Truthful

Here are some examples of using the filters and message handlers:

          import          telebot          bot          =          telebot          .          TeleBot          (          "TOKEN"          )          # Handles all text letters that contains the commands '/start' or '/assist'.          @bot          .          message_handler          (          commands          =          [          'start'          ,          'help'          ])          def          handle_start_help          (          bulletin          ):          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          # Handles all messages for which the lambda returns Truthful          @bot          .          message_handler          (          func          =          lambda          message          :          message          .          document          .          mime_type          ==          'text/plain'          ,          content_types          =          [          'document'          ])          def          handle_text_doc          (          message          ):          pass          # Which could also be defined every bit:          def          test_message          (          message          ):          return          bulletin          .          certificate          .          mime_type          ==          'text/plain'          @bot          .          message_handler          (          func          =          test_message          ,          content_types          =          [          'document'          ])          def          handle_text_doc          (          message          ):          pass          # Handlers can be stacked to create a function which will be called if either message_handler is eligible          # This handler will be chosen if the message starts with '/hi' OR is some emoji          @bot          .          message_handler          (          commands          =          [          'hello'          ])          @bot          .          message_handler          (          func          =          lambda          msg          :          msg          .          text          .          encode          (          "utf-viii"          )          ==          SOME_FANCY_EMOJI          )          def          send_something          (          bulletin          ):          pass        

Important: all handlers are tested in the order in which they were declared

Edited Bulletin 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 Mail service handler

Handle edited channel post messages @bot.edited_channel_post_handler(filters) # <- passes a Bulletin type object to your function

Callback Query Handler

Handle callback queries

          @bot          .          callback_query_handler          (          func          =          lambda          call          :          Truthful          )          def          test_callback          (          telephone call          ):          # <- passes a CallbackQuery type object to your function          logger          .          info          (          call          )        

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 blazon object to your function

Poll Handler

Handle poll updates @bot.poll_handler() # <- passes a Poll type object to your function

Poll Reply Handler

Handle poll answers @bot.poll_answer_handler() # <- passes a PollAnswer type object to your part

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 Fellow member Handler

Handle updates of a chat member's condition 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 y'all want to allow all update types, prepare allowed_updates in bot.polling() / bot.infinity_polling() to util.update_types

Conversation Join Request Handler

Handle chat join requests using: @bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function

Inline Manner

More than information about Inline mode.

Inline handler

Now, you can employ inline_handler to get inline queries in telebot.

          @bot          .          inline_handler          (          lambda          query          :          query          .          query          ==          'text'          )          def          query_text          (          inline_query          ):          # Query bulletin is text        

Chosen Inline handler

Use chosen_inline_handler to get chosen_inline_result in telebot. Don't forgot add together the /setinlinefeedback control for @Botfather.

More information : collecting-feedback

          @bot          .          chosen_inline_handler          (          func          =          lambda          chosen_inline_result          :          True          )          def          test_chosen          (          chosen_inline_result          ):          # Process all chosen_inline_result.        

Reply Inline Query

          @bot          .          inline_handler          (          lambda          query          :          query          .          query          ==          'text'          )          def          query_text          (          inline_query          ):          try          :          r          =          types          .          InlineQueryResultArticle          (          'i'          ,          'Effect'          ,          types          .          InputTextMessageContent          (          'Result message.'          ))          r2          =          types          .          InlineQueryResultArticle          (          'ii'          ,          'Result2'          ,          types          .          InputTextMessageContent          (          'Result message2.'          ))          bot          .          answer_inline_query          (          inline_query          .          id          ,          [          r          ,          r2          ])          except          Exception          as          e          :          print          (          eastward          )        

Additional API features

Middleware Handlers

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 equally a chain of logic connection handled earlier any other handlers are executed. Middleware processing is disabled past default, enable it by setting apihelper.ENABLE_MIDDLEWARE = Truthful.

          apihelper          .          ENABLE_MIDDLEWARE          =          Truthful          @bot          .          middleware_handler          (          update_types          =          [          'bulletin'          ])          def          modify_message          (          bot_instance          ,          message          ):          # modifying the message before it reaches any other handler                    message          .          another_text          =          message          .          text          +          ':changed'          @bot          .          message_handler          (          commands          =          [          'get-go'          ])          def          offset          (          message          ):          # the bulletin is already modified when it reaches message handler          assert          message          .          another_text          ==          message          .          text          +          ':inverse'        

There are other examples using middleware handler in the examples/middleware directory.

Class-based middlewares

There are grade-based middlewares. Cheque out in examples

Custom filters

Also, y'all tin can use born custom filters. Or, you tin can create your own filter.

Example of custom filter

Too, we have examples on them. Check this links:

You can bank check some built-in filters in source code

Example of filtering by id

Case of filtering by text

If you want to add together some built-in filter, you are welcome to add together it in custom_filters.py file.

Here is example of creating filter-class:

          class          IsAdmin          (          telebot          .          custom_filters          .          SimpleCustomFilter          ):          # Course will check whether the user is admin or creator in group or non          key          =          'is_admin'          @staticmethod          def          check          (          message          :          telebot          .          types          .          Message          ):          return          bot          .          get_chat_member          (          message          .          chat          .          id          ,          bulletin          .          from_user          .          id          )          .          status          in          [          'administrator'          ,          'creator'          ]          # To register filter, you need to use method add_custom_filter.          bot          .          add_custom_filter          (          IsAdmin          ())          # At present, y'all can use it in handler.          @bot          .          message_handler          (          is_admin          =          True          )          def          admin_of_group          (          bulletin          ):          bot          .          send_message          (          message          .          chat          .          id          ,          'You are admin of this group!'          )        

TeleBot

          import          telebot          TOKEN          =          '<token_string>'          tb          =          telebot          .          TeleBot          (          TOKEN          )          #create a new Telegram Bot object          # Upon calling this function, TeleBot starts polling the Telegram servers for new letters.          # - interval: int (default 0) - The interval between polling requests          # - timeout: integer (default xx) - Timeout in seconds for long polling.          # - allowed_updates: List of Strings (default None) - Listing of update types to request                    tb          .          infinity_polling          (          interval          =          0          ,          timeout          =          20          )          # getMe          user          =          tb          .          get_me          ()          # setWebhook          tb          .          set_webhook          (          url          =          "http://instance.com"          ,          certificate          =          open up          (          'mycert.pem'          ))          # unset webhook          tb          .          remove_webhook          ()          # getUpdates          updates          =          tb          .          get_updates          ()          # or          updates          =          tb          .          get_updates          (          1234          ,          100          ,          20          )          #get_Updates(offset, limit, timeout):          # sendMessage          tb          .          send_message          (          chat_id          ,          text          )          # editMessageText          tb          .          edit_message_text          (          new_text          ,          chat_id          ,          message_id          )          # forwardMessage          tb          .          forward_message          (          to_chat_id          ,          from_chat_id          ,          message_id          )          # All send_xyz functions which can take a file equally an statement, tin also accept a file_id instead of a file.          # sendPhoto          photograph          =          open up          (          '/tmp/photo.png'          ,          'rb'          )          tb          .          send_photo          (          chat_id          ,          photo          )          tb          .          send_photo          (          chat_id          ,          "FILEID"          )          # sendAudio          sound          =          open up          (          '/tmp/audio.mp3'          ,          'rb'          )          tb          .          send_audio          (          chat_id          ,          sound          )          tb          .          send_audio          (          chat_id          ,          "FILEID"          )          ## sendAudio with duration, performer and title.          tb          .          send_audio          (          CHAT_ID          ,          file_data          ,          1          ,          'eternnoir'          ,          'pyTelegram'          )          # sendVoice          phonation          =          open          (          '/tmp/vocalisation.ogg'          ,          'rb'          )          tb          .          send_voice          (          chat_id          ,          vocalization          )          tb          .          send_voice          (          chat_id          ,          "FILEID"          )          # sendDocument          md          =          open          (          '/tmp/file.txt'          ,          'rb'          )          tb          .          send_document          (          chat_id          ,          doctor          )          tb          .          send_document          (          chat_id          ,          "FILEID"          )          # sendSticker          sti          =          open          (          '/tmp/sti.webp'          ,          'rb'          )          tb          .          send_sticker          (          chat_id          ,          sti          )          tb          .          send_sticker          (          chat_id          ,          "FILEID"          )          # sendVideo          video          =          open          (          '/tmp/video.mp4'          ,          'rb'          )          tb          .          send_video          (          chat_id          ,          video          )          tb          .          send_video          (          chat_id          ,          "FILEID"          )          # sendVideoNote          videonote          =          open up          (          '/tmp/videonote.mp4'          ,          'rb'          )          tb          .          send_video_note          (          chat_id          ,          videonote          )          tb          .          send_video_note          (          chat_id          ,          "FILEID"          )          # sendLocation          tb          .          send_location          (          chat_id          ,          lat          ,          lon          )          # sendChatAction          # action_string tin be one of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video',          # 'record_audio', 'upload_audio', 'upload_document' or 'find_location'.          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          ))        

Reply markup

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.

          from          telebot          import          types          # Using the ReplyKeyboardMarkup class          # It's constructor can have the following optional arguments:          # - resize_keyboard: True/Faux (default False)          # - one_time_keyboard: True/Faux (default Fake)          # - 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          )          itembtn1          =          types          .          KeyboardButton          (          'a'          )          itembtn2          =          types          .          KeyboardButton          (          'v'          )          itembtn3          =          types          .          KeyboardButton          (          'd'          )          markup          .          add together          (          itembtn1          ,          itembtn2          ,          itembtn3          )          tb          .          send_message          (          chat_id          ,          "Choose one alphabetic character:"          ,          reply_markup          =          markup          )          # or add KeyboardButton i row at a time:          markup          =          types          .          ReplyKeyboardMarkup          ()          itembtna          =          types          .          KeyboardButton          (          'a'          )          itembtnv          =          types          .          KeyboardButton          (          'v'          )          itembtnc          =          types          .          KeyboardButton          (          'c'          )          itembtnd          =          types          .          KeyboardButton          (          'd'          )          itembtne          =          types          .          KeyboardButton          (          'e'          )          markup          .          row          (          itembtna          ,          itembtnv          )          markup          .          row          (          itembtnc          ,          itembtnd          ,          itembtne          )          tb          .          send_message          (          chat_id          ,          "Choose one letter:"          ,          reply_markup          =          markup          )        

The final example yields this effect:

ReplyKeyboardMarkup

          # ReplyKeyboardRemove: hides a previously sent ReplyKeyboardMarkup          # Takes an optional selective argument (True/False, default Fake)          markup          =          types          .          ReplyKeyboardRemove          (          selective          =          Fake          )          tb          .          send_message          (          chat_id          ,          bulletin          ,          reply_markup          =          markup          )        
          # ForceReply: forces a user to respond to a message          # Takes an optional selective argument (Truthful/False, default False)          markup          =          types          .          ForceReply          (          selective          =          False          )          tb          .          send_message          (          chat_id          ,          "Send me some other discussion:"          ,          reply_markup          =          markup          )        

ForceReply:

ForceReply

Working with entities

This object represents ane special entity in a text message. For example, hashtags, usernames, URLs, etc. Attributes:

  • type
  • url
  • get-go
  • length
  • user

Here'due south an Example: message.entities[num].<attribute>
Here num is the entity number or order of entity in a reply, for if incase at that place are multiple entities in the answer/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 actress details

Avant-garde utilise of the API

Using local Bot API Sever

Since version five.0 of the Bot API, you have the possibility to run your own Local Bot API Server. pyTelegramBotAPI also supports this feature.

          from          telebot          import          apihelper          apihelper          .          API_URL          =          "http://localhost:4200/bot          {0}          /          {ane}          "        

Important: Similar described here, you lot have to log out your bot from the Telegram server before switching to your local API server. in pyTelegramBotAPI utilize bot.log_out()

Notation: 4200 is an instance port

Asynchronous TeleBot

New: There is an asynchronous implementation of telebot. To enable this behaviour, create an case of AsyncTeleBot instead of TeleBot.

          tb          =          telebot          .          AsyncTeleBot          (          "TOKEN"          )        

Now, every function that calls the Telegram API is executed in a separate asynchronous chore. Using AsyncTeleBot allows yous to do the following:

          import          telebot          tb          =          telebot          .          AsyncTeleBot          (          "TOKEN"          )          @tb          .          message_handler          (          commands          =          [          'start'          ])          async          def          start_message          (          message          ):          await          bot          .          send_message          (          message          .          conversation          .          id          ,          'Hello!'          )        

See more in examples

Sending big text messages

Sometimes you must send messages that exceed 5000 characters. The Telegram API tin not handle that many characters in 1 request, so we need to dissever the message in multiples. Hither is how to do that using the API:

          from          telebot          import          util          large_text          =          open          (          "large_text.txt"          ,          "rb"          )          .          read          ()          # Split the text each 3000 characters.          # split_string returns a list with the splitted text.          splitted_text          =          util          .          split_string          (          large_text          ,          3000          )          for          text          in          splitted_text          :          tb          .          send_message          (          chat_id          ,          text          )        

Or you tin can use the new smart_split role to become more meaningful substrings:

          from          telebot          import          util          large_text          =          open          (          "large_text.txt"          ,          "rb"          )          .          read          ()          # Splits one string into multiple strings, with a maximum amount of `chars_per_string` (max. 4096)          # Splits past last '\n', '. ' or ' ' in exactly this priority.          # smart_split returns a list with the splitted text.          splitted_text          =          util          .          smart_split          (          large_text          ,          chars_per_string          =          3000          )          for          text          in          splitted_text          :          tb          .          send_message          (          chat_id          ,          text          )        

Controlling the amount of Threads used by TeleBot

The TeleBot constructor takes the following optional arguments:

  • threaded: True/False (default Truthful). A flag to bespeak whether TeleBot should execute message handlers on information technology's polling Thread.

The listener mechanism

As an alternative to the bulletin handlers, one can also register a part as a listener to TeleBot.

Observe: handlers won't disappear! Your message volition be processed both by handlers and listeners. Also, it's impossible to predict which will piece of work at get-go because of threading. If you utilize threaded=False, custom listeners will work before, later them handlers volition be called. Example:

          def          handle_messages          (          letters          ):          for          message          in          letters          :          # Do something with the message          bot          .          reply_to          (          message          ,          'Hullo'          )          bot          .          set_update_listener          (          handle_messages          )          bot          .          infinity_polling          ()        

Using web hooks

When using webhooks telegram sends i 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.

Logging

Y'all can utilize the Telebot module logger to log debug info about Telebot. Utilize 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.

          import          logging          logger          =          telebot          .          logger          telebot          .          logger          .          setLevel          (          logging          .          DEBUG          )          # Outputs debug messages to console.        

Proxy

For sync:

You can utilize proxy for request. apihelper.proxy object volition use past phone call requests proxies argument.

          from          telebot          import          apihelper          apihelper          .          proxy          =          {          'http'          :          'http://127.0.0.ane:3128'          }        

If you want to use socket5 proxy you demand install dependency pip install requests[socks] and make sure, that you have the latest version of gunicorn, PySocks, pyTelegramBotAPI, requests and urllib3.

          apihelper          .          proxy          =          {          'https'          :          'socks5://userproxy:countersign@proxy_address:port'          }        

For async:

          from          telebot          import          asyncio_helper          asyncio_helper          .          proxy          =          'http://127.0.0.1:3128'          #url        

Testing

You tin disable or alter the interaction with real Telegram server past using

          apihelper          .          CUSTOM_REQUEST_SENDER          =          your_handler        

parameter. You tin pass there your own part that volition be called instead of requests.request.

For instance:

          def          custom_sender          (          method          ,          url          ,          **          kwargs          ):          print          (          "custom_sender. method:                    {}          , url:                    {}          , params:                    {}          "          .          format          (          method          ,          url          ,          kwargs          .          get          (          "params"          )))          result          =          util          .          CustomRequestResponse          (          '{"ok":true,"result":{"message_id": 1, "appointment": 1, "chat": {"id": one, "blazon": "individual"}}}'          )          render          effect        

Then yous can apply API and proceed requests in your handler code.

          apihelper          .          CUSTOM_REQUEST_SENDER          =          custom_sender          tb          =          TeleBot          (          "test"          )          res          =          tb          .          send_message          (          123          ,          "Test"          )        

Issue will be:

custom_sender. method: mail, url: https://api.telegram.org/botololo/sendMessage, params: {'chat_id': '123', 'text': 'Examination'}

API conformance

  • ✔ Bot API vi.0
  • ✔ Bot API v.7
  • ✔ Bot API v.6
  • ✔ Bot API 5.5
  • ✔ Bot API five.four
  • ➕ Bot API five.iii - ChatMember* classes are full copies of ChatMember
  • ✔ Bot API 5.two
  • ✔ Bot API 5.ane
  • ✔ Bot API five.0
  • ✔ Bot API four.9
  • ✔ Bot API four.8
  • ✔ Bot API 4.7
  • ✔ Bot API 4.6
  • ➕ Bot API 4.five - No nested MessageEntities and Markdown2 support
  • ✔ Bot API iv.4
  • ✔ Bot API 4.3
  • ✔ Bot API four.2
  • ➕ Bot API 4.1 - No Passport back up
  • ➕ Bot API 4.0 - No Passport support

AsyncTeleBot

Asynchronous version of telebot

We accept a fully asynchronous version of TeleBot. This class is non controlled by threads. Asyncio tasks are created to execute all the stuff.

EchoBot

Echo Bot example on AsyncTeleBot:

          # This is a simple echo bot using the decorator mechanism.          # It echoes whatsoever incoming text messages.          from          telebot.async_telebot          import          AsyncTeleBot          import          asyncio          bot          =          AsyncTeleBot          (          'TOKEN'          )          # Handle '/get-go' and '/aid'          @bot          .          message_handler          (          commands          =          [          'help'          ,          'get-go'          ])          async          def          send_welcome          (          bulletin          ):          await          bot          .          reply_to          (          message          ,          """          \          Hi at that place, I am EchoBot.          I am here to repeat your kind words back to you. Just say anything nice and I'll say the exact same thing to yous!          \          """          )          # Handle all other letters with content_type 'text' (content_types defaults to ['text'])          @bot          .          message_handler          (          func          =          lambda          bulletin          :          True          )          async          def          echo_message          (          message          ):          await          bot          .          reply_to          (          message          ,          message          .          text          )          asyncio          .          run          (          bot          .          polling          ())        

As y'all can see here, keywords are await and async.

Why should I apply async?

Asynchronous tasks depend on processor performance. Many asynchronous tasks can run parallelly, while thread tasks volition block each other.

Differences in AsyncTeleBot

AsyncTeleBot is asynchronous. It uses aiohttp instead of requests module.

Examples

See more examples in our examples folder

F.A.Q.

How tin I distinguish a User and a GroupChat in message.conversation?

Telegram Bot API support new type Conversation for message.chat.

  • Check the blazon attribute in Chat object:
          if          bulletin          .          conversation          .          type          ==          "private"          :          # private chat message          if          message          .          chat          .          blazon          ==          "group"          :          # group chat message          if          message          .          conversation          .          blazon          ==          "supergroup"          :          # supergroup chat message          if          message          .          chat          .          blazon          ==          "channel"          :          # channel message        

How tin 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 final used session. Add apihelper.SESSION_TIME_TO_LIVE = 5 * 60 to your initialisation to force recreation after five minutes without any activity.

The Telegram Chat Group

Become aid. Discuss. Conversation.

  • Bring together the pyTelegramBotAPI Telegram Chat Group

Telegram Aqueduct

Join the News channel. Hither we volition post releases and updates.

More examples

  • Echo Bot
  • Deep Linking
  • next_step_handler Example

Code Template

Template is a ready folder that contains architecture of basic project. Here are some examples of template:

  • AsyncTeleBot template
  • TeleBot template

Bots using this API

  • SiteAlert bot (source) by ilteoood - Monitors websites and sends a notification on changes
  • TelegramLoggingBot past aRandomStranger
  • Telegram LMGTFY_bot by GabrielRF - Let me Google that for yous.
  • Telegram Proxy Bot by mrgigabyte
  • RadRetroRobot by Tronikart - Multifunctional Telegram Bot RadRetroRobot.
  • League of Legends bot (source) by i32ropie
  • NeoBot by @NeoRanger
  • ColorCodeBot (source) - Share code snippets as beautifully syntax-highlighted HTML and/or images.
  • ComedoresUGRbot (source) by alejandrocq - Telegram bot to check the bill of fare of Universidad de Granada dining hall.
  • proxybot - Unproblematic Proxy Bot for Telegram. by p-hash
  • DonantesMalagaBot - DonantesMalagaBot facilitates information to Malaga blood donors about the places where they can donate today or in the incoming days. Information technology besides records the date of the last donation so that it helps the donors to know when they can donate again. - by vfranch
  • DuttyBot by Dmytryi Striletskyi - Timetable for i university in Kiev.
  • wat-span by rmed - Send and receive letters to/from WhatsApp through Telegram
  • filmratingbot(source) past jcolladosp - Telegram bot using the Python API that gets films rating from IMDb and metacritic
  • Send2Kindlebot (source) by GabrielRF - Send to Kindle service.
  • RastreioBot (source) by GabrielRF - Bot used to runway packages on the Brazilian Mail Service.
  • Spbu4UBot(link) by EeOneDown - Bot with timetables for SPbU students.
  • SmartySBot(link) past 0xVK - Telegram timetable bot, for Zhytomyr Ivan Franko State University students.
  • LearnIt(link) - A Telegram Bot created to help people to memorize other languages' vocabulary.
  • Bot-Telegram-Shodan by rubenleon
  • VigoBusTelegramBot (GitHub) - Bot that provides buses coming to a certain stop and their remaining time for the urban center of Vigo (Galicia - Spain)
  • kaishnik-bot (source) past airatk - bot which shows all the necessary information to KNTRU-KAI students.
  • Robbie (source) past @FacuM - Back up Telegram bot for developers and maintainers.
  • AsadovBot (source) by @DesExcile - Сatalog of poems by Eduard Asadov.
  • thesaurus_com_bot (source) by @LeoSvalov - words and synonyms from dictionary.com and thesaurus.com in the telegram.
  • InfoBot (source) by @irevenko - An all-circular bot that displays some statistics (conditions, time, crypto etc...)
  • FoodBot (source) by @Fliego - a simple bot for nutrient ordering
  • Sporty (source) by @0xnu - Telegram bot for displaying the latest news, sports schedules and injury updates.
  • JoinGroup Silencer Bot (source) by @zeph1997 - A Telegram Bot to remove "join grouping" and "removed from group" notifications.
  • TasksListsBot (source) past @Pablo-Davila - A (tasks) lists manager bot for Telegram.
  • MyElizaPsychologistBot (source) by @Pablo-Davila - An implementation of the famous Eliza psychologist chatbot.
  • Frcstbot (source) past Mrsqd. A Telegram bot that volition always be happy to show you the weather forecast.
  • MineGramBot by ModischFabrications. This bot can start, stop and monitor a minecraft server.
  • Tabletop DiceBot by dexpiper. This bot can roll multiple dices for RPG-like games, add positive and negative modifiers and show brusk descriptions to the rolls.
  • BarnameKon by Anvaari. This Bot make "Add to google calendar" link for your events. It give information virtually event and return link. It work for Jalali calendar and in Tehran Time. Source code
  • Translator bot by Areeg Fahad. This bot tin can be used to translate texts.
  • Digital Cryptocurrency bot past Areeg Fahad. With this bot, you tin now monitor the prices of more than 12 digital Cryptocurrency.
  • Anti-Tracking Bot by Leon Heess (source). Ship whatsoever link, and the bot tries its best to remove all tracking from the link you sent.
  • Developer Bot by Vishal Singh (source code) This telegram bot tin do tasks like GitHub search & clone,provide c++ learning resource ,Stackoverflow search, Codeforces(profile visualizer,random problems)
  • oneIPO bot by Aadithya & Amol Soans This Telegram bot provides live updates , data and documents on current and upcoming IPOs(Initial Public Offerings)
  • CoronaGraphsBot (source) by TrevorWinstral - Gets live COVID Country information, plots information technology, and briefs the user
  • ETHLectureBot (source) by TrevorWinstral - Notifies ETH students when their lectures have been uploaded
  • Vlun Finder Bot by Resinprotein2333. This bot tin can assistance y'all to find The information of CVE vulnerabilities.
  • ETHGasFeeTrackerBot (Source by DevAdvik - Go Live Ethereum Gas Fees in GWEI
  • Google Sheet Bot by JoachimStanislaus. This bot can help you to track your expenses by uploading your bot entries to your google sheet.
  • GrandQuiz Bot by Carlosma7. This bot is a trivia game that allows yous to play with people from different ages. This project addresses the utilize of a system through chatbots to carry out a social and intergenerational game equally an culling to traditional game development.
  • Diccionario de la RAE (source) This bot lets you detect difinitions of words in Spanish using RAE'due south dictionary. It features direct message and inline search.
  • remoteTelegramShell by EnriqueMoran. Control your LinuxOS computer through Telegram.
  • Pyfram-telegram-bot Query wolframalpha.com and brand apply of its API through Telegram.
  • TranslateThisVideoBot This Bot can empathize spoken text in videos and translate it to English language

Desire to accept your bot listed hither? Just make a pull asking. Simply bots with public source code are accepted.

Source: https://pypi.org/project/pyTelegramBotAPI/

0 Response to "How To Set Up Logger Bot"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel