Telegram URL Shortener Bot - Documentation
Telegram URL Shortener Bot - Complete Documentation
This guide will help you deploy a fully functional Telegram bot that shortens URLs using the TinyURL API and runs on Cloudflare Workers.
Step 1: Create a Telegram Bot
To create a Telegram bot, follow these steps:
- Open @BotFather on Telegram.
- Send
/newbot
and follow the instructions.
- Choose a unique bot name and username.
- Bot Name: Can be anything (e.g., `MyShortBot`)
- Username: Must end with `bot` (e.g., `MyShortBot_Bot`).
- Copy the API Token provided by BotFather.
Example API Token:
1234567890:ABCDEFGHIJKLMNOpQRSTUVWXYZ
-
Step 2: Get TinyURL API Key
To get an API key from TinyURL:
- Go to TinyURL Developer Portal and sign up.
- Log in and navigate to the API Key section.
- Generate an API key and copy it.
Example API Key:
8SaBJtNBHE1dPDyAo8LTjqLZhWDKAOcuDvSIOsZe8Fsmz4XoWN9lfWHr2mth
-
Step 3: Deploy on Cloudflare Workers
Now, we will deploy our bot on Cloudflare Workers.
- Sign up or log in to Cloudflare.
- Go to Workers & Pages in your Cloudflare dashboard.
- Click "Create Application" and select "Worker".
- Enter a name for your Worker and click "Deploy".
- After deployment, click on the Worker name to open its settings.
- Click "Quick Edit" or go to the "Edit Code" section.
- Delete the default code in the editor.
- Paste your code into the editor.
- Click "Save and Deploy" to update your Worker.
- Copy the assigned URL and use it as needed.
-
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
const TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_API";
const TINYURL_API_KEY = "YOUR_TINYURL_API_KEY";
const TELEGRAM_API = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}`;
async function handleRequest(request) {
if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 });
const update = await request.json();
if (!update.message || !update.message.text) return new Response("No message received", { status: 200 });
const chatId = update.message.chat.id;
const text = update.message.text.trim();
if (text === "/start") {
await sendTelegramMessage(chatId, "👋 Welcome! Send me any URL to shorten.");
return new Response("Welcome message sent", { status: 200 });
}
if (!text.startsWith("http")) {
await sendTelegramMessage(chatId, "❌ Invalid URL! Please send a valid link.");
return new Response("Invalid URL", { status: 200 });
}
const shortUrl = await shortenURL(text);
await sendTelegramMessage(chatId, `✅ Shortened URL: [${shortUrl}](${shortUrl})`);
return new Response("OK", { status: 200 });
}
async function shortenURL(longUrl) {
const response = await fetch("https://api.tinyurl.com/create", {
method: "POST",
headers: {
"Authorization": `Bearer ${TINYURL_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ url: longUrl }),
});
const result = await response.json();
return result.data.tiny_url;
}
async function sendTelegramMessage(chatId, message) {
await fetch(`${TELEGRAM_API}/sendMessage`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ chat_id: chatId, text: message, parse_mode: "Markdown", disable_web_page_preview: true }),
});
}
Step 4: Set Webhook
To connect the bot with Cloudflare:
- Open a browser and enter:
https://api.telegram.org/botYOUR_TELEGRAM_BOT_API/setWebhook?url=YOUR_CLOUDFLARE_WORKER_URL
Replace:
- YOUR_TELEGRAM_BOT_API → Your Bot API Token
- YOUR_CLOUDFLARE_WORKER_URL → Your Cloudflare Worker URL
Done! Test Your Bot
Now, open Telegram, send a long URL, and see it get shortened!
Need Help?
If you face any issues, feel free to ask!