File size: 2,089 Bytes
15940e2
57c7885
d83a32f
57c7885
15940e2
57c7885
15940e2
57c7885
 
 
 
 
 
 
 
 
 
15940e2
57c7885
 
15940e2
d83a32f
15940e2
 
 
 
d83a32f
 
 
 
15940e2
 
 
 
 
 
 
d83a32f
57c7885
d83a32f
57c7885
 
 
 
 
 
 
 
 
 
 
ebb0d51
 
57c7885
 
 
 
 
 
 
d83a32f
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 threading
import telebot
from telebot import apihelper
from huggingface_hub import InferenceClient
from flask import Flask

# Принудительно выставляем огромные таймауты
apihelper.CONNECT_TIMEOUT = 90
apihelper.READ_TIMEOUT = 90

# Инициализация Flask (чтобы HF думал, что это сайт)
app = Flask(__name__)

@app.route('/')
def home():
    return "Бот активен и работает!"

# Настройка бота
HF_TOKEN = os.environ.get("HF_TOKEN")
client = InferenceClient(token=HF_TOKEN)

TG_TOKEN = "8531345451:AAE8qJlFEwIcuQdUiIFk2viZS9xLLMk2c_o"
bot = telebot.TeleBot(TG_TOKEN)

MODEL_NAME = "meta-llama/Meta-Llama-3-8B-Instruct"

@bot.message_handler(content_types=['text'])
def handle_message(message):
    try:
        response = client.chat_completion(
            model=MODEL_NAME,
            messages=[
                {"role": "system", "content": "Ты умный AI ассистент. Отвечай четко и только на русском языке."},
                {"role": "user", "content": message.text}
            ],
            max_tokens=512
        )
        bot.reply_to(message, response.choices[0].message.content)
    except Exception as e:
        bot.reply_to(message, f"Ошибка: {str(e)}")

# Функция для запуска поллинга в отдельном потоке
def run_bot():
    while True:
        try:
            # non_stop=True пытается восстанавливать соединение при таймаутах сервера
            bot.polling(non_stop=True, timeout=90, long_polling_timeout=90)
        except Exception:
            import time
            time.sleep(5)

if __name__ == "__main__":
    # Запуск бота в фоне
    bot_thread = threading.Thread(target=run_bot)
    bot_thread.daemon = True
    bot_thread.start()
    
    # Запуск веб-сервера на порту, который требует Hugging Face (7860)
    app.run(host="0.0.0.0", port=7860)