When you refer to message.voice, you're interacting with a Voice object within the Telegram Bot API. This object contains information about an audio file sent as a voice message.
The Voice object itself, as defined by the Telegram Bot API, is primarily a data structure and does not have built-in "methods" in the object-oriented programming sense (like voice.play() or voice.transcribe()). Its purpose is to hold attributes (properties) describing the voice message.
However, the bot API provides methods to interact with this data (e.g., to download the file associated with the file_id). Also, specific bot libraries often add convenience methods to their wrapper objects.
Let's break it down:
Attributes of message.voice (The Voice object)
These are the properties you can access directly from the Voice object:
-
file_id (String)
- Description: Unique identifier for this file. It can be used to download or reuse the file.
- Example:
message.voice.file_id
-
file_unique_id (String)
- Description: Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
- Example:
message.voice.file_unique_id
-
duration (Integer)
- Description: Duration of the audio in seconds as defined by sender.
- Example:
message.voice.duration
-
mime_type (String, Optional)
- Description: MIME type of the file as defined by sender.
- Example:
message.voice.mime_type (e.g., 'audio/ogg')
-
file_size (Integer, Optional)
- Description: File size in bytes. It can be bigger than 2^31 and some programming languages may have trouble with it.
- Example:
message.voice.file_size
Methods related to message.voice
As mentioned, the Voice object itself doesn't have methods. Instead, you use methods of the Bot object (or similar objects provided by your chosen bot library) to interact with the data contained in the Voice object.
1. Telegram Bot API Methods (via your Bot object)
To download the voice message, you use the getFile method with the file_id:
getFile
- Purpose: To get a
File object which contains the file path and URL to download the actual file.
- How to use:
bot.get_file(file_id)
- Result: Returns a
File object which has a file_path attribute. You then use this file_path to construct the download URL (https://api.telegram.org/file/bot<token>/<file_path>).
2. Library-Specific Convenience Methods
Most popular Telegram bot libraries (like python-telegram-bot, pyrogram, telebot, etc.) add convenience methods directly to their Voice or File objects to simplify interactions.
Example (using python-telegram-bot library):
In python-telegram-bot, the Voice object often inherits from or wraps a File object, or provides direct methods to get file information and download.
Practical Example (using python-telegram-bot)
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
# Replace with your actual bot token
TOKEN = "YOUR_BOT_TOKEN"
async def voice_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handles incoming voice messages."""
user = update.effective_user
voice = update.message.voice
print(f"User {user.first_name} sent a voice message.")
print(f" File ID: {voice.file_id}")
print(f" File Unique ID: {voice.file_unique_id}")
print(f" Duration: {voice.duration} seconds")
if voice.mime_type:
print(f" MIME Type: {voice.mime_type}")
if voice.file_size:
print(f" File Size: {voice.file_size} bytes")
# Download the voice message
try:
# Get the File object (which contains the file_path)
file_obj = await voice.get_file()
# Define a path to save the file
download_path = f"downloads/{voice.file_id}.ogg"
# Download the file
await file_obj.download_to_drive(download_path)
await update.message.reply_text(
f"Voice message received and saved to: {download_path}"
)
print(f"Voice message downloaded to: {download_path}")
except Exception as e:
await update.message.reply_text(f"Error downloading voice message: {e}")
print(f"Error downloading voice message: {e}")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Sends a message when the command /start is issued."""
await update.message.reply_text("Send me a voice message!")
def main() -> None:
"""Start the bot."""
application = Application.builder().token(TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.Voice(), voice_handler))
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
# Create a 'downloads' directory if it doesn't exist
import os
if not os.path.exists('downloads'):
os.makedirs('downloads')
main()
In summary, message.voice gives you the data about the voice message (ID, duration, size, type). To act on that data (like downloading the file), you'll typically use methods provided by your bot's API wrapper library, which in turn utilize the underlying Telegram Bot API's getFile method.