-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
796 lines (762 loc) · 36.3 KB
/
app.py
File metadata and controls
796 lines (762 loc) · 36.3 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
import logging
import sqlite3
import polars as pl
import random
import os
import json
import time
import asyncio
import subprocess
from datetime import datetime, timedelta
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, ContextTypes, CallbackQueryHandler
import trafilatura
import aiohttp
from rapidfuzz import fuzz
import streamlit as st
import wikipediaapi
import wikipedia
from aiohttp import web
from typing import List, Dict
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)
# Environment variables
BOT_TOKEN = os.getenv("BOT_TOKEN")
WEBHOOK_URL = os.getenv("WEBHOOK_URL", "https://uiu-buddy-bot.onrender.com/webhook")
PORT = int(os.getenv("PORT", 8443))
STREAMLIT_PORT = int(os.getenv("STREAMLIT_PORT", 8501))
# Initialize SQLite database
def init_db():
try:
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS reminders (
user_id INTEGER, task TEXT, deadline TEXT
)''')
c.execute('''CREATE TABLE IF NOT EXISTS user_profiles (
user_id INTEGER PRIMARY KEY, department TEXT, year INTEGER, favorite_roadmaps TEXT,
current_courses TEXT, section TEXT, contacts TEXT, ride_share_optin INTEGER,
last_updated TEXT
)''')
c.execute('''CREATE TABLE IF NOT EXISTS study_plans (
user_id INTEGER, courses TEXT, hours REAL, target_date TEXT, priorities TEXT
)''')
c.execute('''CREATE TABLE IF NOT EXISTS peer_matches (
user_id INTEGER, course TEXT, section TEXT, location TEXT
)''')
c.execute('''CREATE TABLE IF NOT EXISTS ride_shares (
user_id INTEGER, location_from TEXT, location_to TEXT, time_preference TEXT,
created_at TEXT
)''')
# Insert mock data for peer matching
mock_peers = [
(1001, "Data Structures and Algorithms", "A", "Mirpur"),
(1002, "Data Structures and Algorithms", "B", "Dhanmondi"),
(1003, "Operating Systems", "A", "Banani"),
(1004, "Python Programming", "C", "Gulshan"),
(1005, "CSE321", "B", "Uttara")
]
c.executemany("INSERT OR IGNORE INTO peer_matches (user_id, course, section, location) VALUES (?, ?, ?, ?)", mock_peers)
# Clean up profiles inactive for 5 months
five_months_ago = (datetime.now() - timedelta(days=150)).strftime('%Y-%m-%d')
c.execute("DELETE FROM user_profiles WHERE last_updated < ?", (five_months_ago,))
conn.commit()
logger.info("Database initialized successfully")
return conn
except sqlite3.OperationalError as e:
logger.error(f"Database initialization failed: {e}")
raise
finally:
if 'conn' in locals():
conn.close()
init_db()
# Initialize Wikipedia APIs
wiki_api = wikipediaapi.Wikipedia('UIUBuddyBot/1.0 (https://uiu.ac.bd)', 'en')
wikipedia.set_lang("en")
# Temporary in-memory storage
temp_calendar: List[Dict] = []
# Mock data for fallback
MOCK_EVENTS = [
{"name": "UIU Hackathon 2025", "date": "2025-09-15", "details": "Join the annual coding challenge!"},
{"name": "Midterm Exams", "date": "2025-10-10", "details": "Prepare for your midterm exams."}
]
MOCK_ABOUT = (
"UIU Developer Hub is a student-run club at United International University focused on fostering "
"technical skills through workshops, hackathons, and coding competitions. It provides resources, "
"mentorship, and networking opportunities for students in CSE and related fields."
)
# Web scraping with Trafilatura
async def fetch_web_content(url: str) -> str:
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, timeout=10, headers={'User-Agent': 'Mozilla/5.0'}) as response:
html = await response.text()
return trafilatura.extract(html, include_links=True) or ""
except Exception as e:
logger.error(f"Error fetching {url}: {e}")
return ""
# X scraping with snscrape
def scrape_x(query: str, max_results: int = 5) -> List[Dict]:
try:
cmd = f"snscrape --max-results {max_results} twitter-search '{query} near:Dhaka' > x_results.jsonl"
subprocess.run(cmd, shell=True, check=True)
results = []
with open("x_results.jsonl", "r") as f:
for line in f:
data = json.loads(line)
results.append({"user": data.get("user", {}).get("username", ""), "content": data.get("content", "")})
return results
except Exception as e:
logger.error(f"X scrape error: {e}")
return []
# Rate limiting
user_last_scrape = {}
RATE_LIMIT_SECONDS = 30
def can_scrape(user_id):
last_scrape = user_last_scrape.get(user_id, 0)
if time.time() - last_scrape < RATE_LIMIT_SECONDS:
return False
user_last_scrape[user_id] = time.time()
return True
# Update profile timestamp
def update_profile_timestamp(user_id):
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute("UPDATE user_profiles SET last_updated = ? WHERE user_id = ?",
(datetime.now().strftime('%Y-%m-%d'), user_id))
conn.commit()
finally:
conn.close()
# Notify ride share subscribers
async def notify_ride_share_subscribers(app: Application, location_from: str, location_to: str, time_preference: str, requester_id: int):
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute("SELECT user_id FROM user_profiles WHERE ride_share_optin = 1 AND user_id != ?", (requester_id,))
subscribers = c.fetchall()
for sub in subscribers:
user_id = sub[0]
c.execute("SELECT location FROM peer_matches WHERE user_id = ?", (user_id,))
user_location = c.fetchone()
if user_location and fuzz.partial_ratio(location_from.lower(), user_location[0].lower()) > 70:
try:
await app.bot.send_message(
chat_id=user_id,
text=f"New ride share request: From {location_from} to {location_to} at {time_preference}. Reply to coordinate!"
)
except Exception as e:
logger.error(f"Error sending ride share notification to {user_id}: {e}")
finally:
conn.close()
# Command handlers
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for start command")
return
try:
keyboard = [
[InlineKeyboardButton("View Profile", callback_data='view_profile'),
InlineKeyboardButton("Set Profile", callback_data='set_profile'),
InlineKeyboardButton("About UIU Developer Hub", callback_data='about'),
InlineKeyboardButton("Help", callback_data='help')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
"Welcome to UIU Buddy Bot! 🎓\nFind study partners, ride shares, and more.",
reply_markup=reply_markup
)
update_profile_timestamp(update.effective_user.id)
except Exception as e:
logger.error(f"Error in start command: {e}")
await update.message.reply_text("Error starting the bot. Please try again.")
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for help command")
return
try:
help_text = (
"📚 *UIU Buddy Bot Commands*\n\n"
"/start\n/help\n/about\n/calendar\n/resources\n/cgpa\n/studyplan\n/reminders\n/motivate\n/profile\n/study\n/ride\n/match"
)
await update.message.reply_text(help_text, parse_mode='Markdown')
except Exception as e:
logger.error(f"Error in help command: {e}")
await update.message.reply_text("Error displaying help. Please try again.")
async def about(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for about command")
return
try:
user_id = update.effective_user.id
if not can_scrape(user_id):
await update.message.reply_text("Please wait 30 seconds before requesting information again.")
return
content = await fetch_web_content("https://www.uiu.ac.bd/clubs/developer-hub")
about_text = MOCK_ABOUT
if content:
lines = content.split('\n')
for line in lines:
if any(kw in line.lower() for kw in ['developer hub', 'club', 'mission', 'vision']):
about_text = line.strip()[:500] + "..." if len(line) > 500 else line.strip()
break
response = (
"🏫 *About UIU Developer Hub*\n\n"
f"{about_text}\n\n"
"Visit https://www.facebook.com/uiudevelopershub for more details."
)
await update.message.reply_text(response, parse_mode='Markdown')
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in about command: {e}")
await update.message.reply_text("Error fetching UIU Developer Hub info. Please try again.")
async def calendar(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for calendar command")
return
try:
user_id = update.effective_user.id
if not can_scrape(user_id):
await update.message.reply_text("Please wait 30 seconds before requesting another calendar.")
return
global temp_calendar
temp_calendar = []
content = await fetch_web_content("https://www.uiu.ac.bd/academic-calendars")
if content:
lines = content.split('\n')
for line in lines[:5]:
if any(kw in line.lower() for kw in ['event', 'seminar', 'holiday', 'exam']):
temp_calendar.append({"name": line.strip(), "date": "2025-09-15", "details": line.strip()})
if temp_calendar:
response = "UIU Academic Calendar Events:\n"
for event in temp_calendar:
response += f"- {event['name']} ({event['date']}): {event['details']}\n"
keyboard = [[InlineKeyboardButton("Add Reminder", callback_data='add_reminder_calendar')]]
reply_markup = InlineKeyboardMarkup(keyboard)
else:
response = "Unable to fetch calendar. Using mock data:\n"
for event in MOCK_EVENTS:
response += f"- {event['name']} ({event['date']}): {event['details']}\n"
reply_markup = None
await update.message.reply_text(response, reply_markup=reply_markup)
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in calendar command: {e}")
await update.message.reply_text("Error fetching calendar. Please try again.")
async def resources(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for resources command")
return
try:
user_id = update.effective_user.id
args = context.args
keyword = args[0].lower() if args else None
if not can_scrape(user_id) and keyword:
await update.message.reply_text("Please wait 30 seconds before requesting resources.")
return
resources = [
{"title": "Learn Python", "platform": "freeCodeCamp", "link": "https://freecodecamp.org/learn/python"},
{"title": "CS50", "platform": "edX", "link": "https://edx.org/course/cs50"},
{"title": "JavaScript Tutorial", "platform": "w3schools", "link": "https://w3schools.com/js"},
{"title": "Data Structures and Algorithms", "platform": "GeeksforGeeks", "link": "https://www.geeksforgeeks.org/data-structures"},
{"title": "Operating Systems", "platform": "Coursera", "link": "https://www.coursera.org/learn/os"}
]
wiki_summary = ""
if keyword:
page = wiki_api.page(keyword)
if page.exists():
wiki_summary = page.summary[:200] + "..." if len(page.summary) > 200 else page.summary
else:
try:
wiki_summary = wikipedia.summary(keyword, sentences=2)
except:
wiki_summary = "No Wikipedia summary available."
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute("SELECT favorite_roadmaps FROM user_profiles WHERE user_id = ?", (user_id,))
profile = c.fetchone()
finally:
conn.close()
response = f"Learning Resources{f' for {keyword}' if keyword else ''}:\n"
filtered_resources = resources
if keyword or (profile and profile[0]):
filter_terms = [keyword] if keyword else profile[0].split(',')
filtered_resources = [
r for r in resources
if any(fuzz.partial_ratio(term.lower(), r['title'].lower()) > 70 for term in filter_terms)
]
for resource in filtered_resources[:5]:
response += f"- {resource['title']} ({resource['platform']}): {resource['link']}\n"
if wiki_summary:
response += f"\nWikipedia Summary for {keyword}:\n{wiki_summary}"
await update.message.reply_text(response)
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in resources command: {e}")
await update.message.reply_text("Error fetching resources. Please try again.")
async def cgpa(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for cgpa command")
return
try:
args = context.args
if not args:
await update.message.reply_text(
"Usage: /cgpa course1:grade1 course2:grade2\nExample: /cgpa cse321:A cse322:B+"
)
return
grades = {course.split(':')[0]: course.split(':')[1] for course in args}
grade_points = {'A': 4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7, 'C+': 2.3, 'C': 2.0}
df = pl.DataFrame({"Course": list(grades.keys()), "Grade": list(grades.values())})
df = df.with_columns(pl.col("Grade").map_dict(grade_points, default=None).alias("Points"))
if df["Points"].is_null().any():
await update.message.reply_text("Invalid grade(s). Use: A, A-, B+, B, B-, C+, C")
return
cgpa = df["Points"].mean()
await update.message.reply_text(f"Your CGPA: {cgpa:.2f}\n{df.select(['Course', 'Grade', 'Points']).to_string()}")
update_profile_timestamp(update.effective_user.id)
except Exception as e:
logger.error(f"Error in cgpa command: {e}")
await update.message.reply_text("Invalid format. Use: /cgpa cse321:A cse322:B+")
async def studyplan(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for studyplan command")
return
try:
args = context.args
if len(args) < 4:
await update.message.reply_text(
"Usage: /studyplan course1,course2 hours_per_week target_date(YYYY-MM-DD) priority(course1:1,cse322:2)"
)
return
courses, hours, target_date, priority = args[0].split(','), float(args[1]), args[2], args[3]
try:
datetime.strptime(target_date, '%Y-%m-%d')
except ValueError:
await update.message.reply_text("Invalid date format. Use YYYY-MM-DD, e.g., 2025-09-01")
return
priorities = {p.split(':')[0]: int(p.split(':')[1]) for p in priority.split(',')}
df = pl.DataFrame({"Course": courses})
df = df.with_columns(
Priority=pl.col("Course").map_dict(priorities, default=1),
Hours=pl.col("Course").map_elements(lambda x: (hours * (3 - priorities.get(x, 1))) / len(courses))
)
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute("INSERT INTO study_plans (user_id, courses, hours, target_date, priorities) VALUES (?, ?, ?, ?, ?)",
(update.effective_user.id, args[0], hours, target_date, priority))
conn.commit()
finally:
conn.close()
response = f"Study Plan for {target_date}:\n{df.to_string()}\nTotal Hours/Week: {hours}"
await update.message.reply_text(response)
update_profile_timestamp(update.effective_user.id)
except Exception as e:
logger.error(f"Error in studyplan command: {e}")
await update.message.reply_text("Error creating study plan. Please try again.")
async def reminders(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for reminders command")
return
try:
args = context.args
if not args:
await update.message.reply_text("Usage: /reminders add task deadline(YYYY-MM-DD) or /reminders list")
return
user_id = update.effective_user.id
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
if args[0].lower() == "add":
task, deadline = " ".join(args[1:-1]), args[-1]
try:
datetime.strptime(deadline, '%Y-%m-%d')
except ValueError:
await update.message.reply_text("Invalid date format. Use YYYY-MM-DD, e.g., 2025-09-01")
return
c.execute("INSERT INTO reminders (user_id, task, deadline) VALUES (?, ?, ?)",
(user_id, task, deadline))
conn.commit()
await update.message.reply_text(f"Reminder set: {task} on {deadline}")
else:
c.execute("SELECT task, deadline FROM reminders WHERE user_id = ?", (user_id,))
reminders = c.fetchall()
response = "Your Reminders:\n" + "\n".join(f"- {task} ({deadline})" for task, deadline in reminders)
await update.message.reply_text(response or "No reminders set.")
finally:
conn.close()
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in reminders command: {e}")
await update.message.reply_text("Error setting/listing reminders. Please try again.")
async def motivate(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for motivate command")
return
try:
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute("SELECT favorite_roadmaps, department FROM user_profiles WHERE user_id = ?", (update.effective_user.id,))
profile = c.fetchone()
finally:
conn.close()
tips = [
"Stay focused on your studies. Consistent effort leads to success!",
"Break down complex topics into manageable parts. You can do it!",
"Collaborate with peers to enhance your learning experience."
]
if profile and profile[0]:
tips.append(f"Keep exploring your {profile[0].split(',')[0]} skills. Progress adds up!")
if profile and profile[1]:
tips.append(f"Your {profile[1]} journey is shaping a bright future.")
await update.message.reply_text(random.choice(tips))
update_profile_timestamp(update.effective_user.id)
except Exception as e:
logger.error(f"Error in motivate command: {e}")
await update.message.reply_text("Error fetching motivational tip. Please try again.")
async def profile(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for profile command")
return
try:
args = context.args
user_id = update.effective_user.id
if not args or args[0].lower() != "set" or len(args) < 7:
await update.message.reply_text(
"Usage: /profile set department year roadmaps courses section contacts optin_ride_share\n"
"Example: /profile set CSE 2 python,dsa cse321,cse322 A telegram:@user,fb:user,wa:1234567890 1"
)
return
department, year, favorite_roadmaps, current_courses, section, contacts, ride_share_optin = \
args[1], int(args[2]), args[3], args[4], args[5], args[6], int(args[7])
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute(
"""INSERT OR REPLACE INTO user_profiles
(user_id, department, year, favorite_roadmaps, current_courses, section, contacts, ride_share_optin, last_updated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(user_id, department, year, favorite_roadmaps, current_courses, section, contacts, ride_share_optin, datetime.now().strftime('%Y-%m-%d'))
)
for course in current_courses.split(','):
c.execute(
"INSERT OR REPLACE INTO peer_matches (user_id, course, section, location) VALUES (?, ?, ?, ?)",
(user_id, course, section, context.user_data.get('commute_location', 'Unknown'))
)
conn.commit()
finally:
conn.close()
await update.message.reply_text(
f"Profile updated: {department}, Year {year}, Roadmaps: {favorite_roadmaps}, "
f"Courses: {current_courses}, Section: {section}, Contacts: {contacts}, Ride Share Opt-in: {ride_share_optin}"
)
context.user_data['commute_location'] = context.user_data.get('commute_location', 'Unknown')
except Exception as e:
logger.error(f"Error in profile command: {e}")
await update.message.reply_text("Error setting profile. Please try again.")
async def study_find(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for study find command")
return
try:
args = context.args
if not args:
await update.message.reply_text("Usage: /study find <course>\nExample: /study find cse321")
return
course = " ".join(args).lower()
user_id = update.effective_user.id
if not can_scrape(user_id):
await update.message.reply_text("Please wait 30 seconds before searching for study partners.")
return
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute("SELECT user_id, course, section, location, contacts FROM peer_matches p JOIN user_profiles u ON p.user_id = u.user_id WHERE lower(course) LIKE ?", (f"%{course}%",))
matches = c.fetchall()
finally:
conn.close()
x_results = scrape_x(f"{course} UIU", max_results=3)
wiki_summary = ""
page = wiki_api.page(course)
if page.exists():
wiki_summary = page.summary[:200] + "..." if len(page.summary) > 200 else page.summary
else:
try:
wiki_summary = wikipedia.summary(course, sentences=2)
except:
wiki_summary = "No Wikipedia summary available."
response = f"Study Partners for {course}:\n"
if matches:
for match in matches:
user_id, matched_course, section, location, contacts = match
response += f"- User {user_id} (Course: {matched_course}, Section: {section}, Location: {location}, Contacts: {contacts})\n"
else:
response += "- No peers found in database.\n"
if x_results:
response += "\nX Matches:\n"
for result in x_results[:3]:
response += f"- @{result['user']}: {result['content'][:100]}...\n"
else:
response += "\nNo X matches found.\n"
if wiki_summary:
response += f"\nWikipedia Summary for {course}:\n{wiki_summary}"
await update.message.reply_text(response)
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in study find command: {e}")
await update.message.reply_text("Error finding study partners. Please try again.")
async def ride_share(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for ride share command")
return
try:
args = context.args
if len(args) < 3:
await update.message.reply_text("Usage: /ride share <from> <to> <time>\nExample: /ride share Dhanmondi UIU 08:00")
return
location_from, location_to, time_preference = args[0].lower(), args[1].lower(), args[2]
user_id = update.effective_user.id
if not can_scrape(user_id):
await update.message.reply_text("Please wait 30 seconds before searching for ride shares.")
return
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute(
"INSERT INTO ride_shares (user_id, location_from, location_to, time_preference, created_at) VALUES (?, ?, ?, ?, ?)",
(user_id, location_from, location_to, time_preference, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
)
c.execute("SELECT user_id, course, section, location, contacts FROM peer_matches p JOIN user_profiles u ON p.user_id = u.user_id WHERE lower(location) LIKE ?", (f"%{location_from}%",))
matches = c.fetchall()
conn.commit()
finally:
conn.close()
x_results = scrape_x(f"commute {location_from} UIU", max_results=3)
response = f"Ride Share Partners from {location_from} to {location_to} at {time_preference}:\n"
if matches:
for match in matches:
user_id, course, section, matched_location, contacts = match
response += f"- User {user_id} (Course: {course}, Section: {section}, Location: {matched_location}, Contacts: {contacts})\n"
else:
response += "- No peers found in database.\n"
if x_results:
response += "\nX Matches:\n"
for result in x_results[:3]:
response += f"- @{result['user']}: {result['content'][:100]}...\n"
else:
response += "\nNo X matches found.\n"
await update.message.reply_text(response)
await notify_ride_share_subscribers(context.application, location_from, location_to, time_preference, user_id)
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in ride share command: {e}")
await update.message.reply_text("Error finding ride share partners. Please try again.")
async def match(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
logger.error("No message in update for match command")
return
try:
args = context.args
if len(args) < 2:
await update.message.reply_text("Usage: /match <course> <section>\nExample: /match cse321 A")
return
course, section = args[0].lower(), args[1].upper()
user_id = update.effective_user.id
if not can_scrape(user_id):
await update.message.reply_text("Please wait 30 seconds before searching for section matches.")
return
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute(
"SELECT user_id, course, section, location, contacts FROM peer_matches p JOIN user_profiles u ON p.user_id = u.user_id WHERE lower(course) LIKE ? AND section = ?",
(f"%{course}%", section)
)
matches = c.fetchall()
finally:
conn.close()
x_results = scrape_x(f"{course} {section} UIU", max_results=3)
response = f"Section Matches for {course} (Section {section}):\n"
if matches:
for match in matches:
user_id, matched_course, matched_section, location, contacts = match
response += f"- User {user_id} (Course: {matched_course}, Section: {matched_section}, Location: {location}, Contacts: {contacts})\n"
else:
response += "- No peers found in database.\n"
if x_results:
response += "\nX Matches:\n"
for result in x_results[:3]:
response += f"- @{result['user']}: {result['content'][:100]}...\n"
else:
response += "\nNo X matches found.\n"
await update.message.reply_text(response)
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in match command: {e}")
await update.message.reply_text("Error finding section matches. Please try again.")
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.callback_query:
logger.error("No callback query in update for button callback")
return
try:
query = update.callback_query
await query.answer()
user_id = query.from_user.id
if query.data == 'view_profile':
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
c = conn.cursor()
c.execute("SELECT department, year, favorite_roadmaps, current_courses, section, contacts, ride_share_optin FROM user_profiles WHERE user_id = ?", (user_id,))
profile = c.fetchone()
finally:
conn.close()
if profile:
dept, year, roadmaps, courses, section, contacts, optin = profile
await query.message.reply_text(
f"Profile:\nDepartment: {dept}\nYear: {year}\nRoadmaps: {roadmaps}\nCourses: {courses}\nSection: {section}\nContacts: {contacts}\nRide Share Opt-in: {optin}"
)
else:
await query.message.reply_text("No profile set. Use /profile set dept year roadmaps courses section contacts optin")
elif query.data == 'set_profile':
await query.message.reply_text(
"Set your profile with /profile set department year favorite_roadmaps courses section contacts optin_ride_share\n"
"Example: /profile set CSE 2 python,dsa cse321,cse322 A telegram:@user,fb:user,wa:1234567890 1"
)
elif query.data == 'add_reminder_calendar':
await query.message.reply_text("To add a calendar event reminder, use /reminders add 'Event Name' YYYY-MM-DD")
elif query.data == 'about':
await about(update, context)
elif query.data == 'help':
await help(update, context)
update_profile_timestamp(user_id)
except Exception as e:
logger.error(f"Error in button callback: {e}")
await query.message.reply_text("Error processing your request. Please try again.")
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
logger.error(f"Update {update} caused error {context.error}")
if update:
if update.message:
await update.message.reply_text("An error occurred. Please try again.")
elif update.callback_query:
await update.callback_query.message.reply_text("An error occurred. Please try again.")
# Streamlit dashboard
def run_streamlit():
st.set_page_config(page_title="UIU Buddy Dashboard", page_icon="🎓", layout="wide")
st.title("UIU Buddy Dashboard")
st.header("Student Profiles, Study Plans, Ride Shares, and Matches")
conn = sqlite3.connect('uiu_buddy.db', timeout=10)
try:
profiles = pl.read_database("SELECT * FROM user_profiles", conn)
if not profiles.is_empty():
st.subheader("Student Profiles")
st.dataframe(profiles)
else:
st.write("No user profiles found.")
study_plans = pl.read_database("SELECT * FROM study_plans", conn)
if not study_plans.is_empty():
st.subheader("Study Plans")
st.dataframe(study_plans)
else:
st.write("No study plans found.")
reminders = pl.read_database("SELECT * FROM reminders", conn)
if not reminders.is_empty():
st.subheader("Reminders")
st.dataframe(reminders)
else:
st.write("No reminders set.")
peer_matches = pl.read_database("SELECT * FROM peer_matches", conn)
if not peer_matches.is_empty():
st.subheader("Peer Matches")
st.dataframe(peer_matches)
else:
st.write("No peer matches found.")
ride_shares = pl.read_database("SELECT * FROM ride_shares", conn)
if not ride_shares.is_empty():
st.subheader("Ride Share Requests")
st.dataframe(ride_shares)
else:
st.write("No ride share requests found.")
finally:
conn.close()
# Webhook handler
async def webhook_handler(request: web.Request) -> web.Response:
try:
data = await request.json()
update = Update.de_json(data, application.bot)
if not update:
logger.error("Invalid update received in webhook")
return web.Response(status=400)
await application.process_update(update)
return web.Response(status=200)
except Exception as e:
logger.error(f"Webhook error: {e}")
return web.Response(status=500)
# Health check endpoint
async def health_check(request: web.Request) -> web.Response:
return web.Response(text="UIU Buddy Bot is running", status=200)
# Setup Telegram application and webhook
async def setup_application():
global application
try:
if not BOT_TOKEN:
logger.error("BOT_TOKEN environment variable not set")
raise ValueError("BOT_TOKEN not set")
application = Application.builder().token(BOT_TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help))
application.add_handler(CommandHandler("about", about))
application.add_handler(CommandHandler("calendar", calendar))
application.add_handler(CommandHandler("resources", resources))
application.add_handler(CommandHandler("cgpa", cgpa))
application.add_handler(CommandHandler("studyplan", studyplan))
application.add_handler(CommandHandler("reminders", reminders))
application.add_handler(CommandHandler("motivate", motivate))
application.add_handler(CommandHandler("profile", profile))
application.add_handler(CommandHandler("study", study_find))
application.add_handler(CommandHandler("ride", ride_share))
application.add_handler(CommandHandler("match", match))
application.add_handler(CallbackQueryHandler(button_callback))
application.add_error_handler(error_handler)
await application.initialize()
await application.start()
webhook_info = await application.bot.get_webhook_info()
if webhook_info.url != WEBHOOK_URL:
await application.bot.delete_webhook(drop_pending_updates=True)
await application.bot.set_webhook(url=WEBHOOK_URL)
logger.info(f"Webhook set to {WEBHOOK_URL}")
else:
logger.info(f"Webhook already set to {WEBHOOK_URL}")
except Exception as e:
logger.error(f"Setup failed: {e}")
raise
# Main function
async def main():
try:
app = web.Application()
app.router.add_post('/webhook', webhook_handler)
app.router.add_get('/', health_check)
await setup_application()
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, '0.0.0.0', PORT)
await site.start()
logger.info(f"Webhook server running on port {PORT}")
subprocess.Popen(["streamlit", "run", __file__, "--server.port", str(STREAMLIT_PORT)])
while True:
await asyncio.sleep(3600)
except Exception as e:
logger.error(f"Error in main: {e}")
raise
if __name__ == "__main__":
if "streamlit" in os.environ.get("PYTHONPATH", ""):
run_streamlit()
else:
asyncio.run(main())