How to Create a Telegram Bot Using Python and Host it in a Server for free

✅ Step 1: Create Your Telegram Bot

  1. Open Telegram and search for @BotFather.
  2. Type /start and then /newbot.
  3. Follow the instructions, give your bot a name and a username.
  4. Copy the Bot Token you receive. (Example: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11)

✅ Step 2: Write Your Bot in Python

Install the required library:

pip install python-telegram-bot

Create a file named bot.py:

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

TOKEN = 'YOUR_BOT_TOKEN_HERE'

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hello! I am your bot.")

if __name__ == '__main__':
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    print("Bot is running...")
    app.run_polling()

✅ Step 3: Host for Free (2 Options)

🔹 Option A: Replit

  1. Go to replit.com and create a new Python project.
  2. Upload bot.py and install python-telegram-bot via "Packages".
  3. Edit .replit:
    run = "python3 bot.py"
  4. Click "Run". Your bot is live!

🔹 Option B: Railway

  1. Go to railway.app and sign in via GitHub.
  2. Create a GitHub repo with these files:
    • bot.py
    • requirements.txt:
      python-telegram-bot==20.4
  3. Connect the repo to Railway, deploy it.
  4. Set an environment variable in Railway:
    BOT_TOKEN = your_bot_token_here
  5. Modify your Python code to use:
    import os
    TOKEN = os.getenv("BOT_TOKEN")

✅ Step 4: Keep Bot Awake (for Replit)

  1. Use UptimeRobot to ping your bot every 5 minutes.
  2. You may need to run a simple web server in Replit to serve a keep-alive page.

✅ Final Tips

  • Use async properly for all bot functions.
  • Avoid long or blocking operations.
  • Use logging to debug:
    import logging
    logging.basicConfig(level=logging.INFO)
Author Image

Harun or Rashid Anik


I am a website developer, app developer and content writer. I have been in this profession since 2017.

Previous Post Next Post