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
- In the Telegram app, find
@BotFatherand 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 inbot(likemy_ai_botorMyAiBot) and can only use 5–32 Latin letters, numbers and underscores. When you are done, BotFather sends you a token. - 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, entersetx TELEGRAM_BOT_TOKEN "YOUR_TOKEN_HERE"and then open a new window. If someone else has seen the token, send/tokento 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 - 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. - Turn on the venv in the
newsfolder from part 3 (Macsource .venv/bin/activate· Windows.venv\Scripts\activate). Once you see(.venv)at the start of the line, createai_bot.pyin 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() - 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 withCtrl+C.python ai_bot.py - 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 withcd news, and activate again.echo 'export TELEGRAM_CHAT_ID="YOUR_NUMBER_HERE"' >> ~/.zshrc source ~/.zshrc - 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 - 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.pyin 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) - 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, getUpdatesoffset(start after what was already received) andtimeout(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
summarizein 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 wholenumbers:lettersstring, including the:in the middle.CERTIFICATE_VERIFY_FAILED(Mac): you did not runInstall Certificates.commandfrom step 1 of part 3. If that is hard to run, enterexport 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.pywindow is running on your computer. If it only answers with the chat id, setTELEGRAM_CHAT_IDand 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. BadRequestError400API_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 variableGEMINI_API_KEYcould 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 setTELEGRAM_CHAT_IDbefore 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
- AI automationGetting started with AI automation: Claude vs ChatGPT vs Gemini — which one fits your workAll three have two routes: the chat window and the API. Work a person can paste in each time goes in the chat window; work that must run by itself at a set time or condition goes through the API.4 stepsclaude.ai › chatgpt.com › gemini.google.comRead
- AI automationHow to get a Claude, ChatGPT and Gemini API key, and check pricing and free limitsGet an API key from each company's console with «Create key», and put it in an environment variable instead of writing it in code. Only Gemini has a free tier; ChatGPT and Claude charge for what you use.6 stepsaistudio.google.com/apikey › platform.openai.com/api-keys › platform.claude.com/settings/keysRead
- AI automationGet a daily morning news summary email with the Gemini API: your first Python automationBuild one Python file that collects news headlines, has Gemini summarize them in five lines, and sends the summary to your Gmail. Ask an AI to write the code; this guide only covers how to put it in place and run it.8 stepspython.org › Terminal › myaccount.google.com/apppasswordsRead