pytelegrambotapi
การใช้ Python ที่เรียบง่าย แต่ขยายได้สำหรับ Telegram Bot API
ทั้งแบบซิงโครนัสและแบบอะซิงโครนัส
รองรับ Bot API เวอร์ชัน: 7.1!
API นี้ได้รับการทดสอบด้วย Python 3.8-3.12 และ Pypy 3 มีสองวิธีในการติดตั้งไลบรารี:
$ pip install pyTelegramBotAPI
$ pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git
โดยทั่วไปขอแนะนำให้ใช้ตัวเลือกแรก
ในขณะที่ API พร้อมใช้งาน แต่ก็ยังอยู่ระหว่างการพัฒนาและมีการอัปเดตเป็นประจำอย่าลืมอัปเดตเป็นประจำโดยโทร
pip install pytelegrambotapi --upgrade
สันนิษฐานว่าคุณได้รับโทเค็น API กับ @botfather เราจะเรียก TOKEN โทเค็นนี้ นอกจากนี้คุณมีความรู้พื้นฐานเกี่ยวกับภาษาการเขียนโปรแกรม Python และที่สำคัญกว่า Telegram Bot API
คลาส telebot (กำหนดไว้ใน __init__.py) ห่อหุ้มการโทร API ทั้งหมดในคลาสเดียว มันมีฟังก์ชั่นเช่น send_xyz ( send_message , send_document ฯลฯ ) และหลายวิธีในการฟังข้อความที่เข้ามา
สร้างไฟล์ที่เรียกว่า echo_bot.py จากนั้นเปิดไฟล์และสร้างอินสแตนซ์ของคลาส Telebot
import telebot
bot = telebot . TeleBot ( "TOKEN" , parse_mode = None ) # You can set parse_mode by default. HTML or MARKDOWNหมายเหตุ: ตรวจสอบให้แน่ใจว่าได้แทนที่โทเค็นด้วยโทเค็น API ของคุณเอง
หลังจากการประกาศนั้นเราต้องลงทะเบียนตัวจัดการข้อความที่เรียกว่า ตัวจัดการข้อความกำหนดตัวกรองที่ข้อความต้องผ่าน หากข้อความผ่านตัวกรองฟังก์ชั่นการตกแต่งจะถูกเรียกและข้อความที่เข้ามาจะถูกส่งผ่านเป็นอาร์กิวเมนต์
มากำหนดตัวจัดการข้อความที่จัดการคำสั่งขาเข้า /start และ /help
@ bot . message_handler ( commands = [ 'start' , 'help' ])
def send_welcome ( message ):
bot . reply_to ( message , "Howdy, how are you doing?" )ฟังก์ชั่นที่ตกแต่งด้วยตัวจัดการข้อความ สามารถมีชื่อโดยพลการอย่างไรก็ตามมันจะต้องมีพารามิเตอร์เดียวเท่านั้น (ข้อความ)
มาเพิ่มตัวจัดการอื่นกันเถอะ:
@ bot . message_handler ( func = lambda m : True )
def echo_all ( message ):
bot . reply_to ( message , message . text )อันนี้สะท้อนข้อความที่เข้ามาทั้งหมดกลับไปยังผู้ส่ง มันใช้ฟังก์ชั่นแลมบ์ดาเพื่อทดสอบข้อความ หากแลมบ์ดาส่งคืนจริงข้อความจะถูกจัดการโดยฟังก์ชั่นการตกแต่ง เนื่องจากเราต้องการให้ข้อความทั้งหมดได้รับการจัดการโดยฟังก์ชั่นนี้เราจึงกลับมาเป็นจริงเสมอ
หมายเหตุ: ตัวจัดการทั้งหมดได้รับการทดสอบตามลำดับที่พวกเขาประกาศ
ตอนนี้เรามีบอทพื้นฐานซึ่งตอบข้อความแบบคงที่เป็นคำสั่ง "/เริ่ม" และ "/help" และเสียงที่สะท้อนข้อความที่เหลือ ในการเริ่มต้นบอทให้เพิ่มไฟล์ต้นฉบับของเราต่อไปนี้:
bot . infinity_polling ()เอาล่ะมันแค่ไหน! ตอนนี้ไฟล์ต้นฉบับของเรามีลักษณะเช่นนี้:
import telebot
bot = telebot . TeleBot ( "YOUR_BOT_TOKEN" )
@ bot . message_handler ( commands = [ 'start' , 'help' ])
def send_welcome ( message ):
bot . reply_to ( message , "Howdy, how are you doing?" )
@ bot . message_handler ( func = lambda message : True )
def echo_all ( message ):
bot . reply_to ( message , message . text )
bot . infinity_polling () ในการเริ่มต้นบอทเพียงเปิดเทอร์มินัลแล้วป้อน python echo_bot.py เพื่อเรียกใช้บอท! ทดสอบโดยการส่งคำสั่ง ('/start' และ '/help') และข้อความโดยพลการ
ทุกประเภทถูกกำหนดเป็นประเภท py พวกเขาทั้งหมดสอดคล้องกับคำจำกัดความของ Telegram API อย่างสมบูรณ์ยกเว้นข้อความ from ฟิลด์ซึ่งถูกเปลี่ยนชื่อเป็น from_user (เพราะ from Python ที่สงวนไว้) ดังนั้นคุณลักษณะเช่น message_id สามารถเข้าถึงได้โดยตรงด้วย message.message_id โปรดทราบว่า message.chat สามารถเป็นอินสแตนซ์ของ User หรือ GroupChat ได้ (ดูว่าฉันจะแยกแยะผู้ใช้และ GroupChat ใน message.chat ได้อย่างไร)
วัตถุข้อความยังมีแอตทริบิวต์ content_type ซึ่งกำหนดประเภทของข้อความ content_type สามารถเป็นหนึ่งในสตริงต่อไป delete_chat_photo : text , audio , document , ภาพ animation , game , photo , sticker , video , video_note , voice , location , contact , venue dice new_chat_title left_chat_member new_chat_members new_chat_photo , group_chat_created , supergroup_chat_created channel_chat_created , migrate_to_chat_id , migrate_from_chat_id , pinned_message , invoice video_chat_participants_invited video_chat_started successful_payment , connected_website , poll video_chat_scheduled passport_data , proximity_alert_triggered , video_chat_ended web_app_data , message_auto_delete_timer_changed , forum_topic_created user_shared forum_topic_closed chat_shared forum_topic_reopened story forum_topic_edited , general_forum_topic_hidden write_access_allowed general_forum_topic_unhidden
คุณสามารถใช้บางประเภทในฟังก์ชั่นเดียว ตัวอย่าง:
content_types=["text", "sticker", "pinned_message", "photo", "audio"]
วิธี API ทั้งหมดอยู่ในคลาส Telebot พวกเขาถูกเปลี่ยนชื่อให้ทำตามอนุสัญญาการตั้งชื่อ Python ทั่วไป เช่น getMe ถูกเปลี่ยนชื่อเป็น get_me และ sendMessage เป็น send_message
ด้านล่างนี้เป็นกรณีการใช้งานทั่วไปของ API
ตัวจัดการข้อความเป็นฟังก์ชั่นที่ตกแต่งด้วย message_handler Decorator ของอินสแตนซ์ telebot ตัวจัดการข้อความประกอบด้วยตัวกรองหนึ่งหรือหลายตัว ตัวกรองแต่ละตัวจะต้องส่งคืนจริงสำหรับข้อความบางข้อความเพื่อให้ตัวจัดการข้อความมีสิทธิ์จัดการข้อความนั้น มีการประกาศตัวจัดการข้อความด้วยวิธีต่อไปนี้ (ให้ bot เป็นตัวอย่างของ telebot):
@ bot . message_handler ( filters )
def function_name ( message ):
bot . reply_to ( message , "This is a message handler" ) function_name ไม่ผูกพันกับข้อ จำกัด ใด ๆ ชื่อฟังก์ชั่นใด ๆ ที่ได้รับอนุญาตด้วยตัวจัดการข้อความ ฟังก์ชั่นจะต้องยอมรับอาร์กิวเมนต์ส่วนใหญ่หนึ่งข้อซึ่งจะเป็นข้อความที่ฟังก์ชั่นต้องจัดการ filters เป็นรายการของอาร์กิวเมนต์คำหลัก ตัวกรองถูกประกาศในลักษณะต่อไปนี้: name=argument ตัวจัดการหนึ่งคนอาจมีตัวกรองหลายตัว Telebot รองรับตัวกรองต่อไปนี้:
| ชื่อ | อาร์กิวเมนต์ | เงื่อนไข |
|---|---|---|
| content_types | รายการสตริง (ค่าเริ่มต้น ['text'] ) | True ถ้า message.content_type อยู่ในรายการสตริง |
| regexp | นิพจน์ทั่วไปเป็นสตริง | True ถ้า re.search(regexp_arg) ส่งคืน True และ message.content_type == 'text' (ดู Python Expressions) |
| คำสั่ง | รายการสตริง | True ถ้า message.content_type == 'text' และ message.text เริ่มต้นด้วยคำสั่งที่อยู่ในรายการสตริง |
| chat_types | รายการประเภทแชท | True ถ้า message.chat.type ในตัวกรองของคุณ |
| func | ฟังก์ชัน (Lambda หรือ Function Reference) | True ถ้าการอ้างอิงแลมบ์ดาหรือฟังก์ชั่นส่งคืน True |
นี่คือตัวอย่างของการใช้ตัวกรองและตัวจัดการข้อความ:
import telebot
bot = telebot . TeleBot ( "TOKEN" )
# Handles all text messages that contains the commands '/start' or '/help'.
@ bot . message_handler ( commands = [ 'start' , 'help' ])
def handle_start_help ( message ):
pass
# Handles all sent documents and audio files
@ bot . message_handler ( content_types = [ 'document' , 'audio' ])
def handle_docs_audio ( message ):
pass
# Handles all text messages that match the regular expression
@ bot . message_handler ( regexp = "SOME_REGEXP" )
def handle_message ( message ):
pass
# Handles all messages for which the lambda returns True
@ bot . message_handler ( func = lambda message : message . document . mime_type == 'text/plain' , content_types = [ 'document' ])
def handle_text_doc ( message ):
pass
# Which could also be defined as:
def test_message ( message ):
return message . document . 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 called if the message starts with '/hello' OR is some emoji
@ bot . message_handler ( commands = [ 'hello' ])
@ bot . message_handler ( func = lambda msg : msg . text . encode ( "utf-8" ) == SOME_FANCY_EMOJI )
def send_something ( message ):
passสำคัญ: ตัวจัดการทั้งหมดได้รับการทดสอบตามลำดับที่พวกเขาได้รับการประกาศ
จัดการข้อความที่แก้ไข @bot.edited_message_handler(filters) # <- passes a Message type object to your function
จัดการข้อความโพสต์ช่องสัญญาณ @bot.channel_post_handler(filters) # <- passes a Message type object to your function
จัดการข้อความโพสต์ช่องสัญญาณที่แก้ไข @bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function
จัดการคำค้นหาการโทรกลับ
@ bot . callback_query_handler ( func = lambda call : True )
def test_callback ( call ): # <- passes a CallbackQuery type object to your function
logger . info ( call ) จัดการข้อสงสัยการจัดส่ง @bot.shipping_query_handler() # <- passes a ShippingQuery type object to your function
จัดการการสอบถามล่วงหน้าตรวจสอบ @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function
จัดการการอัปเดตแบบสำรวจความคิดเห็น @bot.poll_handler() # <- passes a Poll type object to your function
จัดการคำตอบแบบสำรวจความคิดเห็น @bot.poll_answer_handler() # <- passes a PollAnswer type object to your function
จัดการการอัปเดตสถานะสมาชิกของบอทในแชท @bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function
จัดการการอัปเดตสถานะของสมาชิกแชทในแชท @bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function หมายเหตุ: การอัปเดต "chat_member" ไม่ได้ร้องขอตามค่าเริ่มต้น หากคุณต้องการอนุญาตให้มีการอัปเดตทุกประเภทให้ตั้ง allowed_updates ใน bot.polling() / bot.infinity_polling() เป็น util.update_types
จัดการการแชทเข้าร่วมคำขอโดยใช้: @bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function
ข้อมูลเพิ่มเติมเกี่ยวกับโหมดอินไลน์
ตอนนี้คุณสามารถใช้ inline_handler เพื่อรับแบบสอบถามแบบอินไลน์ใน Telebot
@ bot . inline_handler ( lambda query : query . query == 'text' )
def query_text ( inline_query ):
# Query message is text ใช้ chosen_inline_handler เพื่อรับ chosen_inline_result ใน telebot อย่าลืมเพิ่มคำสั่ง /setInlineFeedback สำหรับ @botfather
ข้อมูลเพิ่มเติม: การรวบรวมฟีดแบ็ก
@ bot . chosen_inline_handler ( func = lambda chosen_inline_result : True )
def test_chosen ( chosen_inline_result ):
# Process all chosen_inline_result. @ bot . inline_handler ( lambda query : query . query == 'text' )
def query_text ( inline_query ):
try :
r = types . InlineQueryResultArticle ( '1' , 'Result' , types . InputTextMessageContent ( 'Result message.' ))
r2 = types . InlineQueryResultArticle ( '2' , 'Result2' , types . InputTextMessageContent ( 'Result message2.' ))
bot . answer_inline_query ( inline_query . id , [ r , r2 ])
except Exception as e :
print ( e ) ตัวจัดการมิดเดิลแวร์เป็นฟังก์ชั่นที่อนุญาตให้คุณแก้ไขคำขอหรือบริบทของบอทเมื่อพวกเขาผ่านโทรเลขไปยังบอท คุณสามารถจินตนาการถึงมิดเดิลแวร์เป็นห่วงโซ่การเชื่อมต่อตรรกะที่จัดการก่อนที่จะดำเนินการตัวจัดการอื่น ๆ การประมวลผลมิดเดิลแวร์จะถูกปิดใช้งานโดยค่าเริ่มต้นเปิดใช้งานโดยการตั้งค่า apihelper.ENABLE_MIDDLEWARE = True
apihelper . ENABLE_MIDDLEWARE = True
@ bot . middleware_handler ( update_types = [ 'message' ])
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 = [ 'start' ])
def start ( message ):
# the message is already modified when it reaches message handler
assert message . another_text == message . text + ':changed'มีตัวอย่างอื่น ๆ ที่ใช้ตัวจัดการมิดเดิลแวร์ในไดเรกทอรีตัวอย่าง/มิดเดิลแวร์
มี Middlewares ในชั้นเรียน มิดเดิลแวร์ที่ใช้คลาสพื้นฐานมีลักษณะเช่นนี้:
class Middleware ( BaseMiddleware ):
def __init__ ( self ):
self . update_types = [ 'message' ]
def pre_process ( self , message , data ):
data [ 'foo' ] = 'Hello' # just for example
# we edited the data. now, this data is passed to handler.
# return SkipHandler() -> this will skip handler
# return CancelUpdate() -> this will cancel update
def post_process ( self , message , data , exception = None ):
print ( data [ 'foo' ])
if exception : # check for exception
print ( exception )มิดเดิลแวร์ที่ใช้คลาสควรมีสองฟังก์ชั่น: โพสต์และกระบวนการก่อน ดังนั้นอย่างที่คุณเห็น Middlewares ในชั้นเรียนจะทำงานก่อนและหลังการดำเนินการของ Handler สำหรับข้อมูลเพิ่มเติมลองดูตัวอย่าง
นอกจากนี้คุณสามารถใช้ตัวกรองที่กำหนดเองในตัว หรือคุณสามารถสร้างตัวกรองของคุณเอง
ตัวอย่างของตัวกรองที่กำหนดเองเรามีตัวอย่างเกี่ยวกับพวกเขา ตรวจสอบลิงก์นี้: คุณสามารถตรวจสอบตัวกรองในตัวในตัวอย่างซอร์สโค้ดตัวอย่างของการกรองโดยตัวอย่าง ID ของการกรองตามข้อความหากคุณต้องการเพิ่มตัวกรองในตัวคุณสามารถเพิ่มได้ในไฟล์ custom_filters.py นี่คือตัวอย่างของการสร้างคลาสตัวกรอง:
class IsAdmin ( telebot . custom_filters . SimpleCustomFilter ):
# Class will check whether the user is admin or creator in group or not
key = 'is_chat_admin'
@ staticmethod
def check ( message : telebot . types . Message ):
return bot . get_chat_member ( message . chat . id , message . from_user . id ). status in [ 'administrator' , 'creator' ]
# To register filter, you need to use method add_custom_filter.
bot . add_custom_filter ( IsAdmin ())
# Now, you can use it in handler.
@ bot . message_handler ( is_chat_admin = True )
def admin_of_group ( message ):
bot . send_message ( message . chat . id , 'You are admin of this group!' ) 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 messages.
# - interval: int (default 0) - The interval between polling requests
# - timeout: integer (default 20) - Timeout in seconds for long polling.
# - allowed_updates: List of Strings (default None) - List of update types to request
tb . infinity_polling ( interval = 0 , timeout = 20 )
# getMe
user = tb . get_me ()
# setWebhook
tb . set_webhook ( url = "http://example.com" , certificate = open ( '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 as an argument, can also take a file_id instead of a file.
# sendPhoto
photo = open ( '/tmp/photo.png' , 'rb' )
tb . send_photo ( chat_id , photo )
tb . send_photo ( chat_id , "FILEID" )
# sendAudio
audio = open ( '/tmp/audio.mp3' , 'rb' )
tb . send_audio ( chat_id , audio )
tb . send_audio ( chat_id , "FILEID" )
## sendAudio with duration, performer and title.
tb . send_audio ( CHAT_ID , file_data , 1 , 'eternnoir' , 'pyTelegram' )
# sendVoice
voice = open ( '/tmp/voice.ogg' , 'rb' )
tb . send_voice ( chat_id , voice )
tb . send_voice ( chat_id , "FILEID" )
# sendDocument
doc = open ( '/tmp/file.txt' , 'rb' )
tb . send_document ( chat_id , doc )
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 ( '/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 can 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 ))
ฟังก์ชั่น send_xyz ทั้งหมดของ telebot ใช้อาร์กิวเมนต์ reply_markup เสริม อาร์กิวเมนต์นี้จะต้องเป็นอินสแตนซ์ของ ReplyKeyboardMarkup , ReplyKeyboardRemove หรือ ForceReply ซึ่งกำหนดไว้ในประเภท Py
from telebot import types
# Using the ReplyKeyboardMarkup class
# It's constructor can take the following optional arguments:
# - resize_keyboard: True/False (default False)
# - one_time_keyboard: True/False (default False)
# - selective: True/False (default False)
# - row_width: integer (default 3)
# row_width is used in combination with the add() function.
# It defines how many buttons are fit on each row before continuing on the next row.
markup = types . ReplyKeyboardMarkup ( row_width = 2 )
itembtn1 = types . KeyboardButton ( 'a' )
itembtn2 = types . KeyboardButton ( 'v' )
itembtn3 = types . KeyboardButton ( 'd' )
markup . add ( itembtn1 , itembtn2 , itembtn3 )
tb . send_message ( chat_id , "Choose one letter:" , reply_markup = markup )
# or add KeyboardButton one 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 )ตัวอย่างสุดท้ายให้ผลลัพธ์นี้:
# ReplyKeyboardRemove: hides a previously sent ReplyKeyboardMarkup
# Takes an optional selective argument (True/False, default False)
markup = types . ReplyKeyboardRemove ( selective = False )
tb . send_message ( chat_id , message , reply_markup = markup ) # ForceReply: forces a user to reply to a message
# Takes an optional selective argument (True/False, default False)
markup = types . ForceReply ( selective = False )
tb . send_message ( chat_id , "Send me another word:" , reply_markup = markup )โดยเฉพาะ:
วัตถุนี้แสดงถึงเอนทิตีพิเศษหนึ่งรายการในข้อความ ตัวอย่างเช่นแฮชแท็กชื่อผู้ใช้ url ฯลฯ แอตทริบิวต์:
typeurloffsetlengthuser นี่คือตัวอย่าง: message.entities[num].<attribute>
num คือหมายเลขเอนทิตีหรือลำดับของเอนทิตีในการตอบกลับสำหรับหากกรณีมีหลายเอนทิตีในการตอบกลับ/ข้อความ
message.entities ส่งคืนรายการวัตถุเอนทิตี
message.entities[0].type จะให้ประเภทของเอนทิตีแรก
แนะนำ Bot API สำหรับรายละเอียดเพิ่มเติม
ตั้งแต่เวอร์ชัน 5.0 ของ BOT API คุณมีความเป็นไปได้ที่จะเรียกใช้เซิร์ฟเวอร์ Bot API ในพื้นที่ของคุณเอง PyTelegrambotapi ยังรองรับคุณสมบัตินี้
from telebot import apihelper
apihelper . API_URL = "http://localhost:4200/bot{0}/{1}" สำคัญ: เช่นที่อธิบายไว้ที่นี่คุณต้องออกจากระบบบอทของคุณจากเซิร์ฟเวอร์โทรเลขก่อนที่จะเปลี่ยนไปใช้เซิร์ฟเวอร์ API ในพื้นที่ของคุณ ใน pytelegrambotapi ใช้ bot.log_out()
หมายเหตุ: 4200 เป็นพอร์ตตัวอย่าง
ใหม่: มีการใช้ telebot แบบอะซิงโครนัส ในการเปิดใช้งานพฤติกรรมนี้ให้สร้างอินสแตนซ์ของ AsyncTelebot แทน telebot
tb = telebot . AsyncTeleBot ( "TOKEN" )ตอนนี้ทุกฟังก์ชั่นที่เรียกว่า Telegram API จะดำเนินการในงานอะซิงโครนัสแยกต่างหาก การใช้ AsyncTelebot ช่วยให้คุณทำสิ่งต่อไปนี้:
import telebot
tb = telebot . AsyncTeleBot ( "TOKEN" )
@ tb . message_handler ( commands = [ 'start' ])
async def start_message ( message ):
await bot . send_message ( message . chat . id , 'Hello!' )ดูตัวอย่างเพิ่มเติม
บางครั้งคุณต้องส่งข้อความที่เกิน 5,000 อักขระ TELEGRAM API ไม่สามารถจัดการกับอักขระจำนวนมากในคำขอเดียวดังนั้นเราจำเป็นต้องแยกข้อความเป็นทวีคูณ นี่คือวิธีการทำโดยใช้ 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 ) หรือคุณสามารถใช้ฟังก์ชั่น smart_split ใหม่เพื่อรับย่อยที่มีความหมายมากขึ้น:
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 by 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 )ตัวสร้าง Telebot ใช้อาร์กิวเมนต์เสริมต่อไปนี้:
เป็นทางเลือกแทนตัวจัดการข้อความหนึ่งสามารถลงทะเบียนฟังก์ชั่นเป็นผู้ฟัง telebot
ข้อสังเกต: ตัวจัดการจะไม่หายไป! ข้อความของคุณจะถูกประมวลผลทั้งโดยตัวจัดการและผู้ฟัง นอกจากนี้ยังเป็นไปไม่ได้ที่จะทำนายว่าจะทำงานได้ในตอนแรกเนื่องจากการทำเกลียว หากคุณใช้ Threaded = False ผู้ฟังที่กำหนดเองจะทำงานก่อนหน้านี้หลังจากที่พวกเขาจะถูกเรียกใช้ ตัวอย่าง:
def handle_messages ( messages ):
for message in messages :
# Do something with the message
bot . reply_to ( message , 'Hi' )
bot . set_update_listener ( handle_messages )
bot . infinity_polling ()เมื่อใช้ WebHooks Telegram ส่งการอัปเดตหนึ่งครั้งต่อการโทรสำหรับการประมวลผลคุณควรเรียก Process_New_Messages ([update.message]) เมื่อคุณได้รับ
มีตัวอย่างบางส่วนที่ใช้ webhooks ในไดเรกทอรีตัวอย่าง/webhook_examples
คุณสามารถใช้ตัวบันทึกโมดูล Telebot เพื่อบันทึกข้อมูลการดีบักเกี่ยวกับ telebot ใช้ telebot.logger เพื่อรับเครื่องบันทึกของโมดูล telebot เป็นไปได้ที่จะเพิ่มตัวจัดการการบันทึกที่กำหนดเองลงในตัวบันทึก อ้างถึงหน้าโมดูลการบันทึก Python สำหรับข้อมูลเพิ่มเติม
import logging
logger = telebot . logger
telebot . logger . setLevel ( logging . DEBUG ) # Outputs debug messages to console.สำหรับการซิงค์:
คุณสามารถใช้พร็อกซีเพื่อขอ apihelper.proxy Object จะใช้โดยอาร์กิวเมนต์การเรียก requests พร็อกซี
from telebot import apihelper
apihelper . proxy = { 'http' : 'http://127.0.0.1:3128' } หากคุณต้องการใช้ Socket5 Proxy คุณต้องติดตั้ง pip install requests[socks] และตรวจสอบให้แน่ใจว่าคุณมี gunicorn , PySocks , pyTelegramBotAPI , requests และ urllib3 รุ่นล่าสุด
apihelper . proxy = { 'https' : 'socks5://userproxy:password@proxy_address:port' }สำหรับ async:
from telebot import asyncio_helper
asyncio_helper . proxy = 'http://127.0.0.1:3128' #urlคุณสามารถปิดการใช้งานหรือเปลี่ยนการโต้ตอบกับเซิร์ฟเวอร์โทรเลขจริงได้โดยใช้
apihelper . CUSTOM_REQUEST_SENDER = your_handlerพารามิเตอร์. คุณสามารถผ่านฟังก์ชั่นของคุณเองที่จะถูกเรียกแทน คำขอ
ตัวอย่างเช่น:
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, "date": 1, "chat": {"id": 1, "type": "private"}}}' )
return resultจากนั้นคุณสามารถใช้ API และดำเนินการตามคำขอในรหัสตัวจัดการของคุณ
apihelper . CUSTOM_REQUEST_SENDER = custom_sender
tb = TeleBot ( "test" )
res = tb . send_message ( 123 , "Test" )ผลลัพธ์จะเป็น:
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params: {'chat_id': '123', 'text': 'Test'}
เรามี Telebot รุ่นอะซิงโครนัสอย่างสมบูรณ์ คลาสนี้ไม่ได้ควบคุมโดยเธรด งาน Asyncio ถูกสร้างขึ้นเพื่อดำเนินการทั้งหมด
Echo Bot ตัวอย่างบน asyncTelebot:
# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.
from telebot . async_telebot import AsyncTeleBot
import asyncio
bot = AsyncTeleBot ( 'TOKEN' )
# Handle '/start' and '/help'
@ bot . message_handler ( commands = [ 'help' , 'start' ])
async def send_welcome ( message ):
await bot . reply_to ( message , """
Hi there, I am EchoBot.
I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!
""" )
# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
@ bot . message_handler ( func = lambda message : True )
async def echo_message ( message ):
await bot . reply_to ( message , message . text )
asyncio . run ( bot . polling ())อย่างที่คุณเห็นที่นี่คำหลักกำลังรอและ async
งานอะซิงโครนัสขึ้นอยู่กับประสิทธิภาพของโปรเซสเซอร์ งานอะซิงโครนัสจำนวนมากสามารถทำงานได้อย่างขนานในขณะที่งานเธรดจะปิดกั้นซึ่งกันและกัน
AsyncTelebot เป็นแบบอะซิงโครนัส มันใช้ AIOHTTP แทนโมดูลคำขอ
ดูตัวอย่างเพิ่มเติมในโฟลเดอร์ตัวอย่างของเรา
Telegram Bot API สนับสนุนการแชทประเภทใหม่สำหรับ message.chat
type แอตทริบิวต์ในวัตถุ Chat : if message . chat . type == "private" :
# private chat message
if message . chat . type == "group" :
# group chat message
if message . chat . type == "supergroup" :
# supergroup chat message
if message . chat . type == "channel" :
# channel message อินสแตนซ์ BOT ที่ไม่ได้ใช้งานเป็นเวลานานอาจถูกปฏิเสธโดยเซิร์ฟเวอร์เมื่อส่งข้อความเนื่องจากการหมดเวลาของเซสชันที่ใช้ครั้งล่าสุด เพิ่ม apihelper.SESSION_TIME_TO_LIVE = 5 * 60 เพื่อเริ่มต้นการพักผ่อนหย่อนใจหลังจาก 5 นาทีโดยไม่มีกิจกรรมใด ๆ
รับความช่วยเหลือ หารือ. แชท.
เข้าร่วมช่องข่าว ที่นี่เราจะโพสต์เผยแพร่และอัปเดต
เทมเพลตเป็นโฟลเดอร์พร้อมที่มีสถาปัตยกรรมของโครงการพื้นฐาน นี่คือตัวอย่างของเทมเพลต:
ต้องการให้บอทของคุณอยู่ที่นี่หรือไม่? เพียงแค่ทำคำขอดึง ยอมรับเฉพาะบอทที่มีซอร์สโค้ดสาธารณะ