Spaces:
Sleeping
Sleeping
Swaminaatha krishna
Claude Sonnet 4.6
feat: demo prep — unify rating flow, add coolspot pin, clean web UI
58a75e7 Download src/telegram_bot.py from arish7/coolride-telegram: direct link, hf CLI and curl.
- Browser
- Download file 53.2 kB
-
https://huggingface.co/spaces/arish7/coolride-telegram/resolve/main/src/telegram_bot.py
- Command line
-
hf download hf://spaces/arish7/coolride-telegram/src/telegram_bot.py
-
curl -L -o telegram_bot.py https://huggingface.co/spaces/arish7/coolride-telegram/resolve/main/src/telegram_bot.py
53.2 kB
"""
CoolRide Telegram Bot - Master Logic (V16.10 - Final Audit)
Features: Smart Recs, Auto-Link, Sensor+NEA Logs, Post-Ride Menu.
Restored: Long Route Safety Checks & Full Utility Suite.
"""
import os
import json
import re
import asyncio
import threading
from urllib.parse import quote
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.constants import ChatAction
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
from config import APP_URL, GROQ_SYSTEM_PROMPT, MAX_ROUTE_DISTANCE_KM, FALLBACK_PLACES, TIME_DISTANCE_MAP, MAX_SUGGESTIONS_BEFORE_CYCLE, SESSION_TIMEOUT
from helpers import geocode_location, haversine_distance, parse_route_request, find_nearby_amenities, is_in_singapore, parse_recommendations, get_realtime_weather, filter_places_by_distance, log
# --- SHARED STATE ---
user_sessions = {}
_session_lock = threading.Lock()
telegram_links = {}
VALID_REPORT_TYPES = {"too_hot", "blocked", "shade_oasis", "water_available"}
def get_session(user_id):
"""Thread-safe session initialization and retrieval."""
with _session_lock:
if user_id not in user_sessions:
user_sessions[user_id] = {"state": "IDLE", "data": {}}
return user_sessions[user_id]
def md_escape(text: str) -> str:
"""Escape Markdown V1 special characters in user-provided strings."""
if not text:
return text
for ch in ('_', '*', '`', '['):
text = text.replace(ch, f'\\{ch}')
return text
# --- DEPENDENCIES ---
_supabase = None
_groq_client = None
_amenities_data = []
_compute_route_fn = None
_cache_route_fn = None
_G = None
# Telegram Instances
telegram_bot = None
telegram_application = None
_webhook_loop = None
_webhook_thread = None
# --- INITIALIZATION ---
def init_telegram_module(supabase_client, groq_client, amenities_data, compute_route_fn, cache_route_fn, graph):
global _supabase, _groq_client, _amenities_data, _compute_route_fn, _cache_route_fn, _G
_supabase = supabase_client
_groq_client = groq_client
_amenities_data = amenities_data
_compute_route_fn = compute_route_fn
_cache_route_fn = cache_route_fn
_G = graph
# --- LLM ENGINE ---
def chat_with_groq(user_message: str, user_id: str, context_instruction: str = "") -> str:
if not _groq_client: return "Sorry, AI is offline."
session = user_sessions.get(user_id, {})
history = session.get("history", [])
lang_pref = session.get("data", {}).get("language", "English")
sys_prompt = GROQ_SYSTEM_PROMPT + f"\nUSER CONTEXT: Language: {lang_pref}. {context_instruction}"
messages = [{"role": "system", "content": sys_prompt}] + history[-6:]
messages.append({"role": "user", "content": user_message})
try:
response = _groq_client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=messages,
temperature=0.7,
max_tokens=500
)
reply = response.choices[0].message.content
# Update conversation history for multi-turn context
if "history" in session:
session["history"].append({"role": "user", "content": user_message})
session["history"].append({"role": "assistant", "content": reply})
# Keep last 6 exchanges (12 messages)
if len(session["history"]) > 12:
session["history"] = session["history"][-12:]
return reply
except Exception as e:
print(f" ⚠️ Groq Error: {e}", flush=True)
return "I'm having trouble thinking right now."
def extract_clean_reply(llm_response: str) -> tuple:
json_data = parse_route_request(llm_response)
if not json_data:
recs = parse_recommendations(llm_response)
if recs: json_data = {"recommendations": recs}
clean_text = re.sub(r'<HIDDEN_DATA>.*?</HIDDEN_DATA>', '', llm_response, flags=re.DOTALL).strip()
return clean_text, json_data
def get_suggestions(mood: str, time_pref: str, start_coords: tuple, seen_places: list, user_id: str) -> list:
"""Get place suggestions with LLM-first approach and fallback to hardcoded places.
Args:
mood: Category (nature, food, views, museums, shopping)
time_pref: Time preference (short, med, long)
start_coords: User's start location (lat, lon)
seen_places: List of already shown place names
user_id: User's telegram ID
Returns:
List of 3 place dicts with 'name' and 'reason' keys
"""
# 1. Get distance bounds from time preference
min_km, max_km = TIME_DISTANCE_MAP.get(time_pref, (4, 8))
# 2. Check if we need to reset seen list (cap at 9)
if len(seen_places) >= MAX_SUGGESTIONS_BEFORE_CYCLE:
seen_places.clear()
print(f" 🔄 Reset seen_places for user {user_id} (hit cap)", flush=True)
# 3. Try LLM first with strict constraints
exclude_str = ", ".join(seen_places) if seen_places else "none"
time_label = {"short": "10-15 minute", "med": "15-30 minute", "long": "30+ minute"}.get(time_pref, "15-30 minute")
prompt = f"""Recommend exactly 3 {mood} places in Singapore for a {time_label} cycling ride.
STRICT RULES:
- Distance: {min_km}-{max_km} km from user's location
- Category: {mood} only
- EXCLUDE these places (already shown): {exclude_str}
- Return ONLY places matching these constraints
<HIDDEN_DATA>{{"places": [{{"name": "Place1", "reason": "Why good"}}, {{"name": "Place2", "reason": "Why"}}, {{"name": "Place3", "reason": "Why"}}]}}</HIDDEN_DATA>"""
llm_places = []
if _groq_client:
try:
response = chat_with_groq(prompt, user_id, context_instruction="Return exactly 3 places in JSON format.")
_, json_data = extract_clean_reply(response)
if json_data and "places" in json_data:
llm_places = json_data["places"]
elif json_data and "recommendations" in json_data:
llm_places = json_data["recommendations"]
print(f" 🤖 LLM returned {len(llm_places)} places for {mood}/{time_pref}", flush=True)
except Exception as e:
print(f" ⚠️ LLM suggestion failed: {e}", flush=True)
# 4. Filter LLM results by distance (if we have start coords)
if llm_places and start_coords:
valid_places = filter_places_by_distance(llm_places, start_coords, min_km, max_km)
available = [p for p in valid_places if p['name'] not in seen_places]
if len(available) >= 3:
return available[:3]
# Keep any partial LLM matches to merge with fallback later
if available:
print(f" ⚠️ LLM: only {len(available)} matched distance, will pad with fallback", flush=True)
else:
print(f" ⚠️ LLM places didn't match distance filter, using fallback", flush=True)
available = []
else:
available = []
# Track partial results from LLM to merge with fallback
partial_results = list(available)
# 5. Fallback to hardcoded places
fallback = FALLBACK_PLACES.get(mood, FALLBACK_PLACES["nature"])
if start_coords:
# Try strict distance filter first
valid_fallback = filter_places_by_distance(fallback, start_coords, min_km, max_km)
# If too few results, widen range (50% each direction)
if len(valid_fallback) < 3:
wider_min = max(0, min_km * 0.5)
wider_max = max_km * 1.5
valid_fallback = filter_places_by_distance(fallback, start_coords, wider_min, wider_max)
print(f" 📍 Widened filter to {wider_min:.1f}-{wider_max:.1f}km, got {len(valid_fallback)} places", flush=True)
# If STILL too few, use all places sorted by distance (no range filter)
if len(valid_fallback) < 3:
valid_fallback = filter_places_by_distance(fallback, start_coords, 0, 50)
print(f" 📍 Using all places sorted by distance, got {len(valid_fallback)}", flush=True)
# Final safety: if geocoding failed for all, just use raw fallback list
if not valid_fallback:
valid_fallback = fallback
else:
valid_fallback = fallback
# Exclude seen places and any already in partial_results
partial_names = {p['name'] for p in partial_results}
available = [p for p in valid_fallback if p['name'] not in seen_places and p['name'] not in partial_names]
# Merge: partial LLM results first, then fill with fallback
merged = partial_results + available
# If not enough new places, cycle back
if len(merged) < 3:
seen_places.clear()
merged = partial_results + [p for p in valid_fallback if p['name'] not in partial_names]
print(f" 📍 Returning {len(merged[:3])} places for {mood}/{time_pref}", flush=True)
return merged[:3]
# ==========================================
# 🎮 COMMAND HANDLERS
# ==========================================
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
import time as _time
user_id = str(update.effective_user.id)
username = update.effective_user.username or update.effective_user.first_name or f"User_{user_id}"
# 1. Auto-Link
telegram_links[user_id] = username
# 2. Reset Session - Button-First Flow
user_sessions[user_id] = {
"state": "AWAITING_START",
"data": {
"seen_places": [],
"mood": None,
"time": None,
},
"history": [],
"last_active": _time.time() # CRITICAL: Set timestamp to prevent immediate timeout
}
# 3. Immediately ask for starting location (skip language selection)
btn = KeyboardButton("📍 Share Current Location", request_location=True)
await update.message.reply_text(
f"👋 Welcome to **CoolRide**, {md_escape(username)}!\n\n"
"🚴 Let's find you a cool, shaded cycling route.\n\n"
"📍 **Where are you starting from?**\n"
"_Type a place name or share your location:_",
reply_markup=ReplyKeyboardMarkup([[btn]], one_time_keyboard=True, resize_keyboard=True),
parse_mode='Markdown'
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"🆘 **CoolRide Help**\n\n"
"Just use the menu buttons! If you get stuck, type /start to reset.",
parse_mode='Markdown'
)
# --- SAFE REPLY HELPER ---
async def safe_reply(update, context, text, reply_markup=None, parse_mode=None):
"""Send a message whether triggered from a message or callback query."""
user_id = str(update.effective_user.id)
if update.message:
await update.message.reply_text(text, reply_markup=reply_markup, parse_mode=parse_mode)
else:
await context.bot.send_message(chat_id=user_id, text=text, reply_markup=reply_markup, parse_mode=parse_mode)
# --- UTILITY COMMANDS ---
async def feedback_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
session = get_session(user_id)
if session["data"].get("route_id"):
keyboard = [[
InlineKeyboardButton("🥵 Hot", callback_data="rate_hot"),
InlineKeyboardButton("😐 Okay", callback_data="rate_okay"),
InlineKeyboardButton("🌳 Cool", callback_data="rate_cool"),
]]
await safe_reply(update, context,
"How was the heat on that route?",
reply_markup=InlineKeyboardMarkup(keyboard)
)
else:
await safe_reply(update, context,
"You haven't completed a route yet. Type /start to plan one, and you can rate it after! 🚴"
)
async def link_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
username = update.effective_user.username or f"User_{user_id}"
if user_id in telegram_links:
kb = [[InlineKeyboardButton("❌ Unlink Account", callback_data="auth_unlink")]]
await update.message.reply_text(f"✅ Linked as: {md_escape(telegram_links[user_id])}", reply_markup=InlineKeyboardMarkup(kb), parse_mode='Markdown')
else:
telegram_links[user_id] = username
await update.message.reply_text(f"✅ Account linked to {md_escape(username)}.", parse_mode='Markdown')
async def unlink_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
if user_id in telegram_links:
del telegram_links[user_id]
await update.message.reply_text("✅ Unlinked successfully.")
else:
await update.message.reply_text("You are not linked.")
async def report_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
get_session(user_id)
keyboard = [
[InlineKeyboardButton("☀️ Too Hot", callback_data="rep_too_hot"),
InlineKeyboardButton("🚧 Blocked", callback_data="rep_blocked")],
[InlineKeyboardButton("🌳 Shade Oasis", callback_data="rep_shade_oasis"),
InlineKeyboardButton("💧 Water Here", callback_data="rep_water_available")]
]
await safe_reply(update, context, "📢 **Field Report:** What do you see?", reply_markup=InlineKeyboardMarkup(keyboard), parse_mode='Markdown')
async def log_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
session = get_session(user_id)
session["state"] = "AWAITING_LOG_VAL"
await safe_reply(update, context, "📝 **Sensor Log**\nEnter WBGT reading (e.g., 31.5):", parse_mode='Markdown')
# Helper for amenities
async def ask_amenity_location(update, context, type_name):
user_id = str(update.effective_user.id)
session = get_session(user_id)
session["data"]["amenity_search"] = type_name
session["state"] = "AWAITING_AMENITY_LOC"
label = type_name if type_name else "Nearby Spots"
btn = KeyboardButton(f"📍 Share Location for {label}", request_location=True)
await safe_reply(update, context, f"📍 Share your location to find {label}:", reply_markup=ReplyKeyboardMarkup([[btn]], True, True))
async def food_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await ask_amenity_location(update, context, "Hawker")
async def water_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await ask_amenity_location(update, context, "Supermarket")
async def nearby_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await ask_amenity_location(update, context, None)
async def coolspot_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
session = get_session(user_id)
session["state"] = "AWAITING_COOLSPOT_LOC"
btn = KeyboardButton("📍 Share Location", request_location=True)
await update.message.reply_text(
"🌳 Found a cool shortcut or shaded spot? Send me a location pin!",
reply_markup=ReplyKeyboardMarkup([[btn]], one_time_keyboard=True, resize_keyboard=True)
)
# ==========================================
# 🖱️ CALLBACK HANDLER
# ==========================================
async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
import time as _time
query = update.callback_query
await query.answer()
user_id = str(update.effective_user.id)
data = query.data
# Session timeout check
if user_id in user_sessions:
last = user_sessions[user_id].get("last_active", 0)
if _time.time() - last > SESSION_TIMEOUT:
user_sessions[user_id] = {"state": "IDLE", "data": {"seen_places": []}, "last_active": _time.time()}
user_sessions.setdefault(user_id, {"state": "IDLE", "data": {"seen_places": []}, "last_active": _time.time()})
user_sessions[user_id]["last_active"] = _time.time()
session = user_sessions[user_id]
# --- 1. SUGGESTION FLOW (Button-First) ---
# mode_suggest: User clicked "Suggest a Place" from destination prompt
if data == "mode_suggest" or data == "mode_suggest_back":
session["state"] = "AWAITING_MOOD"
keyboard = [
[InlineKeyboardButton("🍜 Food", callback_data="mood_food"), InlineKeyboardButton("🌿 Nature", callback_data="mood_nature")],
[InlineKeyboardButton("🏛️ Museums", callback_data="mood_museums"), InlineKeyboardButton("🌇 Views", callback_data="mood_views")],
[InlineKeyboardButton("🛍️ Shopping", callback_data="mood_shopping")],
[InlineKeyboardButton("⬅️ Back", callback_data="back_to_dest")]
]
if data == "mode_suggest_back":
await context.bot.send_message(
chat_id=user_id,
text="✨ **What kind of place are you in the mood for?**",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
else:
await query.edit_message_text(
"✨ **What kind of place are you in the mood for?**",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
elif data == "back_to_dest":
session["state"] = "AWAITING_DEST"
keyboard = [[InlineKeyboardButton("✨ Suggest a Place", callback_data="mode_suggest")]]
await context.bot.send_message(
chat_id=user_id,
text="🎯 **Where do you want to go?**\n_Type a destination or let me suggest one:_",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
elif data.startswith("mood_"):
mood = data.split("_")[1]
session["data"]["mood"] = mood
session["state"] = "AWAITING_TIME"
keyboard = [
[InlineKeyboardButton("⚡ 10-15 mins", callback_data="time_short")],
[InlineKeyboardButton("🚴 15-30 mins", callback_data="time_med")],
[InlineKeyboardButton("🚴♀️ 30+ mins", callback_data="time_long")],
[InlineKeyboardButton("⬅️ Back to Moods", callback_data="mode_suggest")]
]
mood_icons = {"nature": "🌿", "food": "🍜", "views": "🌇", "museums": "🏛️", "shopping": "🛍️"}
await query.edit_message_text(
f"{mood_icons.get(mood, '✨')} **{mood.title()}** selected!\n\n"
"⏱️ **How long do you want to ride?**",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
elif data.startswith("time_") or data == "rec_refresh":
# Store time preference if this is initial selection
if data.startswith("time_"):
session["data"]["time"] = data.split("_")[1]
mood = session["data"].get("mood", "nature")
time_pref = session["data"].get("time", "med")
start_coords = session["data"].get("start_coords")
# Initialize seen_places if not exists
if "seen_places" not in session["data"]:
session["data"]["seen_places"] = []
seen = session["data"]["seen_places"]
# Show loading message
try:
await query.edit_message_text("🔍 **Finding cool spots for you...**", parse_mode='Markdown')
except:
pass # Message might already be deleted
# Show typing indicator while fetching suggestions
await context.bot.send_chat_action(chat_id=user_id, action=ChatAction.TYPING)
# Get suggestions using the new LLM-first + fallback logic (offloaded to avoid blocking event loop)
loop = asyncio.get_running_loop()
places = await loop.run_in_executor(None, get_suggestions, mood, time_pref, start_coords, seen, user_id)
# Track which places we've shown
for p in places:
if p['name'] not in seen:
seen.append(p['name'])
session["data"]["recommendations"] = places
session["state"] = "SELECTING_PLACE"
# Build keyboard with place buttons
kb = []
for i, p in enumerate(places[:3]):
# Show distance if available
dist_str = f" ({p['distance_km']}km)" if 'distance_km' in p else ""
kb.append([InlineKeyboardButton(f"📍 {p['name']}{dist_str}", callback_data=f"sel_place_{i}")])
kb.append([InlineKeyboardButton("🔁 Suggest something new", callback_data="rec_refresh")])
kb.append([InlineKeyboardButton("⬅️ Different Mood", callback_data="mode_suggest")])
# Show how many we've cycled through
cycle_info = f"\n\n_Shown {len(seen)} of {MAX_SUGGESTIONS_BEFORE_CYCLE} before refresh_" if len(seen) > 3 else ""
time_labels = {"short": "10-15 min", "med": "15-30 min", "long": "30+ min"}
mood_icons = {"nature": "🌿", "food": "🍜", "views": "🌇", "museums": "🏛️", "shopping": "🛍️"}
await context.bot.send_message(
chat_id=user_id,
text=f"🎯 **{mood_icons.get(mood, '✨')} {mood.title()} spots** ({time_labels.get(time_pref, '15-30 min')} ride):{cycle_info}",
reply_markup=InlineKeyboardMarkup(kb),
parse_mode='Markdown'
)
elif data.startswith("sel_place_"):
idx = int(data.split("_")[-1])
places = session["data"].get("recommendations", [])
if idx < len(places):
place = places[idx]
session["data"]["end_name"] = place['name']
# Get coords from place if already computed, otherwise geocode
if 'coords' in place:
session["data"]["end_coords"] = place['coords']
elif 'lat' in place and 'lon' in place:
session["data"]["end_coords"] = (place['lat'], place['lon'])
else:
loop = asyncio.get_running_loop()
coords = await loop.run_in_executor(None, geocode_location, place['name'])
if coords:
session["data"]["end_coords"] = coords
# In Button-First flow, we already have start_coords
if session["data"].get("start_coords"):
# We have both start and end, trigger route calculation
await query.edit_message_text(f"🎯 **Destination:** {md_escape(place['name'])}\n\n_Calculating your cool route..._", parse_mode='Markdown')
await handle_route_trigger(update, context, user_id)
else:
# Fallback: ask for start location (shouldn't happen in normal flow)
session["state"] = "AWAITING_START"
text = f"🎯 **Destination:** {md_escape(place['name'])}\n\n📍 **Where are you starting from?**"
btn = KeyboardButton("📍 Share Current Location", request_location=True)
await context.bot.send_message(chat_id=user_id, text=text, reply_markup=ReplyKeyboardMarkup([[btn]], True, True), parse_mode='Markdown')
# --- 3. LONG ROUTE HANDLING (Restored) ---
elif data == "confirm_long_route":
pending = session.get("pending_route")
if pending:
# Manually trigger route calc with stored coords
session["data"]["start_coords"] = pending["start"]
session["data"]["end_coords"] = pending["end"]
await trigger_route_generation(update, context, user_id)
session["pending_route"] = None
else:
await query.edit_message_text("❌ Session expired. Type /start.")
elif data == "cancel_long_route":
session["pending_route"] = None
# Clear the old destination and re-prompt
session["data"].pop("end_coords", None)
session["data"].pop("end_name", None)
session["state"] = "AWAITING_DEST"
await query.edit_message_text("👍 Route cancelled.")
keyboard = [[InlineKeyboardButton("✨ Suggest a Place", callback_data="mode_suggest")]]
await context.bot.send_message(
chat_id=user_id,
text="🎯 **Pick a closer destination:**\n_Type a place name or let me suggest one:_",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
# --- 4. POST-RIDE MENU ACTIONS ---
elif data == "act_retry_route":
if session["data"].get("start_coords") and session["data"].get("end_coords"):
await trigger_route_generation(update, context, user_id)
else:
await context.bot.send_message(chat_id=user_id, text="Session expired. Type /start to begin.")
elif data == "act_food": await ask_amenity_location(update, context, "Hawker")
elif data == "act_water": await ask_amenity_location(update, context, "Supermarket")
elif data == "act_coolspot":
session["state"] = "AWAITING_COOLSPOT_LOC"
btn = KeyboardButton("📍 Share Location", request_location=True)
await context.bot.send_message(
chat_id=user_id,
text="Found a cool shortcut or shaded spot? Send me a location pin! 📍",
reply_markup=ReplyKeyboardMarkup([[btn]], one_time_keyboard=True, resize_keyboard=True)
)
elif data == "act_report": await report_command(update, context)
elif data == "act_log": await log_command(update, context)
elif data == "act_feedback": await feedback_command(update, context)
elif data == "rate_now":
keyboard = [[
InlineKeyboardButton("🥵 Hot", callback_data="rate_hot"),
InlineKeyboardButton("😐 Okay", callback_data="rate_okay"),
InlineKeyboardButton("🌳 Cool", callback_data="rate_cool"),
]]
await context.bot.send_message(
chat_id=user_id,
text="How was the heat on that route?",
reply_markup=InlineKeyboardMarkup(keyboard)
)
elif data == "new_route":
user_sessions[user_id] = {
"state": "AWAITING_START",
"data": {"seen_places": []},
"history": [],
"last_active": _time.time()
}
btn = KeyboardButton("📍 Share Current Location", request_location=True)
await context.bot.send_message(
chat_id=user_id,
text="🔄 **New Route!**\n\n📍 **Where are you starting from?**",
reply_markup=ReplyKeyboardMarkup([[btn]], one_time_keyboard=True, resize_keyboard=True),
parse_mode='Markdown'
)
elif data == "act_restart":
# Reset session and start fresh with new Button-First flow
user_sessions[user_id] = {
"state": "AWAITING_START",
"data": {"seen_places": []},
"history": [],
"last_active": _time.time() # CRITICAL: Set timestamp
}
btn = KeyboardButton("📍 Share Current Location", request_location=True)
await context.bot.send_message(
chat_id=user_id,
text="🔄 **New Route!**\n\n📍 **Where are you starting from?**",
reply_markup=ReplyKeyboardMarkup([[btn]], one_time_keyboard=True, resize_keyboard=True),
parse_mode='Markdown'
)
# --- 5. FIELD OPS & UTILS ---
elif data == "auth_unlink":
if user_id in telegram_links:
del telegram_links[user_id]
await query.edit_message_text("✅ Account unlinked.")
else:
await query.edit_message_text("Account already unlinked.")
elif data.startswith("rep_"):
rtype = data.replace("rep_", "")
if rtype not in VALID_REPORT_TYPES:
await query.edit_message_text("❌ Invalid report type.")
return
session["data"]["report_type"] = rtype
session["state"] = "AWAITING_REPORT_LOC"
btn = KeyboardButton("📍 Share Location", request_location=True)
await context.bot.send_message(chat_id=user_id, text="📍 Share location to report:", reply_markup=ReplyKeyboardMarkup([[btn]], True, True))
elif data.startswith("tg_rate_"):
rating = data.split("_")[-1] # Extract "5", "3", or "1" from "tg_rate_5"
if _supabase:
try:
_supabase.table('feedback_logs').insert({
"user_email": telegram_links.get(user_id, f"tg_{user_id}"),
"sentiment": "positive" if int(rating) >= 4 else ("neutral" if int(rating) >= 3 else "negative"),
"user_comment": f"[{rating}⭐ rating]",
}).execute()
print(f" ⭐ Telegram rating: {rating} stars from {user_id}", flush=True)
except Exception as e:
print(f" ⚠️ Feedback DB error: {e}", flush=True)
else:
print(f" ⚠️ Feedback skipped - no DB connection", flush=True)
await query.edit_message_text(f"⭐ {rating}-star rating saved. Thank you!")
elif data.startswith("fb_star_"):
stars = data.split("_")[-1] # "5", "4", "3", "2", "1"
session["data"]["fb_stars"] = int(stars)
keyboard = [
[InlineKeyboardButton("💬 Add a Comment", callback_data="fb_comment")],
[InlineKeyboardButton("✅ Done", callback_data="fb_done")]
]
await query.edit_message_text(
f"⭐ {stars}-star rating selected!\n\nWant to add a comment?",
reply_markup=InlineKeyboardMarkup(keyboard)
)
elif data == "fb_comment":
session["state"] = "AWAITING_FEEDBACK"
await query.edit_message_text("💬 Type your comment below:")
elif data == "fb_done":
# Save star-only feedback
stars = session["data"].get("fb_stars", 3)
sentiment = "positive" if stars >= 4 else ("neutral" if stars >= 3 else "negative")
if _supabase:
try:
_supabase.table('feedback_logs').insert({
"user_email": telegram_links.get(user_id, f"tg_{user_id}"),
"sentiment": sentiment,
"user_comment": f"[{stars}⭐ rating]",
}).execute()
print(f" ⭐ Feedback saved: {stars} stars from {user_id}", flush=True)
except Exception as e:
print(f" ⚠️ Feedback DB error: {e}", flush=True)
else:
print(f" ⚠️ Feedback skipped - no DB connection", flush=True)
session["data"].pop("fb_stars", None)
session["state"] = "IDLE"
await query.edit_message_text(f"⭐ {stars}-star feedback saved. Thank you!")
# --- 6. POST-RIDE THERMAL RATING ---
elif data in ("rate_hot", "rate_okay", "rate_cool"):
rating_map = {"rate_hot": "hot", "rate_okay": "okay", "rate_cool": "cool"}
rating = rating_map[data]
route_id = session["data"].get("route_id", "")
route_start = session["data"].get("start_name", "")
route_end = session["data"].get("end_name", "")
if _supabase:
try:
_supabase.table('ride_ratings').insert({
"user_id": user_id,
"route_id": route_id,
"rating": rating,
"route_start": route_start,
"route_end": route_end,
}).execute()
print(f" 🌡️ Ride rating: {rating} from {user_id} for route {route_id}", flush=True)
except Exception as e:
print(f" ⚠️ Ride rating DB error: {e}", flush=True)
session["data"]["rated"] = True
await query.edit_message_text("Thanks! Your feedback helps make routes cooler for everyone.")
else:
await query.answer("This option has expired.", show_alert=True)
await query.message.reply_text(
"That option is no longer available. Type /start to plan a new route! 🚴"
)
# ==========================================
# 📍 LOCATION & LOGIC
# ==========================================
async def handle_location(update: Update, context: ContextTypes.DEFAULT_TYPE):
import time as _time
user_id = str(update.effective_user.id)
loc = update.message.location
session = get_session(user_id)
session["last_active"] = _time.time()
if not is_in_singapore(loc.latitude, loc.longitude):
await update.message.reply_text("🚫 Outside Singapore.")
return
# A. SENSOR LOGGING
if session.get("state") == "AWAITING_LOG_LOC":
val = session["data"].get("log_val")
nea_temp, station = get_realtime_weather(loc.latitude, loc.longitude)
if _supabase:
try:
_supabase.table('sensor_logs').insert({
"user_id": telegram_links.get(user_id, f"tg_{user_id}"),
"lat": loc.latitude, "lon": loc.longitude,
"wbgt_value": val,
"nea_temp": nea_temp,
"weather_station": station,
"notes": "Field Test"
}).execute()
print(f" ✅ Sensor log saved: user={user_id}, wbgt={val}, nea={nea_temp}", flush=True)
except Exception as e:
print(f" ⚠️ Sensor log DB error: {e}", flush=True)
import traceback
traceback.print_exc()
await update.message.reply_text(f"✅ **Data Logged!**\n🌡️ Sensor: {val}°C\n📡 NEA: {nea_temp}°C", parse_mode='Markdown', reply_markup=ReplyKeyboardRemove())
session["state"] = "IDLE"
return
# B. REPORTING
if session.get("state") == "AWAITING_REPORT_LOC":
if _supabase:
try:
_supabase.table('community_reports').insert({
"user_email": telegram_links.get(user_id, f"tg_{user_id}"),
"lat": loc.latitude, "lon": loc.longitude,
"report_type": session["data"].get("report_type", "unknown"),
"description": "Telegram Report"
}).execute()
print(f" 📢 Report saved from {user_id}", flush=True)
except Exception as e:
print(f" ⚠️ Report DB error: {e}", flush=True)
await update.message.reply_text("✅ Report pinned!", reply_markup=ReplyKeyboardRemove())
session["state"] = "IDLE"
return
# C. COOL SPOT PINNING
if session.get("state") == "AWAITING_COOLSPOT_LOC":
if _supabase:
try:
_supabase.table('cool_spots').insert({
"user_id": user_id,
"latitude": loc.latitude,
"longitude": loc.longitude,
}).execute()
print(f" 🌳 Cool spot logged: user={user_id}, lat={loc.latitude}, lon={loc.longitude}", flush=True)
except Exception as e:
print(f" ⚠️ Cool spot DB error: {e}", flush=True)
await update.message.reply_text(
f"🌳 Cool spot logged at [{loc.latitude:.5f}, {loc.longitude:.5f}]! We'll check this area for shade.",
reply_markup=ReplyKeyboardRemove()
)
session["state"] = "IDLE"
return
# E. AMENITY SEARCH
if session.get("state") == "AWAITING_AMENITY_LOC":
amenity_type = session["data"].get("amenity_search")
nearby = find_nearby_amenities(loc.latitude, loc.longitude, _amenities_data, amenity_type, limit=3)
if nearby:
response = f"📍 **Nearby {amenity_type or 'Spots'}:**\n\n"
for i, p in enumerate(nearby, 1):
dist = int(p['distance']*1000)
icon = "🍜" if p['type'] == 'Hawker' else "💧"
response += f"{i}. {icon} *{md_escape(p['name'])}* ({dist}m)\n"
await update.message.reply_text(response, parse_mode='Markdown', reply_markup=ReplyKeyboardRemove())
else:
await update.message.reply_text("😕 No spots found.", reply_markup=ReplyKeyboardRemove())
session["state"] = "IDLE"
return
# D. ROUTE START (DEFAULT) - Button-First Flow
session["data"]["start_coords"] = (loc.latitude, loc.longitude)
session["data"]["start_name"] = "Current Location"
if "end_coords" in session["data"]:
# Already have destination, trigger route calculation
await handle_route_trigger(update, context, user_id)
else:
# Show destination prompt with "Suggest a Place" button
session["state"] = "AWAITING_DEST"
keyboard = [[InlineKeyboardButton("✨ Suggest a Place", callback_data="mode_suggest")]]
await update.message.reply_text(
"📍 **Got it!** Starting from your current location.\n\n"
"🎯 **Where do you want to go?**\n"
"_Type a destination or let me suggest one:_",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
await context.bot.send_message(
chat_id=user_id,
text="_You can also type a place name directly._",
parse_mode='Markdown',
reply_markup=ReplyKeyboardRemove()
)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
import time as _time
user_id = str(update.effective_user.id)
text = update.message.text
# Session timeout check
if user_id in user_sessions:
last = user_sessions[user_id].get("last_active", 0)
if _time.time() - last > SESSION_TIMEOUT:
user_sessions[user_id] = {"state": "IDLE", "data": {"seen_places": []}, "last_active": _time.time()}
user_sessions.setdefault(user_id, {"state": "IDLE", "data": {"seen_places": []}, "last_active": _time.time()})
user_sessions[user_id]["last_active"] = _time.time()
session = user_sessions[user_id]
state = session.get("state")
# TRIGGER - If user types "suggest" or "recommend" (only in IDLE/AWAITING_DEST states)
if state in ("IDLE", "AWAITING_DEST", None) and (text.lower().strip() in ("suggest", "recommend", "suggest a place") or
(len(text.split()) <= 4 and ("suggest" in text.lower() or "recommend" in text.lower()))):
# Only allow if we have a starting point
if not session["data"].get("start_coords"):
btn = KeyboardButton("📍 Share Current Location", request_location=True)
await update.message.reply_text(
"📍 **First, tell me where you're starting from!**\n"
"_Share your location or type a place name._",
reply_markup=ReplyKeyboardMarkup([[btn]], one_time_keyboard=True, resize_keyboard=True),
parse_mode='Markdown'
)
session["state"] = "AWAITING_START"
return
session["state"] = "AWAITING_MOOD"
keyboard = [
[InlineKeyboardButton("🍜 Food", callback_data="mood_food"), InlineKeyboardButton("🌿 Nature", callback_data="mood_nature")],
[InlineKeyboardButton("🏛️ Museums", callback_data="mood_museums"), InlineKeyboardButton("🌇 Views", callback_data="mood_views")],
[InlineKeyboardButton("🛍️ Shopping", callback_data="mood_shopping")]
]
await update.message.reply_text(
"✨ **What kind of place are you in the mood for?**",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
return
# 1. FEEDBACK
if state == "AWAITING_FEEDBACK":
stars = session["data"].get("fb_stars")
if stars:
sentiment = "positive" if stars >= 4 else ("neutral" if stars >= 3 else "negative")
comment = f"[{stars}⭐] {text}"
else:
sentiment = "neutral"
comment = text
if _supabase:
try:
_supabase.table('feedback_logs').insert({
"user_email": telegram_links.get(user_id, f"tg_{user_id}"),
"sentiment": sentiment,
"user_comment": comment,
}).execute()
print(f" ⭐ Feedback saved from {user_id}: {stars or 'no'} stars + comment", flush=True)
except Exception as e:
print(f" ⚠️ Feedback DB error: {e}", flush=True)
else:
print(f" ⚠️ Feedback skipped - no DB connection", flush=True)
session["data"].pop("fb_stars", None)
reply = f"⭐ {stars}-star rating + comment saved. Thank you!" if stars else "✅ Feedback saved. Thank you!"
await update.message.reply_text(reply)
session["state"] = "IDLE"
return
# 2. LOGGING
if state == "AWAITING_LOG_VAL":
try:
session["data"]["log_val"] = float(text)
session["state"] = "AWAITING_LOG_LOC"
btn = KeyboardButton("📍 Share Location", request_location=True)
await update.message.reply_text(f"📉 Reading: **{text}°C**\nShare location:", reply_markup=ReplyKeyboardMarkup([[btn]], True, True), parse_mode='Markdown')
except: await update.message.reply_text("⚠️ Invalid number.")
return
# 2b. MOOD/TIME - Prompt user to use buttons
if state in ("AWAITING_MOOD", "AWAITING_TIME", "SELECTING_PLACE"):
await update.message.reply_text("👆 Please use the buttons above to continue!")
return
# 3. START - Button-First Flow
if state == "AWAITING_START":
coords = geocode_location(text)
if coords:
session["data"]["start_coords"] = coords
session["data"]["start_name"] = text
if "end_coords" in session["data"]:
await handle_route_trigger(update, context, user_id)
else:
# Show destination prompt with "Suggest a Place" button
session["state"] = "AWAITING_DEST"
keyboard = [[InlineKeyboardButton("✨ Suggest a Place", callback_data="mode_suggest")]]
await update.message.reply_text(
f"📍 **Starting from:** {md_escape(text)}\n\n"
"🎯 **Where do you want to go?**\n"
"_Type a destination or let me suggest one:_",
reply_markup=InlineKeyboardMarkup(keyboard),
parse_mode='Markdown'
)
else:
await update.message.reply_text("❌ Couldn't find that place. Try another name or share your location.")
# 4. DEST
elif state == "AWAITING_DEST":
coords = geocode_location(text)
if coords:
session["data"]["end_coords"] = coords
session["data"]["end_name"] = text
await handle_route_trigger(update, context, user_id)
else:
await update.message.reply_text("❌ Unknown destination.")
# 5. GENERAL
else:
# If short text without question mark, might be a place name
if len(text.split()) <= 4 and '?' not in text:
await update.message.reply_text(
"💡 Did you mean to search for a place?\n"
"Type /start to plan a new route, or ask me a question about cycling in Singapore!",
parse_mode='Markdown'
)
return
response = chat_with_groq(text, user_id)
clean, hidden = extract_clean_reply(response)
await update.message.reply_text(clean)
if hidden and "start" in hidden and "end" in hidden:
s = geocode_location(hidden["start"])
e = geocode_location(hidden["end"])
if s and e:
session["data"]["start_coords"] = s; session["data"]["start_name"] = hidden["start"]
session["data"]["end_coords"] = e; session["data"]["end_name"] = hidden["end"]
await handle_route_trigger(update, context, user_id)
# --- ROUTE LOGIC WITH DISTANCE CHECK ---
async def handle_route_trigger(update, context, user_id):
"""Checks distance before calculating."""
session = user_sessions[user_id]
data = session["data"]
start = data.get("start_coords")
end = data.get("end_coords")
if not start or not end: return
# Distance Check (Restored Feature)
dist_km = haversine_distance(start[0], start[1], end[0], end[1])
if dist_km > MAX_ROUTE_DISTANCE_KM:
session["pending_route"] = {"start": start, "end": end}
kb = [[InlineKeyboardButton("✅ Yes, go", callback_data="confirm_long_route"),
InlineKeyboardButton("❌ No, cancel", callback_data="cancel_long_route")]]
await context.bot.send_message(chat_id=user_id, text=f"⚠️ **Long Route Alert!**\nDistance: ~{dist_km:.1f} km.\nAre you sure?", reply_markup=InlineKeyboardMarkup(kb), parse_mode='Markdown')
else:
await trigger_route_generation(update, context, user_id)
session["state"] = "IDLE"
async def trigger_route_generation(update, context, user_id):
import time as _time
session = user_sessions[user_id]
data = session["data"]
start, end = data.get("start_coords"), data.get("end_coords")
await context.bot.send_chat_action(chat_id=user_id, action=ChatAction.TYPING)
msg = await context.bot.send_message(chat_id=user_id, text="🚴 **Calculating...**", parse_mode='Markdown')
log("🚴", "Telegram route request", user=user_id)
if _compute_route_fn:
t_route = _time.time()
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(None, _compute_route_fn, start, end, None, f"tg_{user_id}")
log("🚴", "Telegram route computed", user=user_id, ms=f"{(_time.time()-t_route)*1000:.0f}")
if res and res.get("status") == "success":
route_id = _cache_route_fn(res)
session["data"]["route_id"] = route_id
stats = res["stats"]
tg_user = telegram_links.get(user_id, "Rider")
s_name = quote(data.get("start_name", "Start"))
e_name = quote(data.get("end_name", "End"))
link = f"{APP_URL}?route_id={route_id}&tg={user_id}&tg_user={quote(tg_user)}&start_name={s_name}&end_name={e_name}"
await context.bot.edit_message_text(
chat_id=user_id, message_id=msg.message_id,
text=f"✅ **Route Found!**\n"
f"📍 {md_escape(data.get('start_name', 'Start'))} → {md_escape(data.get('end_name', 'End'))}\n"
f"🌡️ {stats.get('temp')}°C | 🌿 {stats.get('shade_gain')}\n"
f"🚴 {stats.get('cool_dist')} | ⏱️ {stats.get('cool_eta')}",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🚀 Start Navigation", url=link)]]),
parse_mode='Markdown'
)
keyboard = [
[InlineKeyboardButton("🍜 Nearby Food", callback_data="act_food"), InlineKeyboardButton("💧 Nearby Water", callback_data="act_water")],
[InlineKeyboardButton("🌡️ Rate This Route", callback_data="rate_now"), InlineKeyboardButton("🌳 Pin Cool Spot", callback_data="act_coolspot")],
[InlineKeyboardButton("🔁 New Route", callback_data="new_route")],
]
await context.bot.send_message(chat_id=user_id, text="👇 **What's Next?**", reply_markup=InlineKeyboardMarkup(keyboard), parse_mode='Markdown')
asyncio.create_task(_send_rating_prompt(context, user_id, route_id))
else:
kb = [
[InlineKeyboardButton("🔄 Try Again", callback_data="act_retry_route")],
[InlineKeyboardButton("🔁 New Route", callback_data="act_restart")]
]
await context.bot.edit_message_text(
chat_id=user_id, message_id=msg.message_id,
text="❌ *Route calculation failed.*\nThis can happen with very long distances or unusual locations.\n\nTry a different destination or start fresh.",
reply_markup=InlineKeyboardMarkup(kb),
parse_mode='Markdown'
)
# --- POST-RIDE RATING PROMPT ---
async def _send_rating_prompt(context, user_id: str, route_id: str):
"""Sent 5 minutes after route delivery to collect thermal comfort rating."""
await asyncio.sleep(300)
# Skip if the user already rated via the immediate button
if user_sessions.get(user_id, {}).get("data", {}).get("rated"):
return
keyboard = [[
InlineKeyboardButton("🥵 Hot", callback_data="rate_hot"),
InlineKeyboardButton("😐 Okay", callback_data="rate_okay"),
InlineKeyboardButton("🌳 Cool", callback_data="rate_cool"),
]]
try:
await context.bot.send_message(
chat_id=user_id,
text="How was the heat on that route?",
reply_markup=InlineKeyboardMarkup(keyboard)
)
except Exception as e:
print(f" ⚠️ Rating prompt failed for {user_id}: {e}", flush=True)
# --- BOILERPLATE ---
async def setup_bot_commands(application):
from telegram import BotCommand
commands = [
BotCommand("start", "🔄 Main Menu"),
BotCommand("report", "📢 Report"),
BotCommand("log", "📝 Log Sensor"),
BotCommand("coolspot", "🌳 Pin Cool Spot"),
BotCommand("link", "🔗 Accounts"),
BotCommand("help", "🆘 Help")
]
await application.bot.set_my_commands(commands)
def setup_telegram_handlers(application):
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("link", link_command))
application.add_handler(CommandHandler("food", food_command))
application.add_handler(CommandHandler("water", water_command))
application.add_handler(CommandHandler("report", report_command))
application.add_handler(CommandHandler("log", log_command))
application.add_handler(CommandHandler("feedback", feedback_command))
application.add_handler(CommandHandler("unlink", unlink_command))
application.add_handler(CommandHandler("nearby", nearby_command))
application.add_handler(CommandHandler("coolspot", coolspot_command))
application.add_handler(CallbackQueryHandler(handle_callback))
application.add_handler(MessageHandler(filters.LOCATION, handle_location))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
def run_telegram_bot(token):
global telegram_bot
if not token: return
async def start_bot():
global telegram_bot
print(" 🤖 Telegram Polling...", flush=True)
app = Application.builder().token(token).build()
setup_telegram_handlers(app)
await setup_bot_commands(app)
await app.initialize()
await app.start()
telegram_bot = app.bot
await app.updater.start_polling(drop_pending_updates=True)
while True: await asyncio.sleep(1)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(start_bot())
def init_telegram_webhook(token):
global telegram_application, telegram_bot, _webhook_thread
if not token: return None
from telegram import Bot
from telegram.ext import ApplicationBuilder
from telegram.request import HTTPXRequest
def loop_runner():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
global _webhook_loop
_webhook_loop = loop
loop.run_forever()
_webhook_thread = threading.Thread(target=loop_runner, daemon=True)
_webhook_thread.start()
import time
while _webhook_loop is None: time.sleep(0.1)
proxy_base = os.environ.get("TELEGRAM_PROXY_URL", "https://coolride-telegram-proxy-production.up.railway.app").rstrip("/")
proxy_url = proxy_base + "/bot"
telegram_bot = Bot(token=token, base_url=proxy_url)
telegram_application = ApplicationBuilder().token(token).base_url(proxy_url).request(HTTPXRequest(http_version="1.1", connect_timeout=60, read_timeout=60, write_timeout=60, pool_timeout=60)).build()
setup_telegram_handlers(telegram_application)
webhook_url = f"{APP_URL.rstrip('/')}/telegram/webhook"
async def init_with_retry():
attempt = 0
delay = 30
while True:
attempt += 1
try:
await telegram_application.initialize()
await telegram_application.bot.set_webhook(url=webhook_url)
await setup_bot_commands(telegram_application)
print(f" ✅ Telegram initialized successfully (attempt {attempt}), webhook: {webhook_url}", flush=True)
return
except Exception as e:
print(f" ⚠️ Telegram init attempt {attempt} failed: {e}. Retrying in {delay}s...", flush=True)
await asyncio.sleep(delay)
delay = min(delay * 2, 300) # exponential backoff, cap at 5 min
asyncio.run_coroutine_threadsafe(init_with_retry(), _webhook_loop)
return telegram_application
def get_webhook_loop(): return _webhook_loop
def get_telegram_bot(): return telegram_bot
def get_telegram_application(): return telegram_application
"""
CoolRide Telegram Bot - Master Logic (V16.10 - Final Audit)
Features: Smart Recs, Auto-Link, Sensor+NEA Logs, Post-Ride Menu.
Restored: Long Route Safety Checks & Full Utility Suite.
"""
import os
import json
import re
import asyncio
import threading
from urllib.parse import quote
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.constants import ChatAction
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
from config import APP_URL, GROQ_SYSTEM_PROMPT, MAX_ROUTE_DISTANCE_KM, FALLBACK_PLACES, TIME_DISTANCE_MAP, MAX_SUGGESTIONS_BEFORE_CYCLE, SESSION_TIMEOUT
from helpers import geocode_location, haversine_distance, parse_route_request, find_nearby_amenities, is_in_singapore, parse_recommendations, get_realtime_weather, filter_places_by_distance, log
# --- SHARED STATE ---
user_sessions = {}
_session_lock = threading.Lock()
telegram_links = {}
VALID_REPORT_TYPES = {"too_hot", "blocked", "shade_oasis", "water_available"}
def get_session(user_id):
"""Thread-safe session initialization and retrieval."""
with _session_lock:
if user_id not in user_sessions:
user_sessions[user_id] = {"state": "IDLE", "data": {}}
return user_sessions[user_id]
def md_escape(text: str) -> str:
"""Escape Markdown V1 special characters in user-provided strings."""
if not text:
return text
for ch in ('_', '*', '`', '['):
text = text.replace(ch, f'\\{ch}')
return text
# --- DEPENDENCIES ---
_supabase = None
_groq_client = None
_amenities_data = []
_compute_route_fn = None
_cache_route_fn = None
_G = None
# Telegram Instances
telegram_bot = None
telegram_application = None
_webhook_loop = None
_webhook_thread = None
# --- INITIALIZATION ---
def init_telegram_module(supabase_client, groq_client, amenities_data, compute_route_fn, cache_route_fn, graph):
global _supabase, _groq_client, _amenities_data, _compute_route_fn, _cache_route_fn, _G
_supabase = supabase_client
_groq_client = groq_client
_amenities_data = amenities_data
_compute_route_fn = compute_route_fn
_cache_route_fn = cache_route_fn
_G = graph
# --- LLM ENGINE ---
def chat_with_groq(user_message: str, user_id: str, context_instruction: str = "") -> str:
if not _groq_client: return "Sorry, AI is offline."
session = user_sessions.get(user_id, {})
history = session.get("history", [])
lang_pref = session.get("data", {}).get("language", "English")
sys_prompt = GROQ_SYSTEM_PROMPT + f"\nUSER CONTEXT: Language: {lang_pref}. {context_instruction}"
messages = [{"role": "system", "content": sys_prompt}] + history[-6:]
messages.append({"role": "user", "content": user_message})
try:
response = _groq_client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=messages,
temperature=0.7,
max_tokens=500
)
reply = response.choices[0].message.content
# Update conversation history for multi-turn context
if "history" in session:
session["history"].append({"role": "user", "content": user_message})
session["history"].append({"role": "assistant", "content": reply})
# Keep last 6 exchanges (12 messages)
if len(session["history"]) > 12:
session["history"] = session["history"][-12:]
return reply
except Exception as e:
print(f" ⚠️ Groq Error: {e}", flush=True)
return "I'm having trouble thinking right now."
def extract_clean_reply(llm_response: str) -> tuple:
json_data = parse_route_request(llm_response)
if not json_data:
recs = parse_recommendations(llm_response)