Spaces:
Sleeping
Sleeping
from flask import Flask, request | |
import telebot | |
import os | |
import requests | |
import google.generativeai as genai | |
import tempfile | |
import logging | |
import re | |
from telebot.apihelper import ApiTelegramException | |
import time | |
from huggingface_hub import webhook_endpoint, WebhookPayload | |
from gradio import Interface | |
# Replace with your actual API keys and bot token | |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE' | |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM' | |
WEBHOOK_URL = f"https://measmonysuon-flyingbird.hf.space/bot{BOT_TOKEN}" | |
# Initialize the Telegram bot | |
bot = telebot.TeleBot(BOT_TOKEN) | |
# Configure logging | |
logging.basicConfig( | |
level=logging.DEBUG, | |
format='%(asctime)s - %(levelname)s - %(message)s', | |
handlers=[ | |
logging.FileHandler('bot_debug.log'), | |
logging.StreamHandler() | |
] | |
) | |
logger = logging.getLogger(__name__) | |
def set_webhook(): | |
"""Sets the webhook for the Telegram bot.""" | |
try: | |
response = requests.get(f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook?url={WEBHOOK_URL}") | |
result = response.json() | |
if result.get('ok'): | |
logger.info("Webhook set successfully.") | |
else: | |
logger.error(f"Failed to set webhook: {result}") | |
except requests.exceptions.RequestException as e: | |
logger.error(f"Request exception: {e}") | |
async def handle_update(payload: WebhookPayload) -> None: | |
"""Handles incoming updates from Telegram.""" | |
logger.debug(f"Received payload: {payload}") | |
if payload.message: | |
message_text = payload.message.get('text') | |
chat_id = payload.message.get('chat').get('id') | |
if message_text: | |
try: | |
# Generate a response using Google Generative AI or predefined responses | |
prompt = f"Respond to the user: {message_text}" | |
response = requests.post( | |
"https://api.your-ai-service.com/generate", # Replace with your AI service URL | |
json={"prompt": prompt, "api_key": GOOGLE_API_KEY} | |
).json() | |
response_text = response.get('text', 'Sorry, I didn\'t understand that.') | |
# Send the response back to the chat | |
bot.send_message(chat_id, response_text, parse_mode='Markdown') | |
logger.info(f"Response sent to chat_id {chat_id}") | |
except Exception as e: | |
logger.error(f"Error during message processing: {e}") | |
bot.send_message(chat_id, "Sorry, I can't answer this query right now.", parse_mode='Markdown') | |
# Initialize the Gradio interface | |
iface = Interface(fn=handle_update, inputs=[], outputs=[]) | |
# Run the Gradio app | |
if __name__ == "__main__": | |
set_webhook() # Set the webhook for Telegram | |
iface.launch() |