Telegram Bot AI Video: Clips and Images From One API
Telegram bot AI video, step by step: commands, the API calls, waiting for clips by polling or webhook, photo to video, and budgets per user.
Updated 6 min read
A Telegram bot AI video generator is a small program on your server: it reads commands from Telegram, sends each prompt to a video API, waits for the clip and sends the file back to the chat. With Frameport the bot needs a single key for clips and images: Frameport Motion 1 makes /video, $0.10 for 5 seconds at 480p with sound, and Nano Banana 2.1 makes /image at $0.085 an image.
This guide builds the bot in Python with requests and nothing else: the commands, a photo turned into a clip, the two waits every video bot has (Telegram's updates and the clip itself), sending files within Telegram's limits, and a daily budget per user.
The Telegram bot AI video flow in brief
| The user sends | The bot calls | Model | Price |
|---|---|---|---|
/image a lighthouse in fog | POST /v1/images/generations | Nano Banana 2.1 | $0.085 |
/video a paper boat on a rainy street | POST /v1/videos/generations | Frameport Motion 1, 5 s, 480p, 9:16 | $0.10 |
A photo captioned /animate she turns and waves | POST /v1/uploads, then the video endpoint | Frameport Motion 1, the photo as first frame | $0.10 |
Before the code, two secrets. Talk to @BotFather in Telegram, create a bot and copy its token. Then create a Frameport account, add funds and make an API key for this bot alone. Both go in the environment of the server that runs the bot. Telegram users never see your key: they send a command, your server makes the call (authentication).
export TELEGRAM_BOT_TOKEN="..."
export FRAMEPORT_API_KEY="fp_live_..."
pip install requestsCommands to requests
The script long-polls Telegram for messages, turns each command into a request, and checks its running jobs after every poll:
import mimetypes
import os
import time
import requests
API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}
BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
TELEGRAM = f"https://api.telegram.org/bot{BOT_TOKEN}"
DAILY_BUDGET = float(os.environ.get("USER_DAILY_BUDGET", "1")) # your dollars, per user per day
RATIOS = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1, "4:3": 4 / 3, "3:4": 3 / 4}
pending = {} # generation id -> (chat id, budget key); use a database in production
spent = {} # (user id, UTC day) -> dollars charged
def telegram(method, **params):
return requests.post(f"{TELEGRAM}/{method}", timeout=120, **params).json()
def say(chat_id, text):
telegram("sendMessage", json={"chat_id": chat_id, "text": text})
def upload_photo(message):
"""Copy the user's photo to the API: Telegram's file link holds the bot token, so it stays here."""
photo = message["photo"][-1] # the largest size Telegram kept
path = telegram("getFile", json={"file_id": photo["file_id"]})["result"]["file_path"]
data = requests.get(f"https://api.telegram.org/file/bot{BOT_TOKEN}/{path}", timeout=60).content
upload = requests.post(f"{API}/uploads", params={"filename": "photo.jpg"}, data=data, timeout=60,
headers={**HEADERS, "Content-Type": "image/jpeg"}).json()
if upload.get("error"):
raise RuntimeError(upload["error"]["message"])
shape = photo["width"] / photo["height"]
return upload["id"], min(RATIOS, key=lambda name: abs(RATIOS[name] - shape))
def request_for(message):
"""The endpoint and body for a command, or None."""
command, _, prompt = (message.get("text") or message.get("caption") or "").partition(" ")
command, prompt = command.split("@")[0], prompt.strip() # "/video@YourBot" in groups
if not prompt:
return None
if command == "/image":
return "/images/generations", {"model": "nano-banana-2-1", "prompt": prompt, "aspect_ratio": "1:1"}
clip = {"model": "fp-motion-1", "prompt": prompt, "duration": 5, "resolution": "480p", "aspect_ratio": "9:16"}
if command == "/video":
return "/videos/generations", clip
if command == "/animate" and message.get("photo"):
frame, shape = upload_photo(message)
return "/videos/generations", {**clip, "reference_images": [frame], "aspect_ratio": shape}
return None
def start(message, update_id):
chat_id = message["chat"]["id"]
found = request_for(message)
if not found:
say(chat_id, "Send /image <prompt>, /video <prompt>, or a photo captioned /animate <what moves>.")
return
path, body = found
budget = (message["from"]["id"], time.strftime("%Y-%m-%d", time.gmtime()))
quote = requests.post(f"{API}/generations/quote", headers=HEADERS, json=body, timeout=30).json()
if quote.get("error"):
raise RuntimeError(quote["error"]["message"])
if spent.get(budget, 0) + quote["price_usd"] > DAILY_BUDGET:
say(chat_id, "You have used today's budget. It resets at midnight UTC.")
return
gen = requests.post(f"{API}{path}", json={**body, "max_cost_usd": quote["price_usd"]}, timeout=60,
headers={**HEADERS, "Idempotency-Key": f"telegram-{update_id}"}).json()
if gen.get("error"):
raise RuntimeError(gen["error"]["message"])
pending[gen["id"]] = (chat_id, budget)
action = "upload_video" if gen["type"] == "video" else "upload_photo"
telegram("sendChatAction", json={"chat_id": chat_id, "action": action})
say(chat_id, "Started. It will arrive in this chat.")
def send_result(chat_id, gen):
output = gen["outputs"][0]
data = requests.get(output["url"], timeout=300).content # a signed link: no key needed
name = "result" + (mimetypes.guess_extension(output["content_type"]) or "")
fields = {"chat_id": chat_id}
if gen["type"] == "video" and len(data) > 50_000_000:
say(chat_id, f"Too large for a bot to send. This link opens for about an hour: {output['url']}")
return
if gen["type"] == "video":
method, field = "sendVideo", "video"
fields["supports_streaming"] = "true"
elif len(data) <= 10_000_000:
method, field = "sendPhoto", "photo"
else:
method, field = "sendDocument", "document" # sendPhoto stops at 10 MB
telegram(method, data=fields, files={field: (name, data, output["content_type"])})
def deliver():
for gen_id, (chat_id, budget) in list(pending.items()):
gen = requests.get(f"{API}/generations/{gen_id}", headers=HEADERS, timeout=30).json()
if gen["status"] in ("queued", "running"):
continue
del pending[gen_id]
if gen["status"] == "failed":
say(chat_id, f"That one failed, and nothing was charged: {gen['error']['message']}")
continue
spent[budget] = spent.get(budget, 0) + gen["cost_usd"]
send_result(chat_id, gen)
def handle(update):
message = update.get("message")
if not message:
return
try:
start(message, update["update_id"])
except RuntimeError as err: # refused before anything was held
say(message["chat"]["id"], f"Not started, nothing charged: {err}")
if __name__ == "__main__":
offset = 0
while True:
# Long polling: Telegram holds the call open up to 20 seconds when nothing is new
updates = telegram("getUpdates", json={"offset": offset, "timeout": 20, "allowed_updates": ["message"]})
for update in updates.get("result", []):
offset = update["update_id"] + 1
handle(update)
deliver()What each part does:
- A quote before every job.
POST /v1/generations/quoteprices the body without holding or starting anything, so the bot can refuse a request the user's budget no longer covers (quotes). - A cap on every job.
max_cost_usdset to the quoted price refuses anything that would cost more, before any money is held. - One job per Telegram update. The
Idempotency-Keycomes from the update's id, so a submit retried after a timeout returns the first generation instead of paying for a second (idempotency). - No waiting inside a command. The bot keeps a table of running jobs and checks it after each poll, so a clip in progress never blocks the next message. Reads are not counted against your rate limits.
Picture to video in a Telegram bot
When a user sends a photo with /animate as its caption, the bot turns it into the clip's first frame. Telegram hands a bot its files through a link that contains the bot token, so that link must never reach a third party, us included. The script downloads the photo on your server and streams it to POST /v1/uploads, which answers with an id that any request can use for 24 hours (uploads).
The photo then rides in reference_images as the first frame, with an aspect ratio picked to match its shape. Because the frame already shows the subject and the scene, the caption only has to say what moves: "she turns to the camera and laughs", "the waves roll in, slow push-in". On Frameport Motion 1, a first frame does not change the price. The image to video API guide lists the models that take a first frame, and first and last frame video adds a picture to land on.
Sending the clip back to the chat
Telegram's Bot API takes uploaded files of up to 50 MB, photos up to 10 MB, and smaller files when you send a link instead (5 MB for a photo, 20 MB for anything else). So the bot downloads each output from its signed link, which opens without a key for about an hour, and uploads the bytes:
- Clips go out with
sendVideoandsupports_streaming, so they play before the download ends. Short clips at 480p keep the file small. - Images go out with
sendPhoto, orsendDocumentwhen a large picture passes 10 MB. - Anything bigger gets the signed link in a message. Files are not kept forever on our side: a bot that keeps a history copies them to its own storage (files).
sendChatAction shows "sending video" in the chat for a few seconds only (Telegram says 5 at most), so the bot also sends a plain "Started" message the user can see while the clip renders.
Waiting for video: polling vs webhooks on Telegram
A video bot waits twice: for Telegram to deliver messages, and for each clip to finish. Each wait can be polling or a webhook.
| Polling | Webhook | |
|---|---|---|
| Telegram updates | getUpdates with a timeout: long polling, no public URL needed | setWebhook: Telegram posts each update to your HTTPS address |
| The clip | GET /v1/generations/{id} until it settles | Frameport posts generation.succeeded or generation.failed |
| Good for | One process on any machine, and development | Many users, serverless hosting, results the moment they land |
Long polling is the script above. To switch both waits to webhooks, register your Telegram address with a secret_token, which Telegram sends back in the X-Telegram-Bot-Api-Secret-Token header of every update. Telegram takes webhooks on ports 443, 80, 88 and 8443, and getUpdates stops working while one is set.
curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \
-d url=https://bot.example.com/telegram \
-d secret_token="$TELEGRAM_WEBHOOK_SECRET"Then add https://bot.example.com/generations under Webhooks in the dashboard, for both events. One small Flask app receives both, and reuses the functions of bot.py:
import hashlib
import hmac
import json
import os
import threading
import time
from flask import Flask, request
import bot # the script above: its polling loop only runs when started directly
app = Flask(__name__)
TELEGRAM_SECRET = os.environ["TELEGRAM_WEBHOOK_SECRET"] # the string you gave setWebhook
SIGNING_SECRET = os.environ["WEBHOOK_SECRET"] # whsec_..., shown once when you add the endpoint
seen = set() # delivery ids already handled: a retried delivery keeps its id
def signed(raw, header, tolerance=300):
parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
if "t" not in parts or "v1" not in parts or abs(time.time() - int(parts["t"])) > tolerance:
return False
expected = hmac.new(SIGNING_SECRET.encode(), parts["t"].encode() + b"." + raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts["v1"])
@app.post("/telegram")
def telegram_update():
if request.headers.get("X-Telegram-Bot-Api-Secret-Token") != TELEGRAM_SECRET:
return "", 403
threading.Thread(target=bot.handle, args=(request.get_json(),)).start()
return "", 200
@app.post("/generations")
def generation_settled():
raw = request.get_data()
if not signed(raw, request.headers.get("Frameport-Signature", "")):
return "", 400
event = json.loads(raw)
gen = event["data"]
if event["id"] in seen or gen["id"] not in bot.pending:
return "", 204 # already handled, or a job this bot did not start
seen.add(event["id"])
chat_id, budget = bot.pending.pop(gen["id"])
if gen["status"] == "failed":
bot.say(chat_id, f"That one failed, and nothing was charged: {gen['error']['message']}")
else:
bot.spent[budget] = bot.spent.get(budget, 0) + gen["cost_usd"]
threading.Thread(target=bot.send_result, args=(chat_id, gen)).start()
return "", 204Both handlers answer at once and do the slow work in a thread: Frameport expects a 2xx within 10 seconds and retries after 1, 5 and 15 minutes otherwise (webhooks). Run bot.deliver() every few minutes as a backstop for a delivery your server missed. Polling vs webhooks covers that hybrid, and the video generation API in Python the calls one by one.
Budgets per user
| What | Where it is set | What happens past it |
|---|---|---|
| A daily budget per user | USER_DAILY_BUDGET, checked against each quote | The bot says so and starts nothing |
| The price of one job | max_cost_usd on the request | 400 max_cost_exceeded, nothing held |
| Jobs that start, per minute | 60 for the whole workspace | 429 rate_limited with Retry-After |
| Jobs running at once | 20 for the whole workspace | 429 concurrency_limit |
In a group chat, key the budget on the chat as well as the user, so one busy group cannot spend for everyone. Keep the spent table in a database, so a restart does not reset it.
Every workspace starts with its content filter on, and a prompt it blocks is refused with 400 content_filtered before anything is held. For an unfiltered Telegram AI bot, only an owner or an admin of the workspace, aged 18 or older, can turn the filter off in Settings; our own models, Frameport Motion 1 included, then render without a content filter. Models from other makers, such as Nano Banana 2.1, keep their makers' policies and may refuse, and the acceptable use policy applies either way: nothing involving minors, no real identifiable people without their consent, nothing illegal. That covers the photos people send to /animate too, and you answer for what users make through your keys. A refused job costs nothing.
The photos sent to /animate reach the API as described in upload image to API, and the bot's key belongs on your server (API key security).
FAQ
How do I make a Telegram bot that generates AI videos?
Create the bot with @BotFather, read its messages with getUpdates or a webhook, send each prompt to a video API from your server, and send the clip back with sendVideo once the job succeeds. The bot.py script above does it with Python and requests.
Should a Telegram bot use long polling or webhooks?
Long polling for one process or while you develop: it needs no public URL. Webhooks once the bot has many users or runs on serverless hosting: Telegram posts each update to your HTTPS address, and the same server can take the video API's webhooks too.
Can a Telegram bot turn a picture into a video?
Yes. The bot downloads the photo on its own server, uploads it to the video API, and sends it as the first frame of the clip, with a prompt that describes the motion. Never pass Telegram's file link on, since it contains the bot token.
How big a video can a Telegram bot send?
Telegram's Bot API says bots can send video files of up to 50 MB by upload, and up to 20 MB when they send a link instead. Short clips at 480p keep files small; for anything larger, send a link.
Is there a free AI video generator Telegram bot?
Not one that renders for nothing. The account, the API key and quotes are free, and a clip that fails costs nothing, but each clip is paid from a prepaid balance, from $0.02 a second. You can try a prompt in the Studio before your bot sends it.