DEV Community

tansihmittal
tansihmittal

Posted on

Build Your First Telegram Bot: URL Shortener

A Super Simple Guide for Complete Beginners πŸš€

Telegram

Hey there! πŸš€ Let's build something cool togetherβ€”a Telegram bot that shortens long URLs. Don't worry if you're new to coding; we'll go step by step!


🎯 What Will Our Bot Do?

βœ… Turn long URLs into short ones

βœ… Create custom short URLs (choose your own nickname for a link!)

βœ… Work directly in Telegram, just like chatting with a friend


πŸ› οΈ What You’ll Need


πŸ“ Step-by-Step Guide

Step 1: Setting Up Your Tools

Install the required Python packages by running:

pip install python-telegram-bot shotcutap
Enter fullscreen mode Exit fullscreen mode

Step 2: Getting Your Telegram Bot Token

  1. Open Telegram and search for β€œBotFather”.
  2. Send /newbot and follow the prompts:
    • Choose a name (e.g., My URL Shortener)
    • Choose a username (must end in bot, e.g., myurlshortener_bot)

BotFather

  1. BotFather will give you a bot tokenβ€”save it somewhere safe!

Step 3: Getting Your Shotcut API Key

  1. Go to Shotcut Developer Portal
  2. Sign up for a free account
  3. Get your API key from the dashboard Shotcut API

πŸ§‘β€πŸ’» Step 4: Writing the Code

Create a new file bot.py and paste this code:

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from shotcut import ShotcutAPI

BOT_TOKEN = "paste_your_telegram_bot_token_here"  # Get this from BotFather
SHOTCUT_API_KEY = "paste_your_shotcut_api_key_here"  # Get this from Shotcut website

shortener = ShotcutAPI(api_key=SHOTCUT_API_KEY)

async def welcome_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
    welcome_message = """
    πŸ‘‹ Hi there! I'm your URL Shortener Bot!
    Just send me any link, and I'll make it shorter for you!
    Type /help for more info.
    """
    await update.message.reply_text(welcome_message)

async def show_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
    help_message = """
    πŸ“š How to use me:
    1️⃣ Send a link to shorten it.
    2️⃣ Use /custom [URL] [name] for a custom short link.
    """
    await update.message.reply_text(help_message)

async def make_custom_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if len(context.args) < 2:
        await update.message.reply_text("❌ Please provide a URL and custom name.")
        return

    original_link, custom_name = context.args[0], context.args[1]
    try:
        result = shortener.shorten_link(url=original_link, custom=custom_name)
        await update.message.reply_text(f"✨ Custom short link: {result['shorturl']}")
    except Exception as e:
        await update.message.reply_text(f"πŸ˜” Error: {str(e)}")

async def make_short_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
    original_link = update.message.text.strip()
    if not original_link.startswith(('http://', 'https://')):
        await update.message.reply_text("πŸ€” That doesn't look like a valid link.")
        return

    try:
        result = shortener.shorten_link(url=original_link)
        await update.message.reply_text(f"✨ Short link: {result['shorturl']}")
    except Exception as e:
        await update.message.reply_text(f"πŸ˜” Error: {str(e)}")


def start_bot():
    print("πŸš€ Starting Telegram Bot...")
    app = Application.builder().token(BOT_TOKEN).build()
    app.add_handler(CommandHandler("start", welcome_user))
    app.add_handler(CommandHandler("help", show_help))
    app.add_handler(CommandHandler("custom", make_custom_link))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, make_short_link))
    app.run_polling()

if __name__ == '__main__':
    start_bot()
Enter fullscreen mode Exit fullscreen mode

πŸš€ Running Your Bot

  1. Save Your Secret Tokens

    • Replace paste_your_telegram_bot_token_here with your Telegram bot token
    • Replace paste_your_shotcut_api_key_here with your Shotcut API key
  2. Start Your Bot

   python bot.py
Enter fullscreen mode Exit fullscreen mode

You should see β€œYour bot is ready!” πŸŽ‰

  1. Test Your Bot
    • Open Telegram and find your bot
    • Try /start, /help, sending a link, and /custom commands Demo

πŸ” Troubleshooting

Issue Solution
Invalid Token Ensure your bot token is correct & has no spaces
Links not working Make sure they start with http:// or https://
Bot not responding Restart the bot (Ctrl+C then python bot.py)

πŸ”’ Keep Your Bot Secure

  • Never share your bot token or API key
  • Store your credentials in a safe place
  • Be careful about the links you shorten

πŸŽ‰ You Did It!

Congratulations! You’ve built your own Telegram bot! This is just the beginningβ€”feel free to add more features.

Need help? The Python and Telegram Bot communities are super friendly and always happy to help new coders! 😊

Try Shotcut.in Official Telegram Bot πŸ”—βœ¨

Happy coding! πŸš€

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more