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
- Go to Google Cloud Console.
- Create a project and enable Google Sheets API and Google Drive API.
- Create a Service Account, download the JSON key file, and rename it to
credentials.json. - Share your target Google Sheet with the
client_emailfound insidecredentials.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:
- Rate Limiting: Use
aiogrammiddleware to track user IDs in a local dictionary or Redis. If a user sends more than 5 messages in 10 seconds, ignore them. - Input Validation: Use regex to validate phone numbers. Don't trust user input.
- Bot Detection: Check
message.from_user.is_botto 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
.envfile andpython-dotenv. - [ ] Logging: Configure the
loggingmodule to write to a file, not just stdout. - [ ] Error Handling: Wrap your Google Sheets API calls in
try/exceptblocks 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=alwaysis set in your systemd file to handle unexpected crashes.
Common Mistakes to Avoid
- Blocking Operations: Never use
time.sleep()in anaiogrambot. It blocks the entire event loop. Useawait asyncio.sleep(). - Synchronous Sheets API:
gspreadis synchronous. For high-traffic bots, this will cause lag. Usegspread-asyncioto 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
Комментарии
Отправить комментарий