-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram_bot.py
More file actions
300 lines (231 loc) · 10.2 KB
/
Copy pathtelegram_bot.py
File metadata and controls
300 lines (231 loc) · 10.2 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# telegram_bot.py
# Telegram Bot integration for Data Plan Tracker
# Provides mobile notifications and interactive commands
import os
import sys
import json
from datetime import datetime
# Optional dependency - bot works only if python-telegram-bot is installed
try:
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
TELEGRAM_AVAILABLE = True
except ImportError:
TELEGRAM_AVAILABLE = False
# Import from project
import database
import alerts
def get_bot_config() -> dict:
"""Get Telegram bot configuration from config or env vars."""
config = alerts.load_config()
telegram_cfg = config.get("webhooks", {}).get("telegram", {})
# Fallback to env vars
if not telegram_cfg.get("bot_token"):
telegram_cfg["bot_token"] = os.getenv("DATAPLAN_TELEGRAM_BOT_TOKEN", "")
if not telegram_cfg.get("chat_id"):
telegram_cfg["chat_id"] = os.getenv("DATAPLAN_TELEGRAM_CHAT_ID", "")
return telegram_cfg
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /start command."""
welcome_text = """
📡 **Data Plan Tracker Bot**
Available commands:
/plans - List all active plans
/expiring - Show plans expiring soon
/summary - Monthly spend summary
/stats - Detailed statistics
/check - Run daily check
/help - Show this help message
Use the dashboard for full management:
```
python run.py
```
"""
await update.message.reply_text(welcome_text, parse_mode="Markdown")
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /help command."""
await start_command(update, context)
async def plans_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /plans command - list all active plans."""
plans = database.get_all_plans(active_only=True)
if not plans:
await update.message.reply_text("No active plans found.")
return
message_lines = [f"📋 *{len(plans)} Active Plans:*\n"]
for p in plans[:20]: # Limit to 20 plans
name = p.get("name", "Unnamed")
provider = p.get("provider", "No provider")
cost = p.get("cost", 0)
renewal = p.get("next_renewal", "No date")
# Calculate days left
days_text = ""
if renewal:
try:
renewal_date = datetime.strptime(renewal, "%Y-%m-%d").date()
days = (renewal_date - datetime.now().date()).days
if days < 0:
days_text = f" ({days} days OVERDUE)"
elif days <= 7:
days_text = f" ({days} days left) ⚠️"
else:
days_text = f" ({days} days left)"
except:
pass
message_lines.append(f"• *{name}* ({provider}) - ${cost:.2f}{days_text}")
if len(plans) > 20:
message_lines.append(f"\n... and {len(plans) - 20} more plans")
await update.message.reply_text("\n".join(message_lines), parse_mode="Markdown")
async def expiring_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /expiring command - show plans expiring soon."""
config = alerts.load_config()
warning_days = config.get("alert_days_warning", 14)
expiring = database.get_expiring_plans(within_days=warning_days)
if not expiring:
await update.message.reply_text(f"✅ No plans expiring in the next {warning_days} days.")
return
message_lines = [f"⚠️ *{len(expiring)} Plans Expiring Soon:*\n"]
for p in expiring:
name = p.get("name", "Unnamed")
provider = p.get("provider", "No provider")
renewal = p.get("next_renewal", "")
cost = p.get("cost", 0)
try:
renewal_date = datetime.strptime(renewal, "%Y-%m-%d").date()
days = (renewal_date - datetime.now().date()).days
days_text = f"{days} days left"
if days < 0:
days_text = f"{abs(days)} days OVERDUE ❌"
elif days <= 3:
days_text = f"{days} days left 🔴"
elif days <= 7:
days_text = f"{days} days left 🟡"
except:
days_text = "unknown"
message_lines.append(f"• *{name}* ({provider})\n ${cost:.2f} - Due: {renewal} ({days_text})")
await update.message.reply_text("\n".join(message_lines), parse_mode="Markdown")
async def summary_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /summary command - show spend summary."""
plans = database.get_all_plans(active_only=True)
if not plans:
await update.message.reply_text("No active plans.")
return
# Calculate costs
from tracker import MONTHLY_EQUIV
monthly_total = 0.0
by_type = {}
for p in plans:
cost = p.get("cost", 0) or 0
cycle = p.get("billing_cycle", "monthly") or "monthly"
monthly_cost = cost * MONTHLY_EQUIV.get(cycle, 1.0)
monthly_total += monthly_cost
t = p.get("type", "other")
by_type.setdefault(t, {"count": 0, "monthly": 0.0})
by_type[t]["count"] += 1
by_type[t]["monthly"] += monthly_cost
message_lines = [
"📊 *Spend Summary*\n",
f"*Total Plans:* {len(plans)}",
f"*Monthly Spend:* ${monthly_total:.2f}",
f"*Annual Projection:* ${monthly_total * 12:.2f}\n",
"*By Type:*"
]
for t, stats in sorted(by_type.items()):
message_lines.append(f"• {t.upper()}: {stats['count']} plans - ${stats['monthly']:.2f}/mo")
await update.message.reply_text("\n".join(message_lines), parse_mode="Markdown")
async def stats_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /stats command - show detailed statistics."""
plans = database.get_all_plans(active_only=True)
if not plans:
await update.message.reply_text("No active plans.")
return
# Calculate statistics
from tracker import days_until
upcoming_7 = sum(1 for p in plans if p.get("next_renewal") and days_until(p["next_renewal"]) <= 7)
upcoming_14 = sum(1 for p in plans if p.get("next_renewal") and days_until(p["next_renewal"]) <= 14)
upcoming_30 = sum(1 for p in plans if p.get("next_renewal") and days_until(p["next_renewal"]) <= 30)
auto_renew = sum(1 for p in plans if p.get("auto_renew"))
manual_renew = len(plans) - auto_renew
with_phone = sum(1 for p in plans if p.get("phone_number"))
unique_vms = len(set(p.get("assigned_vm") for p in plans if p.get("assigned_vm")))
message_lines = [
"📈 *Statistics*\n",
f"*Active Plans:* {len(plans)}",
f"*Unique VMs:* {unique_vms}",
f"*Plans with Phone:* {with_phone}",
"",
"*Upcoming Renewals:*",
f"• Next 7 days: {upcoming_7}",
f"• Next 14 days: {upcoming_14}",
f"• Next 30 days: {upcoming_30}",
"",
"*Auto-Renew Status:*",
f"• Auto-renew: {auto_renew}",
f"• Manual renew: {manual_renew}"
]
await update.message.reply_text("\n".join(message_lines), parse_mode="Markdown")
async def check_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /check command - run daily check."""
await update.message.reply_text("🔔 Running daily check...")
# Run the check (this will send any configured alerts)
import subprocess
result = subprocess.run(
[sys.executable, "tracker.py", "check"],
capture_output=True,
text=True,
cwd=os.path.dirname(os.path.abspath(__file__))
)
if result.returncode == 0:
await update.message.reply_text("✅ Daily check completed. Check your notifications!")
else:
await update.message.reply_text(f"❌ Check failed:\n```\n{result.stderr[:500]}\n```", parse_mode="Markdown")
def send_telegram_notification(message: str, bot_token: str = None, chat_id: str = None):
"""Send a notification via Telegram Bot API (synchronous version)."""
if not TELEGRAM_AVAILABLE:
print("[!] python-telegram-bot not installed. Run: pip install python-telegram-bot")
return False
cfg = get_bot_config()
token = bot_token or cfg.get("bot_token")
chat = chat_id or cfg.get("chat_id")
if not token or not chat:
print("[!] Telegram bot not configured. Set bot_token and chat_id in config.")
return False
try:
import requests
url = f"https://api.telegram.org/bot{token}/sendMessage"
payload = {
"chat_id": chat,
"text": message,
"parse_mode": "Markdown"
}
response = requests.post(url, json=payload, timeout=10)
return response.status_code == 200
except Exception as e:
print(f"[!] Telegram notification failed: {e}")
return False
def run_bot_polling():
"""Run the bot in polling mode (for development/testing)."""
if not TELEGRAM_AVAILABLE:
print("[!] python-telegram-bot not installed. Run: pip install python-telegram-bot")
return
cfg = get_bot_config()
token = cfg.get("bot_token")
if not token:
print("[!] Telegram bot token not configured.")
print(" Set in config.json: webhooks.telegram.bot_token")
print(" Or via env var: DATAPLAN_TELEGRAM_BOT_TOKEN")
return
print("[*] Starting Telegram Bot...")
print(" Press Ctrl+C to stop")
application = Application.builder().token(token).build()
# Add command handlers
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("plans", plans_command))
application.add_handler(CommandHandler("expiring", expiring_command))
application.add_handler(CommandHandler("summary", summary_command))
application.add_handler(CommandHandler("stats", stats_command))
application.add_handler(CommandHandler("check", check_command))
# Run the bot until Ctrl+C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
run_bot_polling()