EnglishEN

How to make a Telegram AI bot: from a BotFather token to connecting AI

Send /newbot to @BotFather on Telegram to get a bot and a token, then use one Python file so Gemini answers whatever you send your bot. The same bot can also alert you when a web page you watch changes.

Where to goTelegram @BotFatherTerminalnews folder from part 3

Steps

  1. In the Telegram app, find @BotFather and open a chat. Check that the account has the blue check mark next to its name. Send /newbot, send a bot name (the name shown in chats; any language is fine), then send a bot username. The username must end in bot (like my_ai_bot or MyAiBot) and can only use 5–32 Latin letters, numbers and underscores. When you are done, BotFather sends you a token.
  2. The token is a long string shaped like numbers:letters_and_numbers. Anyone who has it can control your bot, so treat it like a password: do not write it in the code; put it in an environment variable (Mac). On Windows, enter setx TELEGRAM_BOT_TOKEN "YOUR_TOKEN_HERE" and then open a new window. If someone else has seen the token, send /token to BotFather to get a new one. The old token stops working from then on.
    echo 'export TELEGRAM_BOT_TOKEN="YOUR_TOKEN_HERE"' >> ~/.zshrc
    source ~/.zshrc
  3. You can get the code by putting this into the Claude, ChatGPT or Gemini chat window. As in part 3, you write what it receives, what it does, where it sends the result, and «do not write secret values in the code». To have Claude write the bot's answers, add one more line asking it to switch to code that uses the Claude key from part 2. This part uses Gemini, which has a free tier.
    Please make a Telegram bot in a single Python file.
    1. Call getUpdates from the Telegram Bot API with long polling (timeout 30 seconds) to receive new messages.
    2. Send the received text to the Gemini API (the google-genai library) and get a short answer in English.
    3. Send that answer to the same chat with sendMessage. Cut it at 4000 characters so it stays under Telegram's length limit.
    4. Answer only in the chat that matches the environment variable TELEGRAM_CHAT_ID; if that value is empty, only report the chat id of the chat it came from.
    Do not write the token and key in the code; read them from the environment variables TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, GEMINI_API_KEY.
    Use only one outside library, google-genai, and call Telegram with Python's built-in urllib.
  4. Turn on the venv in the news folder from part 3 (Mac source .venv/bin/activate · Windows .venv\Scripts\activate). Once you see (.venv) at the start of the line, create ai_bot.py in that folder and paste the code in. There are no new libraries to install. If the code the AI gave you looks very different, you can use this code as it is.
    import json
    import os
    import urllib.parse
    import urllib.request
    
    from google import genai
    
    # Read the bot token and my chat id from environment variables, not from the code
    TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
    MY_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")  # If empty, the bot only reports the chat id
    API = f"https://api.telegram.org/bot{TOKEN}/"
    
    def call(method, **params):
        data = urllib.parse.urlencode(params).encode()
        with urllib.request.urlopen(API + method, data=data, timeout=40) as r:
            return json.loads(r.read())["result"]
    
    def ask_ai(question):
        client = genai.Client()  # Reads the GEMINI_API_KEY environment variable
        interaction = client.interactions.create(
            model="gemini-4-hydrogen",
            input="Please answer briefly and clearly in English.\n\n" + question,
        )
        return interaction.output_text
    
    def main():
        print("The bot is on. Press Ctrl+C to stop it.")
        offset = 0
        while True:
            # Wait up to 30 seconds for new messages (long polling)
            for update in call("getUpdates", offset=offset, timeout=30):
                offset = update["update_id"] + 1
                msg = update.get("message")
                if not msg or "text" not in msg:
                    continue
                chat_id = str(msg["chat"]["id"])
                if not MY_CHAT_ID:
                    print(f"My chat id: {chat_id}")
                    call("sendMessage", chat_id=chat_id, text=f"chat id: {chat_id}")
                    continue
                if chat_id != MY_CHAT_ID:
                    continue  # Do not answer messages from anyone but me
                answer = ask_ai(msg["text"])
                call("sendMessage", chat_id=chat_id, text=answer[:4000])
    
    if __name__ == "__main__":
        main()
    
  5. Start it for the first time. When «The bot is on.» appears, find the bot you made in step 1 in Telegram on your phone, tap Start and send anything. The bot replies with chat id: NUMBER, and the same number shows on your computer screen. The chat id is the number of the chat the bot sends answers to; once you set it, the bot will not answer anyone else who messages it. Stop it with Ctrl+C.
    python ai_bot.py
  6. Put this number in an environment variable (Mac). On Windows, enter setx TELEGRAM_CHAT_ID "YOUR_NUMBER_HERE", then open a new window, go into the folder with cd news, and activate again.
    echo 'export TELEGRAM_CHAT_ID="YOUR_NUMBER_HERE"' >> ~/.zshrc
    source ~/.zshrc
  7. Start it again. Now when you send the bot a question, Gemini's answer comes back on Telegram. It answers only while this window is running.
    python ai_bot.py
  8. The same bot can also «alert you when a page you watch changes». Use it for places you used to check every day for notices or openings. This file does not use AI; if the page content differs from last time, it sends you one line on Telegram. Create page_watch.py in the same folder and paste the code in.
    import hashlib
    import os
    import pathlib
    import urllib.parse
    import urllib.request
    
    TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
    MY_CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
    WATCH_URL = "https://www.python.org/downloads/"  # Change to the address you want to watch
    SAVED = pathlib.Path("last_page.txt")  # Fingerprint of the page from last time
    
    def send(text):
        data = urllib.parse.urlencode({"chat_id": MY_CHAT_ID, "text": text}).encode()
        urllib.request.urlopen(f"https://api.telegram.org/bot{TOKEN}/sendMessage", data=data, timeout=20)
    
    req = urllib.request.Request(WATCH_URL, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=20) as r:
        now = hashlib.sha256(r.read()).hexdigest()
    
    before = SAVED.read_text() if SAVED.exists() else ""
    if before and before != now:
        send(f"The page has changed: {WATCH_URL}")
        print("Changed → sent to Telegram")
    else:
        print("First check" if not before else "No change")
    SAVED.write_text(now)
    
  9. Run it. The first time you see «First check», after that «No change», and on a day the page changes you get an alert on Telegram.
    python page_watch.py

