Spaces:
Sleeping
Sleeping
File size: 8,466 Bytes
ba25022 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | #!/usr/bin/env python3
"""
Telegram Subscriber Manager
Automatically registers users who message the bot and allows them to subscribe to categories.
"""
import os
import json
import requests
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
SUBSCRIBERS_FILE = Path(__file__).parent / "telegram_subscribers.json"
class SubscriberManager:
def __init__(self):
self.bot_token = BOT_TOKEN
if not self.bot_token:
raise ValueError("TELEGRAM_BOT_TOKEN not found in .env")
self.base_url = f"https://api.telegram.org/bot{self.bot_token}"
self.subscribers = self.load_subscribers()
def load_subscribers(self):
"""Load subscribers from JSON file"""
if SUBSCRIBERS_FILE.exists():
with open(SUBSCRIBERS_FILE, 'r') as f:
return json.load(f)
return {}
def save_subscribers(self):
"""Save subscribers to JSON file"""
with open(SUBSCRIBERS_FILE, 'w') as f:
json.dump(self.subscribers, f, indent=2)
def get_updates(self, offset=None):
"""Get new messages from Telegram"""
url = f"{self.base_url}/getUpdates"
params = {"timeout": 30, "offset": offset}
response = requests.get(url, params=params, timeout=35)
return response.json()
def send_message(self, chat_id, text):
"""Send a message to a chat"""
url = f"{self.base_url}/sendMessage"
payload = {
"chat_id": chat_id,
"text": text,
"parse_mode": "HTML"
}
response = requests.post(url, json=payload, timeout=10)
return response.json()
def subscribe_user(self, chat_id, name, username, categories=None):
"""Subscribe a user to categories"""
if categories is None:
categories = ["NSE Live"] # Default to NSE Live
chat_id_str = str(chat_id)
self.subscribers[chat_id_str] = {
"name": name,
"username": username,
"categories": categories,
"active": True
}
self.save_subscribers()
return True
def unsubscribe_user(self, chat_id):
"""Unsubscribe a user"""
chat_id_str = str(chat_id)
if chat_id_str in self.subscribers:
self.subscribers[chat_id_str]["active"] = False
self.save_subscribers()
return True
return False
def get_active_subscribers(self, category=None):
"""Get all active subscribers, optionally filtered by category"""
active = {}
for chat_id, data in self.subscribers.items():
if data.get("active", True):
if category is None or category in data.get("categories", []):
active[chat_id] = data
return active
def process_message(self, message):
"""Process incoming message and handle commands"""
chat = message.get("chat", {})
chat_id = chat.get("id")
text = message.get("text", "").strip()
first_name = chat.get("first_name", "")
last_name = chat.get("last_name", "")
username = chat.get("username", "")
name = f"{first_name} {last_name}".strip() or username or "User"
# Handle commands
if text.startswith("/start"):
# Auto-subscribe to NSE Live
self.subscribe_user(chat_id, name, username, ["NSE Live"])
response = f"""
β
<b>Welcome to BiasBuster Trading Alerts!</b>
Hi {first_name}! You're now subscribed to <b>NSE Live</b> signals.
You'll receive alerts for:
β’ Nifty Future BUY/SELL signals
β’ Bank Nifty Future BUY/SELL signals
β’ TP/SL hit notifications
β’ Re-entry opportunities
<b>Commands:</b>
/status - Check your subscription
/categories - Change categories
/stop - Unsubscribe
<b>Your Chat ID:</b> {chat_id}
"""
self.send_message(chat_id, response)
return "subscribed"
elif text.startswith("/status"):
chat_id_str = str(chat_id)
if chat_id_str in self.subscribers:
sub = self.subscribers[chat_id_str]
categories = ", ".join(sub.get("categories", []))
status = "Active β
" if sub.get("active", True) else "Inactive β"
response = f"""
π <b>Your Subscription Status</b>
<b>Name:</b> {sub.get('name', 'Unknown')}
<b>Status:</b> {status}
<b>Categories:</b> {categories}
<b>Chat ID:</b> {chat_id}
Use /categories to change your subscriptions.
"""
else:
response = "You're not subscribed yet. Send /start to subscribe!"
self.send_message(chat_id, response)
return "status"
elif text.startswith("/categories"):
response = """
π <b>Available Categories:</b>
Reply with the number to subscribe:
1οΈβ£ NSE Live (Nifty & Bank Nifty Futures)
2οΈβ£ Forex (EUR/USD, GBP/USD, etc.)
3οΈβ£ Crypto (Bitcoin, Ethereum)
4οΈβ£ Indian Stocks (Nifty 50 stocks)
5οΈβ£ Commodities (Gold, Silver, Oil)
6οΈβ£ ALL (All signals)
Example: Reply "1" for NSE Live only
Or "1,2" for NSE Live + Forex
"""
self.send_message(chat_id, response)
return "categories_menu"
elif text.startswith("/stop"):
self.unsubscribe_user(chat_id)
response = """
π <b>Unsubscribed</b>
You won't receive any more alerts.
Send /start anytime to resubscribe.
"""
self.send_message(chat_id, response)
return "unsubscribed"
# Handle category selection (numbers)
elif text.isdigit() or "," in text:
category_map = {
"1": "NSE Live",
"2": "Forex",
"3": "Crypto",
"4": "Indian Stocks",
"5": "Commodities",
"6": "ALL"
}
selected = []
for num in text.replace(" ", "").split(","):
if num in category_map:
selected.append(category_map[num])
if selected:
self.subscribe_user(chat_id, name, username, selected)
categories = ", ".join(selected)
response = f"""
β
<b>Subscription Updated!</b>
You'll now receive alerts for:
{categories}
Use /status to check your subscription anytime.
"""
self.send_message(chat_id, response)
return "updated"
# Default response
else:
response = """
π Hi! I'm BiasBuster Trading Alert Bot.
<b>Commands:</b>
/start - Subscribe to alerts
/status - Check subscription
/categories - Change categories
/stop - Unsubscribe
Send /start to get started!
"""
self.send_message(chat_id, response)
return "help"
def run_listener(self):
"""Run the bot listener to process messages"""
print("π€ Starting Telegram Subscriber Bot...")
print(f"π± Bot is listening for messages...")
print(f"πΎ Subscribers file: {SUBSCRIBERS_FILE}")
print("\nPress Ctrl+C to stop\n")
offset = None
try:
while True:
result = self.get_updates(offset)
if result.get("ok"):
updates = result.get("result", [])
for update in updates:
offset = update["update_id"] + 1
message = update.get("message", {})
if message:
chat = message.get("chat", {})
chat_id = chat.get("id")
name = chat.get("first_name", "User")
text = message.get("text", "")
print(f"π¨ Message from {name} ({chat_id}): {text}")
action = self.process_message(message)
print(f"β
Action: {action}\n")
except KeyboardInterrupt:
print("\n\nπ Stopped listening.")
print(f"π Total subscribers: {len(self.get_active_subscribers())}")
if __name__ == "__main__":
manager = SubscriberManager()
manager.run_listener()
|