File size: 2,901 Bytes
a9fdb06
7993fc2
8f21498
7993fc2
 
138db9e
8f21498
7993fc2
8f21498
7993fc2
 
8f21498
138db9e
a9fdb06
 
73daa36
138db9e
7c0956d
138db9e
 
 
 
a9fdb06
951d89b
 
 
 
 
 
 
 
8f21498
 
a9fdb06
8f21498
a9fdb06
 
 
 
 
7c0956d
138db9e
951d89b
 
8f21498
951d89b
 
 
 
 
 
 
 
 
a9fdb06
8f21498
a9fdb06
951d89b
40b1998
8f21498
 
 
 
 
 
a9fdb06
8f21498
 
 
 
 
 
 
 
 
 
 
 
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
import os
import asyncio
import threading
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from transformers import pipeline
import gradio as gr

# Telegram bot token (from environment variable)
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")

# Load AI model for text generation
generator = pipeline("text-generation", model="distilgpt2")

# Telegram bot handlers
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hello! I'm a chatbot powered by an AI model. Send me a message, and I'll respond!")

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_message = update.message.text
    response = generator(user_message, max_length=50, num_return_sequences=1, truncation=True)[0]['generated_text']
    await update.message.reply_text(response)

async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(f"Error occurred: {context.error}")
    if "Conflict" in str(context.error):
        await context.bot.send_message(
            chat_id=update.effective_chat.id if update else None,
            text="Bot conflict detected. Restarting..."
        )

# Telegram bot logic
async def telegram_bot():
    if not TELEGRAM_BOT_TOKEN:
        print("Telegram bot token not found. Please set TELEGRAM_BOT_TOKEN.")
        return

    application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()

    # Add handlers
    application.add_handler(CommandHandler("start", start))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    application.add_error_handler(error_handler)

    # Clear webhook and updates
    print("Clearing any existing webhook and updates...")
    try:
        await application.bot.delete_webhook(drop_pending_updates=True)
        updates = await application.bot.get_updates(timeout=1)
        if updates:
            last_update_id = updates[-1].update_id
            await application.bot.get_updates(offset=last_update_id + 1, timeout=1)
    except Exception as e:
        print(f"Error clearing updates: {e}")

    # Start bot polling
    print("Starting Telegram bot...")
    await application.run_polling(allowed_updates=Update.ALL_TYPES)

# Gradio logic
def gradio_app():
    iface = gr.Interface(fn=lambda x: "Hello " + x, inputs="text", outputs="text")
    iface.launch()

# Combine both
if __name__ == "__main__":
    # Step 1: Start Gradio in a separate thread
    gradio_thread = threading.Thread(target=gradio_app)
    gradio_thread.start()

    # Step 2: Start Telegram bot in the main thread, handling event loop properly
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

    loop.run_until_complete(telegram_bot())