Build a Telegram Bot with Python Telebot: A Step‑by‑Step Guide

This guide walks through creating a Telegram bot with Python's telebot library, covering data architecture, obtaining a BotFather token, configuring bot details, installing the package, writing message handlers, linking to a local LLM server, handling audio responses, and running the bot.

JavaEdge
JavaEdge
JavaEdge
Build a Telegram Bot with Python Telebot: A Step‑by‑Step Guide

0 Data Architecture

+-----+
        | TTS |
        +--+--+
           |
           v
     +------------+
     | Server api |
     +-----+------+
           |
     +-----v-----+
     |   Agent   |
     +-----+-----+
       |       |
   +---v---+ +-v------+
   | tools | | memory |
   +-------+ +--------+

Data flows from memory upward to TTS and then downward to tools.

1 Obtain Bot Token

Search for BotFather on Telegram and choose the officially verified (blue‑check) account; many impostors exist.

This is the genuine one.

1.1 Create a New Bot

1.2 Edit Bot Information

Edit the "About" field:

Set Bot Avatar

Now you can directly access the bot.

2 Install the telebot Package

import telebot
# previously obtained user token
bot = telebot.TeleBot('xxx:xxx')

3 Write Client Code

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, '你好我是JavaEdge,欢迎光临!')
python tele-qwen.py

Run the script; the bot will start responding.

3.1 Simple Reply

3.2 Reply with Reference

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.reply_to(message, '你好!')

4 Connect Bot to a Server‑Side LLM API

Link the bot to a chat interface that forwards user queries to a local LLM service.

@bot.message_handler(func=lambda message: True)
def echo_all(message):
    # bot.reply_to(message, message.text)
    try:
        encoded_text = urllib.parse.quote(message.text)
        response = requests.post('http://localhost:8090/chat?query=' + encoded_text, timeout=100)
        if response.status_code == 200:
            ai_say = json.loads(response.text)
            if "msg" in ai_say:
                bot.reply_to(message, ai_say["msg"]["output"])
                audio_path = f"{ai_say['id']}.mp3"
                asyncio.run(check_audio(message, audio_path))
            else:
                bot.reply_to(message, "对不起,我不知道怎么回答你")
    except requests.RequestException as e:
        bot.reply_to(message, "对不起,我不知道怎么回答你")

async def check_audio(message, audio_path):
    while True:
        if os.path.exists(audio_path):
            with open(audio_path, 'rb') as f:
                bot.send_audio(message.chat.id, f)
            os.remove(audio_path)
            break
        else:
            print("waiting")
            await asyncio.sleep(1)

bot.infinity_polling()

This forwards the LLM's textual and audio responses back to Telegram users.

Reference: Telegram Bot API.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

asyncioTelegram bottelebot
JavaEdge
Written by

JavaEdge

First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.