TeleBot, a Python library for interacting with the Telegram Bot API, defines content types to help you easily identify and handle different kinds of messages that your bot receives. These content types simplify the process of extracting relevant information from incoming updates and responding accordingly. Here’s a breakdown of the common content types in TeleBot:
Key Content Types
TeleBot’s message. content_type attribute will be one of these values:
Text: A plain text message. This is the most common type of message.
message. text: Contains the text of the message.
Audio: An audio file.
message. audio: Contains an Audio object with information about the audio file (duration, file_id, mime_type, etc.). Use bot. get_file(message. audio. file_id) to download the file.
Document: A general document file (not specifically audio, photo, video, or voice).
message. document: Contains a Document object with information about the document (file_name, mime_type, file_size, file_id, etc.). Use bot. get_file(message. document. file_id) to download the file.
Photo: A photo (image) message.
message. photo: Contains a list of PhotoSize objects. Telegram sends photos in multiple sizes. The last element in the list is the largest photo. Use bot. get_file(message. photo[-1].file_id) to download the file.
Sticker: A sticker.
message. sticker: Contains a Sticker object with information about the sticker (file_id, width, height, emoji, etc.). Use bot. get_file(message. sticker. file_id) to download the sticker file.
Video: A video file.
message. video: Contains a Video object with information about the video (duration, file_id, width, height, mime_type, etc.). Use bot. get_file(message. video. file_id) to download the file.
Voice: A voice message (audio recorded directly within Telegram).
message. voice: Contains a Voice object with information about the voice message (duration, file_id, mime_type, etc.). Use bot. get_file(message. voice. file_id) to download the file.
Video_note: A video note (a circular video message).
message. video_note: Contains a VideoNote object with information about the video note (duration, file_id, length, etc.). Use bot. get_file(message. video_note. file_id) to download the file.
Contact: A contact shared by the user.
message. contact: Contains a Contact object with information about the contact (phone_number, first_name, last_name, etc.).
Location: A location shared by the user.
message. location: Contains a Location object with latitude and longitude.
Venue: A venue (a place with a name, address, and location).
message. venue: Contains a Venue object with information about the venue (location, title, address, etc.).
Animation: An animated GIF or other animation. Technically a special type of document.
message. animation: Contains an Animation object. Use bot. get_file(message. animation. file_id) to download.
Game: A game (if your bot is integrated with Telegram games).
message. game: Contains a Game object.
Poll: A poll created in a Telegram group or channel.
message. poll: Contains a Poll object.
Invoice: An invoice (if your bot is integrated with Telegram payments).
message. invoice: Contains an Invoice object.
Successful_payment: Information about a successful payment.
message. successful_payment: Contains a SuccessfulPayment object.
Dice: A dice throw result.
message. dice: Contains a Dice object with the value of the dice throw.
Reply: (This is not a content type itself, but related to replying to messages) A message object that you are replying to.
* `message. reply_to_message`: Contains the `Message` object of the message being replied to.
How to Use Content Types
Here’s how you can use content types to handle different messages in your TeleBot:
Import telebot
API_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN" # Replace with your bot’s token
Bot = telebot. TeleBot(API_TOKEN)
@bot. message_handler(func=lambda message: True) # Handles all messages
Def handle_all_messages(message):
if message. content_type == ‘text’:
bot. reply_to(message, f"You sent me text: {message. text}")
elif message. content_type == ‘photo’:
bot. reply_to(message, "Nice photo!")
# Get the file_id of the largest photo
file_id = message. photo[-1].file_id
file_info = bot. get_file(file_id)
downloaded_file = bot. download_file(file_info. file_path)
with open("image. jpg", ‘wb’) as new_file: # Save the photo
new_file. write(downloaded_file)
elif message. content_type == ‘audio’:
bot. reply_to(message, "I received an audio file!")
elif message. content_type == ‘document’:
bot. reply_to(message, f"I received a document named: {message. document. file_name}")
#Download the document
file_id = message. document. file_id
file_info = bot. get_file(file_id)
downloaded_file = bot. download_file(file_info. file_path)
with open(message. document. file_name, ‘wb’) as new_file:
new_file. write(downloaded_file)
elif message. content_type == ‘location’:
bot. reply_to(message, f"You sent a location: Latitude={message. location. latitude}, Longitude={message. location. longitude}")
else:
bot. reply_to(message, f"I received something else: {message. content_type}")
Bot. infinity_polling()
Explanation:
@bot. message_handler(func=lambda message: True): This decorator registers a function to handle all incoming messages. The func=lambda message: True part means that the handler will be called for every message, regardless of its content. You can replace True with a more specific condition to filter messages based on other criteria (e. g., func=lambda message: message. chat. type == ‘private’ to handle only private messages). Message. content_type: Inside the handler function, we check the message. content_type attribute to determine the type of the message. Handling Different Content Types: Based on the content_type, we extract the relevant data from the message object (e. g., message. text, message. photo, message. location) and process it accordingly. Downloading Files: For file-based content types (audio, document, photo, video, voice, etc.), you need to use bot. get_file(file_id) to get the file path on Telegram servers. Then use bot. download_file(file_path) to download the file content itself. Remember to save the downloaded content to a file with the appropriate extension.
Best Practices:
Use Specific Handlers: Instead of a single handler that handles all message types, consider using multiple handlers with more specific filters. This makes your code more organized and easier to maintain. For example:
· @bot. message_handler(content_types=[‘text’])
· def handle_text_messages(message):
· bot. reply_to(message, message. text)
·
· @bot. message_handler(content_types=[‘photo’])
· def handle_photo_messages(message):
· bot. reply_to(message, "Nice photo!")
Handle Unknown Content Types: Include a default case in your message handler to handle content types that your bot doesn’t explicitly support. This can help prevent errors and provide a more user-friendly experience. Error Handling: Implement proper error handling, especially when downloading files. Network errors or problems with the Telegram API can cause downloads to fail.