Background Remover

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:

  1. Open @BotFather on Telegram.
  2. Send /newbot and follow the instructions.
  3. Choose a unique bot name and username.
  4. Bot Name: Can be anything (e.g., `MyShortBot`)
  5. Username: Must end with `bot` (e.g., `MyShortBot_Bot`).
  6. Copy the API Token provided by BotFather.

    Example API Token:

    API
    1234567890:ABCDEFGHIJKLMNOpQRSTUVWXYZ
  7. BotFather API Token Screenshot

Step 2: Get TinyURL API Key

To get an API key from TinyURL:

  1. Go to TinyURL Developer Portal and sign up.
  2. Log in and navigate to the API Key section.
  3. Generate an API key and copy it.

    Example API Key:

    API
    8SaBJtNBHE1dPDyAo8LTjqLZhWDKAOcuDvSIOsZe8Fsmz4XoWN9lfWHr2mth
  4. Get TinyURL API Key Get TinyURL API Key Get TinyURL API Key Get TinyURL API Key

Step 3: Deploy on Cloudflare Workers

Now, we will deploy our bot on Cloudflare Workers.

  1. Sign up or log in to Cloudflare.
  2. Go to Workers & Pages in your Cloudflare dashboard.
  3. Click "Create Application" and select "Worker".
  4. Enter a name for your Worker and click "Deploy".
  5. After deployment, click on the Worker name to open its settings.
  6. Click "Quick Edit" or go to the "Edit Code" section.
  7. Delete the default code in the editor.
  8. Paste your code into the editor.
  9. Click "Save and Deploy" to update your Worker.
  10. Copy the assigned URL and use it as needed.
  11. Get TinyURL API Key Get TinyURL API Key Get TinyURL API Key Get TinyURL API Key

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:

  1. 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!

Telegram Bot Response Screenshot

Need Help?

If you face any issues, feel free to ask!

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.