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
- Go to Google Cloud Console.
- Create a project, enable "Google Sheets API" and "Google Drive API".
- Create a Service Account, download the JSON key, and share your target Google Sheet with the
client_emailfound 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
- Transfer files: Use
scpto move your project folder to the VPS. - Virtual Environment:
bash python3 -m venv venv source venv/bin/activate pip install -r requirements.txt - 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
- Start the bot:
bash systemctl daemon-reload systemctl enable leadbot systemctl start leadbot
Checklist for Production
- [ ] Environment Variables: Never hardcode tokens. Use
.envfiles andpython-dotenv. - [ ] Logging: Configure
loggingto write to a file, not just stdout, so you can debug crashes. - [ ] Error Handling: Wrap Google Sheets API calls in
try/exceptblocks 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
.gitignorefile to ensurecredentials.jsonand.envare never pushed to GitHub.
Common Mistakes to Avoid
- Blocking IO: Never use
time.sleep()or synchronous requests (likerequestslibrary) inside anaiogramhandler. It will freeze the entire bot for all users. Always useawait. - 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'sFSMContext. - Hardcoding IDs: Never hardcode user IDs or sheet names. Use a config file.
- 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
exceptblocks to alert you of errors. - 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
aiogramupdated 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
Комментарии
Отправить комментарий