Package: tgbotapi
tgbotapiThe UltimateTelegram Bot APIFrameworkBased OnpyTelegramBotAPIHow to UsePrerequisitesPresumed you have obtained a bot token with@BotFatherA Simple BotThe Bot class encapsulates all API calls in a single class, It provides functions such assend_xyz(send_message,send_documentetc.)
and several ways to listen for incoming messages.Create a file calledecho_bot.py. Then, open the file and create an instance of the Bot class.importtgbotapi# Note: Make sure to actually replace TOKEN with your own API tokenbot=tgbotapi.Bot(access_token="TOKEN")# After that declaration, we need to register some so-called update handler.# update_type define filters which can be a message, If a message passes the filter,# the decorated function is called and the incoming message is passed as an argument.# Let's define an update handler which handles incoming `/start` and `/help` bot_command.@bot.update_handler(update_type='message',bot_command=['/start','/help'])# A function which is decorated by an update handler can have an arbitrary name,# however, it must have only one parameter (the msg)defsend_welcome(msg):bot.send_message(chat_id=msg.chat.uid,text="Howdy, how are you doing?",parse_mode=None,entities=None,disable_web_page_preview=False,disable_notification=False,reply_to_message_id=msg.message_id,allow_sending_without_reply=True,reply_markup=None)# 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 text messages to be handled by this function,# so it simply always return True.@bot.update_handler(update_type='message',func=lambdamessage:message.text)defecho_all(msg):bot.send_message(chat_id=msg.chat.uid,text=msg.text,parse_mode=None,entities=None,disable_web_page_preview=False,disable_notification=False,reply_to_message_id=None,allow_sending_without_reply=True,reply_markup=None)# Finally, we call long polling functionbot.polling()Alright, that's it! Our source file, To start the bot, simply open up a terminal and enterpython echo_bot.pyto run
the bot!
Test it by sending commands ('/start' and '/help') and arbitrary text messages.ChangeLogversion 5.7Added support for Video Stickers. Added the field is_video to the classes Sticker and StickerSet.Added the parameter webm_sticker to the methods createNewStickerSet and addStickerToSet.FixesNo Issues until NowFramework ExplanationAhandleris a function that is decorated with theupdate_handlerdecorator of a Bot instance, handlers consist of
one or multiple filters, Each filter match returns True for a certain message in order for an update handler to become
eligible.Here are some examples of using the filters and handlers:update_typefiltersreturn typesfunction argumentmessagechat_type,bot_command,regexp,funcMessagemessagemessage_editedchat_type,bot_command,regexp,funcMessagemessagechannel_postchat_type,bot_command,regexp,funcMessagemessageedited_channel_postchat_type,bot_command,regexp,funcMessagemessageinline_queryregexp,funcInlineQueryquerychosen_inline_queryregexp,funcChosenInlineQueryquerycallback_queryregexp,funcCallbackQueryqueryshipping_queryregexp,funcShippingQueryqueryper_checkout_queryregexp,funcPreCheckoutQueryquerypollregexp,funcPollpollpoll_answerregexp,funcPollAnswerpollmy_chat_memberregexp,funcChatMemberUpdatedmemberchat_memberregexp,funcChatMemberUpdatedmemberchat_join_requestregexp,funcChatJoinRequestmemberA message handler is declared in the following way:importtgbotapibot=tgbotapi.Bot(access_token="TOKEN")@bot.update_handler(update_type='message')# filtersdeffunction_name(message):bot.send_message(chat_id=message.chat.uid,text="This is a message handler")function_nameis not bound to any restrictions. Any function name is permitted with update handlers. The function must
accept at most one argument, which will be the message that the function must handle.filtersis a list of keyword arguments. A filter is declared in the following manner:name=argument. One handler may
have multiple filters.Bot supports the following filters:nameargument(s)Conditionupdate_typelist of strings or string (default['message'])Trueifupdate.messageis present.chat_typelist of strings or string (private,channel,group,supergroup)Trueifmessage.chat.ttypeinchat_typebot_commandlist of strings or string (/start)Trueifmessage.entities[0].bot_commandandmessage.textstarts with a commandregexa regular expression as a stringTrueifre.search(regexp_arg)returnsTruefunca function (lambda or function reference)Trueif the lambda or function reference returnsTrueLoggingYou can use the tgbotapi module logger to log debug info about Bot.It is possible to add custom logging Handlers to the logger,
Refer to thePython loggingfor more info.importloggingfromtgbotapiimportloggerlogger.setLevel(logging.DEBUG)# Outputs debug messages to console.How to ContributeYou must followContributingGuidelines.We are committed to providing a friendly community, for more experience
readCode Of Conduct.How to CommunicateYou're welcome to drop in and ask questions, discuss bugs and such,
CheckCommunicationMethods.Frequently Asked QuestionsHow can I distinguish a User and a GroupChat in Message Chat?Telegram Bot API supports type Chat for message Check thettypeattribute inChatobjectAttributionThese Documents are adapted
forMA24th Open Source Software,For more informationContactwith any additional questions or comments.