✅ Step 1: Create Your Telegram Bot
- Open Telegram and search for
@BotFather
. - Type
/start
and then/newbot
. - Follow the instructions, give your bot a name and a username.
- 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
- Go to replit.com and create a new Python project.
- Upload
bot.py
and installpython-telegram-bot
via "Packages". - Edit
.replit
:run = "python3 bot.py"
- Click "Run". Your bot is live!
🔹 Option B: Railway
- Go to railway.app and sign in via GitHub.
- Create a GitHub repo with these files:
bot.py
requirements.txt
:python-telegram-bot==20.4
- Connect the repo to Railway, deploy it.
- Set an environment variable in Railway:
BOT_TOKEN = your_bot_token_here
- Modify your Python code to use:
import os TOKEN = os.getenv("BOT_TOKEN")
✅ Step 4: Keep Bot Awake (for Replit)
- Use UptimeRobot to ping your bot every 5 minutes.
- 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)