File size: 2,438 Bytes
ea754c5
 
 
32d20a9
 
 
ea754c5
 
32d20a9
ea754c5
 
32d20a9
 
 
 
 
 
 
 
ea754c5
 
 
 
32d20a9
ea754c5
 
 
 
32d20a9
 
ea754c5
 
32d20a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea754c5
 
 
 
 
 
 
 
32d20a9
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
import os
import requests
import telebot
from fastapi import FastAPI, Request

# سحب التوكنات المخفية
HF_TOKEN = os.getenv("HF_TOKEN")
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SPACE_ID = os.getenv("SPACE_ID") # متغير بيوفره Hugging Face لوحده

bot = telebot.TeleBot(TELEGRAM_TOKEN)
app = FastAPI()

# تجميع رابط المنصة عشان نربطه بتليجرام
if SPACE_ID:
    USER, SPACE = SPACE_ID.split('/')
    WEBHOOK_URL = f"https://{USER.lower()}-{SPACE.lower()}.hf.space/webhook"
else:
    WEBHOOK_URL = None

def get_ai_response(user_message):
    headers = {"Authorization": f"Bearer {HF_TOKEN}"}
    api_url = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct/v1/chat/completions"
    data = {"messages": [{"role": "user", "content": user_message}], "max_tokens": 1000}
    try:
        response = requests.post(api_url, headers=headers, json=data)
        if response.status_code == 200:
            return response.json()["choices"][0]["message"]["content"]
        return "النموذج بيحمل دلوقتي، جرب تاني كمان ثواني."
    except:
        return "حصل خطأ في الاتصال بالذكاء الاصطناعي."

# أول ما المنصة تشتغل، تبلغ تليجرام بالرابط
@app.on_event("startup")
def on_startup():
    if WEBHOOK_URL:
        bot.remove_webhook()
        bot.set_webhook(url=WEBHOOK_URL)

# المسار اللي تليجرام هيبعت عليه الرسايل
@app.post("/webhook")
async def webhook(request: Request):
    update = await request.json()
    update_obj = telebot.types.Update.de_json(update)
    bot.process_new_updates([update_obj])
    return {"status": "ok"}

# عشان المنصة متبقاش فاضية لو فتحت الرابط
@app.get("/")
def read_root():
    return "البوت شغال ومربوط بتليجرام بنجاح! 🚀"

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, "أهلاً بيك يا غالي! أنا بوت ذكاء اصطناعي، اسألني في أي حاجة.")

@bot.message_handler(func=lambda message: True)
def handle_message(message):
    msg = bot.reply_to(message, "ثواني بجمع الإجابة... ⏳")
    ai_response = get_ai_response(message.text)
    bot.edit_message_text(chat_id=message.chat.id, message_id=msg.message_id, text=ai_response)