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

Building a lead-capturing Telegram bot requires a robust architecture to ensure data integrity and uptime. We will use aiogram (the industry standard for asynchronous Telegram bots in Python) and Google Sheets API as a lightweight CRM.

Prerequisites and Setup

You need a VPS running Ubuntu 22.04+, Python 3.10+, and a Telegram Bot Token from @BotFather.

1. Google Sheets API Setup

  1. Go to Google Cloud Console.
  2. Create a project and enable Google Sheets API and Google Drive API.
  3. Create a Service Account, download the JSON key file, and rename it to credentials.json.
  4. Share your target Google Sheet with the client_email found inside credentials.json.

Code Skeleton

Install dependencies: pip install aiogram gspread oauth2client

Main Bot Logic (bot.py)

import asyncio
import logging
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('credentials.json', scope)
client = gspread.authorize(creds)
sheet = client.open("LeadsSheet").sheet1

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

class LeadForm(StatesGroup):
    waiting_for_name = State()
    waiting_for_phone = State()

@dp.message(Command("start"))
async def start(message: types.Message, state: FSMContext):
    await message.answer("Welcome! Click below to start lead capture.", 
                         reply_markup=types.InlineKeyboardMarkup(inline_keyboard=[
                             [types.InlineKeyboardButton(text="Capture Lead", callback_data="start_lead")]
                         ]))

@dp.callback_query(F.data == "start_lead")
async def start_lead(callback: types.CallbackQuery, state: FSMContext):
    await callback.message.answer("Enter your name:")
    await state.set_state(LeadForm.waiting_for_name)

@dp.message(LeadForm.waiting_for_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.waiting_for_phone)

@dp.message(LeadForm.waiting_for_phone)
async def process_phone(message: types.Message, state: FSMContext):
    data = await state.get_data()
    sheet.append_row([data['name'], message.text, message.from_user.username])
    await message.answer("Lead saved successfully!")
    await state.clear()

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

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

Anti-Spam Measures

A common mistake is leaving a bot open to abuse. Implement these three layers:

  1. Rate Limiting: Use aiogram middleware to track user IDs in a local dictionary or Redis. If a user sends more than 5 messages in 10 seconds, ignore them.
  2. Input Validation: Use regex to validate phone numbers. Don't trust user input.
  3. Bot Detection: Check message.from_user.is_bot to ensure you aren't capturing data from other automated scripts.

Deployment on VPS with Systemd

Running python bot.py in the terminal will kill your bot when you close the SSH session. Use systemd for process management.

1. Create the Service File

Create /etc/systemd/system/telegram_bot.service:

[Unit]
Description=Telegram Lead Bot
After=network.target

[Service]
User=root
WorkingDirectory=/root/my_bot
ExecStart=/usr/bin/python3 /root/my_bot/bot.py
Restart=always

[Install]
WantedBy=multi-user.target

2. Enable and Start

systemctl daemon-reload
systemctl enable telegram_bot
systemctl start telegram_bot

Checklist for Production

  • [ ] Environment Variables: Never hardcode your token. Use a .env file and python-dotenv.
  • [ ] Logging: Configure the logging module to write to a file, not just stdout.
  • [ ] Error Handling: Wrap your Google Sheets API calls in try/except blocks to prevent the bot from crashing if the API is down.
  • [ ] Permissions: Ensure your VPS user has restricted access to the directory containing credentials.json.
  • [ ] Restart Policy: Ensure Restart=always is set in your systemd file to handle unexpected crashes.

Common Mistakes to Avoid

  • Blocking Operations: Never use time.sleep() in an aiogram bot. It blocks the entire event loop. Use await asyncio.sleep().
  • Synchronous Sheets API: gspread is synchronous. For high-traffic bots, this will cause lag. Use gspread-asyncio to prevent the bot from freezing while waiting for Google's servers.
  • Ignoring Updates: If your bot goes offline, it will process all missed updates when it reconnects. If you don't want this, clear the update queue on startup.
  • Hardcoding IDs: Use a database or a config file for Admin IDs. Never hardcode them in the source code.

Professional Summary

By following this architecture, you ensure that your lead generation process is automated, scalable, and resilient. The use of aiogram ensures high performance, while systemd ensures your bot stays alive 24/7.

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