Docs the code follows

  • The address shape https://api.telegram.org/bot<TOKEN>/METHOD_NAME, getUpdates offset (start after what was already received) and timeout (long polling seconds), and the sendMessage length of 1–4096 characters follow the Telegram Bot API docs.
  • The model name and the shape of the Gemini call are the same as in part 3.
  • The bot answers only while the file is running on your computer. How to keep it answering with your computer off is covered in part 11, the server part.

Using page alerts

  • A page with text that changes every time you look, such as dates or visitor counts, will show «Changed» every time. For those, if there is an RSS feed, watch the RSS address as in part 3, or ask the AI to change the code to compare only the part you care about (such as the notice list) instead of the whole page.
  • If sending the alert fails, the fingerprint is not saved, so it sends again the next time you run it.
  • If you want «what changed» in one line, ask the AI for one more thing: feed the changed text to Gemini, like summarize in part 3.
  • How to run it automatically once a day is covered in the server parts.

Troubleshooting

  • KeyError: 'TELEGRAM_BOT_TOKEN': you did not set the token environment variable, or the name is wrong. Go back to step 2. On Windows, check that you opened a new window.
  • HTTP Error 401: Unauthorized: the token is wrong. Enter the token BotFather sent again, with no spaces before or after. If you got a new one with /token, the old token no longer works.
  • HTTP Error 404: Not Found: the token has the wrong shape. Check that you copied the whole numbers:letters string, including the : in the middle.
  • CERTIFICATE_VERIFY_FAILED (Mac): you did not run Install Certificates.command from step 1 of part 3. If that is hard to run, enter export SSL_CERT_FILE=$(python -c "import certifi; print(certifi.where())") in the window with the venv on and run it again in the same window (if you close the window, enter it again).
  • Bot does not answer at all: check that you tapped Start for the bot on your phone and that the python ai_bot.py window is running on your computer. If it only answers with the chat id, set TELEGRAM_CHAT_ID and start it again. If an error appeared in the window and the bot stopped the moment you sent the first message, see the two lines below.
  • BadRequestError 400 API_KEY_INVALID: the Gemini key was pasted wrong. Fix it as in «Troubleshooting» in part 2. Starting the bot works; the error shows up when the first message comes in.
  • ValueError: No API key was provided.: the Gemini key environment variable GEMINI_API_KEY could not be found. Check with the check command from part 2. This one also shows up when the first message comes in.
  • KeyError: 'TELEGRAM_CHAT_ID' (page_watch.py): the watch file sends to your chat id, so set TELEGRAM_CHAT_ID before running it.
  • No answer when someone else messages the bot: this is on purpose. It only answers your chat id.
  • Bots that have had a webhook set: according to the Telegram docs, getUpdates does not work on a bot with a webhook set. This part works without webhooks.
  • ModuleNotFoundError: No module named 'google': you ran it outside the venv box. Activate it so (.venv) shows at the start of the line, then run it.
  • Bot stops when you turn off your computer: that is because the bot runs on your computer. How to keep it running is covered in part 11.

Next part

In part 5, we have AI fill in summary and category columns in a Google Sheet where orders and inquiries pile up.

Source

Related posts