import telebot
import requests
import json
import os
# --- КОНФИГ ---
BOT_TOKEN = 'ВСТАВЬ_СЮДА_ТОКЕН'
ADMIN_ID = 'ВСТАВЬ_СЮДА_СВОЙ_ID' # Твой ID из @userinfobot
MODEL_NAME = 'gemma4:e4b'
HISTORY_FILE = 'history.json'
bot = telebot.TeleBot(BOT_TOKEN)
SYSTEM_PROMPT = (
"Ты — мой многогранный ИИ-ассистент (Режиссер/Медик/Психолог). "
"Будь краток, структурен, дисциплинирован и эмпатичен."
)
# --- ПАМЯТЬ ---
def load_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
def save_history(data):
with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
chat_histories = load_history()
# --- КОМАНДА ДЛЯ АДМИНА ---
@bot.message_handler(commands=['logs'])
def show_logs(message):
if str(message.chat.id) == ADMIN_ID:
# Выводит историю в консоль (черное окно)
print(json.dumps(chat_histories, indent=2, ensure_ascii=False))
bot.reply_to(message, "Логи сброшены в консоль.")
else:
bot.reply_to(message, "Доступ запрещен.")
# --- ОСНОВНОЙ ОБРАБОТЧИК ---
@bot.message_handler(func=lambda message: True)
def handle_message(message):
chat_id = str(message.chat.id)
bot.send_chat_action(message.chat.id, 'typing')
if chat_id not in chat_histories:
chat_histories[chat_id] = [{"role": "system", "content": SYSTEM_PROMPT}]
chat_histories[chat_id].append({"role": "user", "content": message.text})
# Ограничение памяти (система + 11 реплик)
if len(chat_histories[chat_id]) > 12:
chat_histories[chat_id] = [chat_histories[chat_id][0]] + chat_histories[chat_id][-11:]
payload = {
"model": MODEL_NAME,
"messages": chat_histories[chat_id],
"stream": False
}
try:
response = requests.post("http://localhost:11434/api/chat", json=payload)
if response.status_code == 200:
ai_response = response.json()['message']['content']
chat_histories[chat_id].append({"role": "assistant", "content": ai_response})
save_history(chat_histories)
bot.reply_to(message, ai_response)
except Exception as e:
bot.reply_to(message, f"Ошибка: {e}")
print("Бот запущен. Ожидание сообщений...")
bot.infinity_polling()