Spaces:
Sleeping
Sleeping
import os | |
import logging | |
from flask import Flask | |
from telegram import Update | |
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters | |
import google.generativeai as genai | |
# ==== CONFIG ==== | |
TELEGRAM_TOKEN = "7745816717:AAGKTpRtuPknjRAIct_2kdoANpJx3ZFztrg" | |
GEMINI_API_KEY = "AIzaSyCq23lcvpPfig6ifq1rmt-z11vKpMvDD4I" | |
# ==== LOGGING ==== | |
logging.basicConfig( | |
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO | |
) | |
logger = logging.getLogger(__name__) | |
# ==== GEMINI AI SETUP ==== | |
genai.configure(api_key=GEMINI_API_KEY) | |
model = genai.GenerativeModel("gemini-pro") | |
# ==== FLASK APP ==== | |
flask_app = Flask(__name__) | |
def home(): | |
return "✅ Telegram AI Chatbot is running on port 7860!" | |
# ==== TELEGRAM BOT HANDLERS ==== | |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
await update.message.reply_text("👋 Hi! I am your AI friend. How can I help you today?") | |
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
user_message = update.message.text | |
try: | |
response = model.generate_content(user_message) | |
reply = response.text if response.text else "⚠️ I couldn’t generate a reply." | |
except Exception as e: | |
logger.error(e) | |
reply = "❌ Something went wrong while generating response." | |
await update.message.reply_text(reply) | |
# ==== TELEGRAM BOT RUNNER ==== | |
def run_telegram_bot(): | |
app = ApplicationBuilder().token(TELEGRAM_TOKEN).build() | |
app.add_handler(CommandHandler("start", start)) | |
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat)) | |
app.run_polling() | |
# ==== MAIN ==== | |
if __name__ == "__main__": | |
import threading | |
# Run Telegram bot in a separate thread | |
threading.Thread(target=run_telegram_bot, daemon=True).start() | |
# Run Flask server on 0.0.0.0:7860 | |
flask_app.run(host="0.0.0.0", port=7860) | |