How to Build a Telegram Bot That Captures Leads 24/7

Building a lead-capturing Telegram bot is a high-ROI task. You automate the qualification process, store data structured, and reduce friction for the client. We will use aiogram 3.x for its asynchronous performance and gspread for Google Sheets integration.

Prerequisites and Tech Stack

  • Language: Python 3.10+
  • Library: aiogram (Bot API)
  • Database: Google Sheets API (Free, easy for clients to view)
  • Hosting: Ubuntu 22.04 VPS
  • Process Manager: systemd

Step 1: Project Setup and Google Sheets API

  1. Go to Google Cloud Console.
  2. Create a project, enable "Google Sheets API" and "Google Drive API".
  3. Create a Service Account, download the JSON key, and share your target Google Sheet with the client_email found in that JSON.

Step 2: Bot Code Skeleton

Install dependencies: pip install aiogram gspread oauth2client

import asyncio
import logging
import gspread
from aiogram import Bot, Dispatcher, types, F
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from oauth2client.service_account import ServiceAccountCredentials

# Configuration
API_TOKEN = 'YOUR_BOT_TOKEN'
gc = gspread.service_account(filename='credentials.json')
sheet = gc.open("Leads").sheet1

bot = Bot(token=API_TOKEN)
dp = Dispatcher()

class LeadForm(StatesGroup):
    name = State()
    phone = State()

@dp.message(Command("start"))
async def cmd_start(message: types.Message, state: FSMContext):
    await message.answer("Hello! What is your name?")
    await state.set_state(LeadForm.name)

@dp.message(LeadForm.name)
async def process_name(message: types.Message, state: FSMContext):
    await state.update_data(name=message.text)
    await message.answer("Great! Now send your phone number.")
    await state.set_state(LeadForm.phone)

@dp.message(LeadForm.phone)
async def process_phone(message: types.Message, state: FSMContext):
    data = await state.get_data()
    # Anti-spam/Validation logic here
    sheet.append_row([data['name'], message.text, message.from_user.username])
    await message.answer("Thanks! We will contact you soon.")
    await state.clear()

async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

Step 3: Anti-Spam Measures

Don't rely on basic input. Implement: 1. Rate Limiting: Use aiogram middleware to restrict users to 1 request per 5 seconds. 2. Phone Validation: Use phonenumbers library to verify if the input is a real format. 3. Button Constraints: Use ReplyKeyboardMarkup or InlineKeyboardMarkup to force users to click "Share Contact" instead of typing text. This prevents manual spam entries.

Step 4: Deployment on VPS

  1. Transfer files: Use scp to move your project folder to the VPS.
  2. Virtual Environment: bash python3 -m venv venv source venv/bin/activate pip install -r requirements.txt
  3. Create systemd service: Create /etc/systemd/system/leadbot.service:
[Unit]
Description=Telegram Lead Bot
After=network.target

[Service]
User=root
WorkingDirectory=/root/leadbot
ExecStart=/root/leadbot/venv/bin/python main.py
Restart=always

[Install]
WantedBy=multi-user.target
  1. Start the bot: bash systemctl daemon-reload systemctl enable leadbot systemctl start leadbot

Checklist for Production

  • [ ] Environment Variables: Never hardcode tokens. Use .env files and python-dotenv.
  • [ ] Logging: Configure logging to write to a file, not just stdout, so you can debug crashes.
  • [ ] Error Handling: Wrap Google Sheets API calls in try/except blocks to prevent the bot from dying if the sheet is locked or API quotas are hit.
  • [ ] Graceful Shutdown: Ensure the bot finishes current tasks before stopping.
  • [ ] Security: Use a .gitignore file to ensure credentials.json and .env are never pushed to GitHub.

Common Mistakes to Avoid

  1. Blocking IO: Never use time.sleep() or synchronous requests (like requests library) inside an aiogram handler. It will freeze the entire bot for all users. Always use await.
  2. Ignoring FSM: Beginners often try to manage state with global variables. This fails as soon as two people use the bot at the same time. Use aiogram's FSMContext.
  3. Hardcoding IDs: Never hardcode user IDs or sheet names. Use a config file.
  4. No Monitoring: If your bot crashes on the VPS, you won't know until a client complains. Set up a simple Telegram notification in your except blocks to alert you of errors.
  5. Over-complicating: Don't build a full CRM inside the bot if you can just push to Google Sheets or Zapier. Keep the bot as a "Frontend" and use existing tools for the "Backend."

Maintenance Strategy

  • Logs: Check logs weekly: journalctl -u leadbot -f.
  • Updates: Keep aiogram updated to receive security patches.
  • Backups: Google Sheets is your database. Export it as CSV periodically.

Need this done for you? Hire me on Freelancehunt: https://freelancehunt.com/freelancer/sspoisk

Originally posted at https://guardlabs.online/care/

Комментарии

Популярные сообщения из этого блога

You Rank #1 on Google. ChatGPT Still Tells Buyers You’re Obsolete.

I shipped a 12-question crypto security audit in 2 hours

Engineering the Invisible — what most SaaS teams miss