Milleage-tracker / telegram_bot.py
yukee1992's picture
Create telegram_bot.py
13befe4 verified
Raw
History Blame Contribute Delete
1.7 kB
import os
import requests
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
# Your Hugging Face Space URL (replace YOUR_USERNAME with your username)
# Example: https://mileage-tracker-YOUR_USERNAME.hf.space
HF_SPACE_URL = "https://YOUR_USERNAME-mileage-tracker.hf.space"
# Get bot token from Hugging Face secret
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Forward message to Hugging Face Space"""
user_id = update.effective_user.id
text = update.message.text
# Send to our FastAPI endpoint
try:
response = requests.post(
f"{HF_SPACE_URL}/webhook",
json={"user_id": user_id, "text": text},
timeout=30
)
result = response.json()
if "reply" in result:
await update.message.reply_text(result["reply"])
# If there's a file attached, send it
if "file" in result and result["file"]:
# For now, we'll just mention the file
await update.message.reply_text("πŸ“Ž Report generated! (File download coming soon)")
except Exception as e:
await update.message.reply_text(f"❌ Error: {str(e)}")
def main():
"""Start the bot"""
app = Application.builder().token(BOT_TOKEN).build()
# Handle all text messages
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
print("πŸ€– Telegram bot is running...")
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()