Creating a Telegram bot with the described functionality is a comprehensive project that involves several components, including user interaction via Telegram (and potentially Discord), parsing data from Upwork, managing user filters and groups, sending notifications, and ensuring reliability and scalability. Below is a detailed guide to help you implement this bot, covering architecture, technologies, and sample code snippets to get you started.
Table of Contents
- Technology Stack
- Project Setup
- Bot Architecture Overview
- Database Design
- Core Components Implementation
- Platform Adapters
- Ensuring Reliability
- Deployment Considerations
- Sample Code Snippets
- Additional Resources
Technology Stack
- Programming Language: Python (recommended for its rich ecosystem and libraries)
- Telegram API: python-telegram-bot
- Discord API: discord.py
- Database: MongoDB (primary), Redis (caching)
- Web Scraping: BeautifulSoup, Scrapy, or Upwork's API (if available)
- Asynchronous Task Processing: Celery with RabbitMQ or Redis as a broker
- Deployment: Docker, Kubernetes (optional for scalability)
- Backup and Monitoring: Implement backup strategies and use monitoring tools like Prometheus & Grafana
Project Setup
-
Initialize the Project Repository:
mkdir upwork_telegram_bot
cd upwork_telegram_bot
git init
-
Create a Virtual Environment:
python3 -m venv venv
source venv/bin/activate
-
Create requirements.txt:
python-telegram-bot==13.15
discord.py==2.0.1
pymongo==4.2.0
redis==4.5.4
celery==5.2.7
beautifulsoup4==4.11.1
requests==2.28.1
Install dependencies:
pip install -r requirements.txt
-
Project Structure:
Following the structure you provided:
upwork_telegram_bot/
├── core/
│ ├── filters.py
│ ├── upwork_parser.py
│ ├── notifications.py
│ ├── group_manager.py
│ └── utils.py
├── telegram_adapter/
│ ├── main.py
│ ├── handlers.py
│ ├── telegram_api.py
│ └── buttons.py
├── discord_adapter/
│ ├── main.py
│ ├── handlers.py
│ ├── discord_api.py
│ └── buttons.py
├── db/
│ ├── database.py
│ ├── users.py
│ ├── orders.py
│ └── groups.py
├── config.py
└── requirements.txt
Bot Architecture Overview
The bot is designed with a clear separation of concerns, ensuring that the core logic is platform-agnostic, while adapters handle platform-specific interactions. Here's a high-level overview:
-
Core Logic (core/):
- filters.py: Manages filter creation, updating, and validation.
- upwork_parser.py: Handles scraping or API interactions with Upwork to fetch orders.
- notifications.py: Manages the notification logic, ensuring users receive relevant updates.
- group_manager.py: Handles grouping of users based on their filter settings.
- utils.py: Contains helper functions used across the core components.
-
Platform Adapters (telegram_adapter/ & discord_adapter/):
- main.py: Entry point for each platform.
- handlers.py: Contains event handlers for commands and interactions.
- [platform]_api.py: Interface with the respective platform's API.
- buttons.py: Generates platform-specific interactive elements.
-
Database Layer (db/):
- database.py: Handles database connections and configurations.
- users.py: CRUD operations for user data.
- orders.py: CRUD operations for order data.
- groups.py: CRUD operations for group data.
-
Configuration (config.py):
- Stores API keys, database URLs, and other configurations.
Database Design
As outlined, MongoDB is suitable for this application due to its flexibility with document structures. Here's a refined schema:
-
Users Collection (users):
{
"_id": "123456789",
"platform": "telegram",
"username": "JohnDoe",
"filters": {
"category": "Design",
"budget_min": 100,
"experience_level": "Intermediate",
"job_type": "Fixed Price",
"client_location": ["USA", "UK"],
"skills": ["Photoshop"],
"language": ["English"],
"payment_verification": true
},
"group_id": "group_1",
"notifications_enabled": true,
"last_activity": "2024-11-17T10:00:00Z"
}
-
Groups Collection (groups):
{
"_id": "group_1",
"filters": {
"category": "Design",
"budget_min": 100,
"experience_level": "Intermediate",
"job_type": "Fixed Price",
"client_location": ["USA", "UK"],
"skills": ["Photoshop"],
"language": ["English"],
"payment_verification": true
},
"user_ids": ["123456789", "987654321"],
"parsing_active": true,
"created_at": "2024-11-16T09:00:00Z",
"last_parsed": "2024-11-17T10:00:00Z"
}
-
Orders Collection (orders):
{
"_id": "order_987654321",
"group_id": "group_1",
"title": "Create a logo design",
"description": "We need a creative logo...",
"budget": 500,
"type": "Fixed Price",
"client": {
"name": "JaneDoe",
"profile_url": "https://upwork.com/profile/12345",
"spent": 2000
},
"skills": ["Photoshop", "Design"],
"created_at": "2024-11-17T09:00:00Z",
"expires_at": "2024-11-18T09:00:00Z",
"order_url": "https://upwork.com/job/12345"
}
-
Notifications Log Collection (notifications_log):
{
"user_id": "123456789",
"order_id": "order_987654321",
"sent_at": "2024-11-17T10:05:00Z"
}
Indexes:
Ensure that you create indexes on frequently queried fields to optimize performance.
db.users.createIndex({ "_id": 1 });
db.groups.createIndex({ "filters.category": 1, "filters.budget_min": 1 });
db.orders.createIndex({ "group_id": 1, "created_at": 1 });
db.notifications_log.createIndex({ "user_id": 1, "order_id": 1 });
Core Components Implementation
Filters Management (core/filters.py)
Manage creation, validation, and application of filters.
# core/filters.py
from typing import Dict, Any
class Filters:
VALID_CATEGORIES = ["Design & Creative", "Development", "Marketing & Advertising"]
# Define other valid options...
def validate_filters(self, filters: Dict[str, Any]) -> bool:
# Implement validation logic
pass
def apply_filters(self, order: Dict[str, Any], filters: Dict[str, Any]) -> bool:
# Implement logic to determine if an order matches the filters
pass
Upwork Parser (core/upwork_parser.py)
Handles fetching data from Upwork. If Upwork provides an API, use it; otherwise, implement web scraping.
# core/upwork_parser.py
import requests
from bs4 import BeautifulSoup
from typing import List, Dict
class UpworkParser:
def __init__(self, filters: Dict[str, Any]):
self.filters = filters
def fetch_orders(self) -> List[Dict[str, Any]]:
# Implement API calls or web scraping to retrieve orders based on filters
orders = []
# Example using requests and BeautifulSoup
response = requests.get("https://www.upwork.com/ab/jobs/search/", params=self.filters)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
# Parse the HTML to extract order details
# Populate the 'orders' list
return orders
def parse_order(self, html) -> Dict[str, Any]:
# Implement parsing logic for a single order
pass
User and Group Management (core/group_manager.py)
Handles user groups based on filter similarity.
# core/group_manager.py
from db.groups import GroupsDB
from db.users import UsersDB
class GroupManager:
def __init__(self):
self.groups_db = GroupsDB()
def find_or_create_group(self, user_filters: Dict[str, Any]) -> str:
group = self.groups_db.find_group_by_filters(user_filters)
if group:
return group['_id']
else:
new_group_id = self.groups_db.create_group(user_filters)
return new_group_id
def add_user_to_group(self, user_id: str, group_id: str):
self.groups_db.add_user(group_id, user_id)
Notifications System (core/notifications.py)
Manages sending notifications to users.
# core/notifications.py
from db.orders import OrdersDB
from db.notifications_log import NotificationsLogDB
from db.users import UsersDB
from telegram_adapter.telegram_api import TelegramAPI
class Notifications:
def __init__(self):
self.orders_db = OrdersDB()
self.notifications_log_db = NotificationsLogDB()
self.users_db = UsersDB()
self.telegram_api = TelegramAPI()
def send_new_order_notifications(self, order: Dict[str, Any]):
group_id = order['group_id']
users = self.users_db.get_users_by_group(group_id, notifications_enabled=True)
for user in users:
if not self.notifications_log_db.is_notified(user['_id'], order['_id']):
message = self.format_message(order)
self.telegram_api.send_message(user['platform_id'], message)
self.notifications_log_db.log_notification(user['_id'], order['_id'])
def format_message(self, order: Dict[str, Any]) -> str:
return (
f"**{order['title']}**\n"
f"{order['description']}\n"
f"Budget: ${order['budget']}\n"
f"Type: {order['type']}\n"
f"Client: {order['client']['name']}\n"
f"[Profile]({order['client']['profile_url']})\n"
f"Total Spent: ${order['client']['spent']}\n"
f"[View Order]({order['order_url']})"
)
Platform Adapters
Telegram Adapter (telegram_adapter/)
Handles all Telegram-specific interactions.
# telegram_adapter/main.py
from telegram.ext import Updater
from handlers import setup_handlers
from config import TELEGRAM_TOKEN
def main():
updater = Updater(token=TELEGRAM_TOKEN, use_context=True)
dispatcher = updater.dispatcher
setup_handlers(dispatcher)
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
- telegram_adapter/handlers.py
# telegram_adapter/handlers.py
from telegram import Update
from telegram.ext import CallbackContext, CommandHandler, CallbackQueryHandler
from telegram_adapter.buttons import create_start_buttons, create_filter_buttons
def start(update: Update, context: CallbackContext):
user = update.effective_user
# Send welcome message with Start button
update.message.reply_text(
"Welcome to Upwork Order Finder Bot! Press 'Start' to begin.",
reply_markup=create_start_buttons()
)
def handle_start_button(update: Update, context: CallbackContext):
query = update.callback_query
query.answer()
# Send description and prompt to customize filters
query.edit_message_text(
"Customize your search settings by selecting filters below:",
reply_markup=create_filter_buttons()
)
def setup_handlers(dispatcher):
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CallbackQueryHandler(handle_start_button, pattern='^start$'))
# Add more handlers for filter selections and other interactions
- telegram_adapter/buttons.py
# telegram_adapter/buttons.py
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
def create_start_buttons():
keyboard = [
[InlineKeyboardButton("Start", callback_data='start')]
]
return InlineKeyboardMarkup(keyboard)
def create_filter_buttons():
keyboard = [
[InlineKeyboardButton("Category", callback_data='filter_category')],
[InlineKeyboardButton("Budget", callback_data='filter_budget')],
# Add other filter buttons
]
return InlineKeyboardMarkup(keyboard)
- telegram_adapter/telegram_api.py
# telegram_adapter/telegram_api.py
from telegram import Bot
from config import TELEGRAM_TOKEN
class TelegramAPI:
def __init__(self):
self.bot = Bot(token=TELEGRAM_TOKEN)
def send_message(self, chat_id: str, text: str, parse_mode='Markdown', reply_markup=None):
self.bot.send_message(
chat_id=chat_id,
text=text,
parse_mode=parse_mode,
reply_markup=reply_markup
)
Discord Adapter (discord_adapter/)
Similar to the Telegram adapter but using discord.py.
# discord_adapter/main.py
import discord
from discord.ext import commands
from handlers import setup_handlers
from config import DISCORD_TOKEN
def main():
bot = commands.Bot(command_prefix="/")
setup_handlers(bot)
bot.run(DISCORD_TOKEN)
if __name__ == "__main__":
main()
- discord_adapter/handlers.py
# discord_adapter/handlers.py
from discord.ext import commands
from discord import Embed, Button, View
def setup_handlers(bot):
@bot.command(name='start')
async def start(ctx):
embed = Embed(title="Welcome to Upwork Order Finder Bot!", description="Press Start to begin.")
view = View()
view.add_item(Button(label="Start", custom_id="start_button"))
await ctx.send(embed=embed, view=view)
@bot.event
async def on_interaction(interaction):
if interaction.data['custom_id'] == 'start_button':
await interaction.response.edit_message(
content="Customize your search settings by selecting filters below.",
view=FilterView()
)
class FilterView(View):
def __init__(self):
super().__init__()
self.add_item(Button(label="Category", custom_id="filter_category"))
self.add_item(Button(label="Budget", custom_id="filter_budget"))
# Add other filter buttons
- discord_adapter/discord_api.py
# discord_adapter/discord_api.py
# Similar to telegram_api.py but using discord.py's API
Ensuring Reliability
-
Duplicate Notifications:
- Use
notifications_log to track sent notifications.
- Before sending, check if the
(user_id, order_id) pair exists.
-
Backup and Migration:
- Deploy the bot using containerization (Docker).
- Use orchestration tools like Kubernetes for automatic failover.
- Regularly back up the MongoDB database.
- Implement retry mechanisms for failed tasks.
-
Asynchronous Processing:
- Use Celery for handling parsing and notification tasks.
- This ensures that your bot remains responsive.
-
Caching with Redis:
- Cache parsed data to reduce latency.
- Store frequently accessed data to speed up operations.
Deployment Considerations
-
Hosting:
- Choose a reliable cloud provider (AWS, Google Cloud, Azure).
- Ensure scalability to handle increasing users and data.
-
Environment Variables:
- Store sensitive information like API tokens in environment variables.
- Use tools like
dotenv to manage environment configurations.
-
Monitoring and Logging:
- Implement logging using Python's
logging module.
- Use monitoring tools to keep track of bot performance and uptime.
-
Continuous Integration/Continuous Deployment (CI/CD):
- Set up pipelines to automate testing and deployment.
Sample Code Snippets
Setting Up the Project Structure
upwork_telegram_bot/
├── core/
│ ├── filters.py
│ ├── upwork_parser.py
│ ├── notifications.py
│ ├── group_manager.py
│ └── utils.py
├── telegram_adapter/
│ ├── main.py
│ ├── handlers.py
│ ├── telegram_api.py
│ └── buttons.py
├── discord_adapter/
│ ├── main.py
│ ├── handlers.py
│ ├── discord_api.py
│ └── buttons.py
├── db/
│ ├── database.py
│ ├── users.py
│ ├── orders.py
│ └── groups.py
├── config.py
└── requirements.txt
Telegram Adapter Example
# telegram_adapter/handlers.py
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackContext
from db.users import UsersDB
from core.group_manager import GroupManager
users_db = UsersDB()
group_manager = GroupManager()
def handle_filter_selection(update: Update, context: CallbackContext):
query = update.callback_query
query.answer()
selected_filter = query.data # e.g., 'filter_category'
# Based on the filter selected, prompt user for input
# For simplicity, let's assume it's category selection
if selected_filter == 'filter_category':
keyboard = [
[InlineKeyboardButton("Design & Creative", callback_data='category_design')],
[InlineKeyboardButton("Development", callback_data='category_development')],
[InlineKeyboardButton("Marketing & Advertising", callback_data='category_marketing')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="Select a category:",
reply_markup=reply_markup
)
# Handle other filters similarly
def handle_category_selection(update: Update, context: CallbackContext):
query = update.callback_query
query.answer()
category = query.data.replace('category_', '').replace('_', ' ').title()
user_id = query.from_user.id
users_db.update_user_filter(user_id, 'category', category)
# Check if all filters are set; if not, prompt next filter
# If all set, find or create group and confirm setup
group_id = group_manager.find_or_create_group(users_db.get_user_filters(user_id))
users_db.update_user_group(user_id, group_id)
query.edit_message_text(
text=f"Filters updated! You have been added to group {group_id}. You will receive notifications for new orders."
)
Upwork Parser Skeleton
# core/upwork_parser.py
import asyncio
from db.groups import GroupsDB
from db.orders import OrdersDB
from core.filters import Filters
from core.notifications import Notifications
class UpworkParser:
def __init__(self):
self.groups_db = GroupsDB()
self.orders_db = OrdersDB()
self.filters = Filters()
self.notifications = Notifications()
async def parse_and_notify(self):
active_groups = self.groups_db.get_active_groups()
for group in active_groups:
orders = self.fetch_orders(group.filters)
for order in orders:
if self.filters.apply_filters(order, group.filters):
self.orders_db.save_order(order)
await self.notifications.send_new_order_notifications(order)
def fetch_orders(self, filters):
# Implement fetching logic (API or scraping)
pass
Notification Logic
# core/notifications.py
from db.users import UsersDB
from db.notifications_log import NotificationsLogDB
from telegram_adapter.telegram_api import TelegramAPI
class Notifications:
def __init__(self):
self.users_db = UsersDB()
self.notifications_log_db = NotificationsLogDB()
self.telegram_api = TelegramAPI()
def send_new_order_notifications(self, order):
group_id = order['group_id']
users = self.users_db.get_users_by_group(group_id, notifications_enabled=True)
for user in users:
if not self.notifications_log_db.is_order_notified(user['_id'], order['_id']):
message = self.format_order_message(order)
self.telegram_api.send_message(user['id'], message)
self.notifications_log_db.log_notification(user['_id'], order['_id'])
def format_order_message(self, order):
return (
f"**{order['title']}**\n"
f"{order['description']}\n"
f"Budget: ${order['budget']}\n"
f"Type: {order['type']}\n"
f"Client: {order['client']['name']}\n"
f"[Profile]({order['client']['profile_url']})\n"
f"Total Spent: ${order['client']['spent']}\n"
f"[View Order]({order['order_url']})"
)
Additional Resources
Conclusion
Building a Telegram (and Discord) bot with the described functionality involves multiple layers, including user interaction, data parsing, database management, and notifications. By following the outlined architecture and leveraging the provided code snippets, you can methodically develop each component. Ensure to test each part thoroughly and implement robust error handling to maintain reliability. Additionally, consider scalability from the outset to accommodate a growing user base.
Feel free to reach out with specific questions or for further clarification on any of the components!