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

Building a lead-capturing Telegram bot is a high-ROI task. You need stability, data integrity, and a clean deployment pipeline. We will use aiogram (v3+) for the bot logic and gspread for Google Sheets integration.


Architecture and Prerequisites

  • Framework: aiogram (asynchronous, robust).
  • Database/Storage: Google Sheets (via Google Sheets API) for simplicity, or PostgreSQL for scale.
  • Deployment: Ubuntu 22.04+ VPS + systemd for process management.
  • Anti-Spam: Rate limiting via aiogram middleware.

Checklist

  • [ ] Telegram Bot Token (from @BotFather).
  • [ ] Google Cloud Project with "Google Sheets API" enabled.
  • [ ] Service Account JSON key file.
  • [ ] VPS with Python 3.10+ installed.

The Code Skeleton

Install dependencies: pip install aiogram gspread oauth2client.

bot.py

import asyncio
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
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# Setup Google Sheets
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open("Leads").sheet1

bot = Bot(token="YOUR_TOKEN")
dp = Dispatcher()

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

@dp.message(Command("start"))
async def start(message: types.Message):
    await message.answer("Welcome! Send /lead to start.")

@dp.message(Command("lead"))
async def start_lead(message: types.Message, state: FSMContext):
    await message.answer("Enter 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("Enter 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()
    # Save to Sheet
    sheet.append_row([data['name'], message.text, message.from_user.username])
    await message.answer("Saved! We will contact you soon.")
    await state.clear()

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

if __name__ == "__main__":
    asyncio.run(main())

Implementing Anti-Spam

To prevent flood attacks, implement a simple middleware in aiogram that tracks user IDs and timestamps.

from aiogram import BaseMiddleware
from time import time

class AntiSpamMiddleware(BaseMiddleware):
    def __init__(self):
        self.users = {}

    async def __call__(self, handler, event, data):
        user_id = event.from_user.id
        now = time()
        if user_id in self.users and now - self.users[user_id] < 1:
            return # Ignore message
        self.users[user_id] = now
        return await handler(event, data)

Register this in your dp object using dp.message.middleware(AntiSpamMiddleware()).


Deployment on VPS with Systemd

  1. Transfer files: Use scp or git clone to move your project to /opt/lead_bot.
  2. Create a Virtual Environment: bash python3 -m venv venv source venv/bin/activate pip install -r requirements.txt
  3. Create a Systemd service file: sudo nano /etc/systemd/system/leadbot.service
[Unit]
Description=Telegram Lead Bot
After=network.target

[Service]
User=root
WorkingDirectory=/opt/lead_bot
ExecStart=/opt/lead_bot/venv/bin/python bot.py
Restart=always

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

Common Pitfalls and Troubleshooting

1. Google Sheets API Quotas

Google has strict write limits. If you expect high volume, do not write to the sheet on every single message. Instead, use a local SQLite database to buffer leads and a background task (using asyncio.create_task) to sync to Google Sheets every 5 minutes.

2. State Persistence

By default, aiogram FSM stores states in memory. If your bot restarts, all users in the middle of a flow will lose their progress. For production, use RedisStorage to persist states across reboots.

3. Environment Variables

Never hardcode your tokens. Use a .env file and the python-dotenv library. If you commit your JSON key or token to GitHub, they will be stolen by bots within seconds.

4. Bot Blocking

If your bot sends too many messages to users who haven't interacted with it, Telegram will flag your account. Always use try/except blocks around bot.send_message to catch TelegramForbiddenError (when a user blocks the bot).

5. Timeouts

If your VPS is behind a restrictive firewall, ensure outbound traffic on port 443 is allowed, as Telegram's API relies on HTTPS.


Scaling Advice

Once your bot grows: * Database: Move from Google Sheets to PostgreSQL. * Logging: Use the logging module to write to a file, and use journalctl -u leadbot -f to monitor the process in real-time. * Webhooks: If you move to a production environment with high traffic, switch from polling to webhooks to reduce latency and resource consumption.

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

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

Комментарии

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

Beyond the Sandbox: Why Paper Trading Lies and What to Actually Validate

Why Your European Amazon Store is Bleeding Cash (And It's Not the Demand)

Regime Detection: Why Your Strategy Fails and How to Spot the Shift