Creating a comprehensive Telegram bot that handles product listings, customer inquiries, payments, and marketing requires integrating multiple components. Below is a step-by-step guide with code snippets to help you build this bot using Python. We'll use python-telegram-bot for interacting with Telegram, BeautifulSoup for scraping, SQLite for the database, and integrate PayFast/Yoco for payments. Additionally, we'll incorporate basic NLP using Rasa for friendly interactions.
Prerequisites
- Python 3.7+ installed on your machine.
- Telegram Bot Token: Create a bot using BotFather and obtain the API token.
- PayFast/Yoco Account: Sign up and obtain API keys.
- Host Environment: For deployment, like Heroku, AWS, or any cloud service.
- Libraries: Install necessary Python libraries.
pip install python-telegram-bot==13.14 beautifulsoup4 requests sqlalchemy rasa
Project Structure
telegram_bot/
├── bot.py
├── scraper.py
├── database.py
├── payments.py
├── nlp/
│ ├── config.yml
│ ├── domain.yml
│ ├── nlu.yml
│ └── stories.yml
└── requirements.txt
1. Setting Up the Database
We'll use SQLAlchemy with SQLite for simplicity. Create a database.py file.
# database.py
from sqlalchemy import create_engine, Column, Integer, String, Float, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
Base = declarative_base()
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
name = Column(String)
description = Column(String)
price = Column(Float)
stock = Column(Integer)
image_url = Column(String)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
telegram_id = Column(String, unique=True)
cart = relationship("Cart", back_populates="user")
class Cart(Base):
__tablename__ = 'carts'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
items = Column(String) # JSON string of product IDs and quantities
user = relationship("User", back_populates="cart")
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
items = Column(String) # JSON string
total = Column(Float)
payment_status = Column(Boolean, default=False)
engine = create_engine('sqlite:///telegram_bot.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
2. Scraping the Yaga Store
Create a scraper.py file to scrape product data from your Yaga store using BeautifulSoup.
# scraper.py
import requests
from bs4 import BeautifulSoup
from database import Session, Product
def scrape_yaga_store():
session = Session()
url = 'https://your-yaga-store-url.com' # Replace with your Yaga store URL
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Example scraping logic - adjust selectors based on your store's HTML structure
products = soup.find_all('div', class_='product-item')
for prod in products:
name = prod.find('h2').text.strip()
description = prod.find('p', class_='description').text.strip()
price = float(prod.find('span', class_='price').text.strip().replace('$', ''))
stock = int(prod.find('span', class_='stock').text.strip())
image_url = prod.find('img')['src']
existing_product = session.query(Product).filter_by(name=name).first()
if not existing_product:
product = Product(
name=name,
description=description,
price=price,
stock=stock,
image_url=image_url
)
session.add(product)
session.commit()
session.close()
if __name__ == "__main__":
scrape_yaga_store()
Note: Schedule this script to run periodically (e.g., using cron) to keep your product data updated.
3. NLP Setup with Rasa
To handle friendly and helpful responses, set up Rasa for NLP. This involves configuring Rasa's training data and models.
a. Initialize Rasa
Navigate to the nlp/ directory and initialize Rasa.
cd nlp
rasa init
Follow the prompts to set up a basic Rasa project. Customize the nlu.yml, domain.yml, and stories.yml files to handle your specific intents and entities related to your products.
b. Train Rasa Model
rasa train
c. Start Rasa Server
Run the Rasa server so your bot can communicate with it.
rasa run --enable-api --model models/
4. Payment Gateway Integration
Create a payments.py file to handle PayFast/Yoco integrations. Below is a placeholder for PayFast integration.
# payments.py
import requests
PAYFAST_MERCHANT_ID = 'your_merchant_id'
PAYFAST_RETURN_URL = 'https://yourdomain.com/payment/return'
PAYFAST_NOTIFY_URL = 'https://yourdomain.com/payment/notify'
PAYFAST_SECRET_KEY = 'your_secret_key' # Needed for validating notifications
def create_payfast_payment(order_id, amount, item_description):
data = {
'merchant_id': PAYFAST_MERCHANT_ID,
'return_url': PAYFAST_RETURN_URL,
'cancel_url': 'https://yourdomain.com/payment/cancel',
'notify_url': PAYFAST_NOTIFY_URL,
'm_payment_id': order_id,
'amount': amount,
'item_name': item_description,
'currency': 'ZAR'
}
# PayFast uses form-based POST; here we could generate the payment link
payment_url = 'https://www.payfast.co.za/eng/process?' + '&'.join([f"{k}={v}" for k, v in data.items()])
return payment_url
def validate_payfast_notification(params):
# Implement validation logic based on PayFast's documentation
# Typically involves verifying the signature using the secret key
pass
# Similarly, implement Yoco integration as needed
5. Telegram Bot Implementation
Create a bot.py file that ties everything together.
# bot.py
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
CallbackContext,
CallbackQueryHandler
)
from database import Session, User, Product, Cart, Order
from scraper.py import scrape_yaga_store
from payments import create_payfast_payment
import json
import requests
# Configure logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Initialize Rasa endpoint
RASA_ENDPOINT = 'http://localhost:5005/webhooks/rest/webhook'
def start(update: Update, context: CallbackContext):
user = update.message.from_user
session_db = Session()
db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
if not db_user:
db_user = User(telegram_id=str(user.id))
session_db.add(db_user)
session_db.commit()
session_db.close()
update.message.reply_text(
"Welcome to our store! How can I assist you today? Type /help to see available commands."
)
def help_command(update: Update, context: CallbackContext):
help_text = (
"/start - Start interacting with the bot\n"
"/products - View available products\n"
"/cart - View your cart\n"
"/checkout - Proceed to checkout\n"
"/help - Show this help message"
)
update.message.reply_text(help_text)
def products(update: Update, context: CallbackContext):
session_db = Session()
products = session_db.query(Product).all()
session_db.close()
for product in products:
keyboard = [
[InlineKeyboardButton("Add to Cart", callback_data=f"add_{product.id}")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_photo(
photo=product.image_url,
caption=f"*{product.name}*\n{product.description}\nPrice: R{product.price}",
parse_mode='Markdown',
reply_markup=reply_markup
)
def button(update: Update, context: CallbackContext):
query = update.callback_query
query.answer()
data = query.data
if data.startswith("add_"):
product_id = int(data.split("_")[1])
user = query.from_user
session_db = Session()
db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
cart = session_db.query(Cart).filter_by(user_id=db_user.id).first()
if not cart:
cart = Cart(user_id=db_user.id, items=json.dumps({}))
session_db.add(cart)
cart_items = json.loads(cart.items)
cart_items[str(product_id)] = cart_items.get(str(product_id), 0) + 1
cart.items = json.dumps(cart_items)
session_db.commit()
session_db.close()
query.edit_message_text(text="Item added to your cart.")
elif data.startswith("remove_"):
# Implement remove functionality
pass
def view_cart(update: Update, context: CallbackContext):
user = update.message.from_user
session_db = Session()
db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
cart = session_db.query(Cart).filter_by(user_id=db_user.id).first()
if not cart or not cart.items:
update.message.reply_text("Your cart is empty.")
session_db.close()
return
cart_items = json.loads(cart.items)
message = "Your Cart:\n"
total = 0
for product_id, quantity in cart_items.items():
product = session_db.query(Product).filter_by(id=int(product_id)).first()
if product:
message += f"{product.name} x{quantity} - R{product.price * quantity}\n"
total += product.price * quantity
message += f"\nTotal: R{total}"
keyboard = [
[InlineKeyboardButton("Checkout", callback_data="checkout")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(message, reply_markup=reply_markup)
session_db.close()
def checkout(update: Update, context: CallbackContext):
query = update.callback_query
query.answer()
user = query.from_user
session_db = Session()
db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
cart = session_db.query(Cart).filter_by(user_id=db_user.id).first()
if not cart or not cart.items:
query.edit_message_text(text="Your cart is empty.")
session_db.close()
return
cart_items = json.loads(cart.items)
total = 0
item_description = ""
for product_id, quantity in cart_items.items():
product = session_db.query(Product).filter_by(id=int(product_id)).first()
if product:
total += product.price * quantity
item_description += f"{product.name} x{quantity}, "
payment_link = create_payfast_payment(order_id=str(db_user.id), amount=total, item_description=item_description)
order = Order(
user_id=db_user.id,
items=json.dumps(cart_items),
total=total,
payment_status=False
)
session_db.add(order)
session_db.commit()
query.edit_message_text(text=f"Please complete your payment here: {payment_link}")
session_db.close()
def handle_message(update: Update, context: CallbackContext):
user_message = update.message.text
# Send message to Rasa for NLP processing
response = requests.post(RASA_ENDPOINT, json={"message": user_message})
if response.status_code == 200:
data = response.json()
if data:
bot_reply = data[0].get('text', "I'm not sure how to respond to that.")
update.message.reply_text(bot_reply)
else:
update.message.reply_text("I'm not sure how to respond to that.")
else:
update.message.reply_text("Sorry, I'm having trouble understanding you right now.")
def main():
# Replace 'YOUR_TELEGRAM_BOT_TOKEN' with your actual token
updater = Updater("YOUR_TELEGRAM_BOT_TOKEN", use_context=True)
dispatcher = updater.dispatcher
# Handlers
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help_command))
dispatcher.add_handler(CommandHandler("products", products))
dispatcher.add_handler(CommandHandler("cart", view_cart))
dispatcher.add_handler(CallbackQueryHandler(button))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_message))
# Start the Bot
updater.start_polling()
# Start scraping periodically (e.g., every 6 hours)
import threading
import time
def periodic_scrape():
while True:
scrape_yaga_store()
time.sleep(6 * 60 * 60) # 6 hours
scrape_thread = threading.Thread(target=periodic_scrape, daemon=True)
scrape_thread.start()
updater.idle()
if __name__ == '__main__':
main()
6. Marketing Automation
To implement marketing automation like broadcasting promotions and retargeting, you can add scheduled tasks that send messages to all users or specific segments based on their interactions.
a. Broadcasting Promotions
Add a function in bot.py to broadcast messages.
def broadcast_promotion(context: CallbackContext):
session_db = Session()
users = session_db.query(User).all()
for user in users:
try:
context.bot.send_message(chat_id=user.telegram_id, text="Check out our latest discounts!")
except Exception as e:
logger.error(f"Error sending message to {user.telegram_id}: {e}")
session_db.close()
b. Scheduling the Broadcast
Use JobQueue to schedule periodic broadcasts.
In the main() function, add:
# Schedule a daily promotion at 9 AM
from datetime import time
job_queue = updater.job_queue
job_queue.run_daily(
broadcast_promotion,
time=time(hour=9, minute=0, second=0)
)
c. Customer Retargeting
Implement retargeting by tracking user interactions and sending personalized messages. This requires more advanced logic, such as analyzing user behavior and determining when to send retargeting messages.
7. Deploying the Bot
To ensure your bot runs 24/7, deploy it to a cloud service like Heroku. Below are the basic steps for deploying to Heroku.
a. Create Procfile
Create a Procfile in your project root.
worker: python bot.py
b. Create requirements.txt
Ensure all dependencies are listed.
python-telegram-bot==13.14
beautifulsoup4
requests
sqlalchemy
rasa
# Add other dependencies as needed
c. Deploy to Heroku
- Initialize Git Repository
git init
git add .
git commit -m "Initial commit"
- Create Heroku App
heroku create your-app-name
- Deploy
git push heroku master
- Configure Environment Variables
Set your Telegram bot token and payment gateway keys as environment variables.
heroku config:set TELEGRAM_TOKEN=your_token PAYFAST_MERCHANT_ID=your_id PAYFAST_SECRET_KEY=your_secret
d. Ensure Rasa Server is Running
You need to deploy the Rasa server alongside your bot or use a separate service. Alternatively, integrate Rasa as part of your deployed application.
8. Example Workflow
-
Inquiry
- User: "Hi, do you have any sneakers?"
- Bot: Parses the message via Rasa, understands "sneakers" intent.
- Bot: Lists available sneakers from the database.
-
Add to Cart
- User: Clicks "Add to Cart" on a sneaker.
- Bot: Adds the item to the user's cart and confirms.
-
Checkout
- User: Types
/checkout
- Bot: Generates a PayFast payment link and sends it.
-
Confirmation
- User: Completes payment via PayFast.
- Bot: Receives webhook notification, updates order status, and sends confirmation message.
Additional Tips
-
Security: Never hard-code sensitive information like API tokens or secrets in your code. Use environment variables or a secure secrets manager.
-
Webhooks vs. Polling: For better efficiency and scalability, especially in production, consider using webhooks instead of long polling.
-
Error Handling: Implement robust error handling to manage exceptions and ensure the bot doesn't crash unexpectedly.
-
Scalability: For a larger user base, consider migrating from SQLite to a more robust database like PostgreSQL.
-
Testing: Thoroughly test each component individually before integrating to ensure stability.
Resources
By following this guide and customizing each component according to your specific needs and Yaga store structure, you'll be able to create a fully functional Telegram bot that can handle selling products, managing customer inquiries, processing payments, and executing marketing strategies.