|
|
|
|
@ -1,7 +1,8 @@
|
|
|
|
|
# bot_message.py
|
|
|
|
|
import re
|
|
|
|
|
import json
|
|
|
|
|
import qrcode
|
|
|
|
|
from ai_agent.api_common import get_ai_agent, call_ai_agent, get_contact_meta, set_contact_meta, is_valid_name
|
|
|
|
|
from ai_agent.api_common import get_system_prompt, get_ai_agent, call_ai_agent
|
|
|
|
|
from max_bot.max_api import *
|
|
|
|
|
from restoran_max_bot.bot_started import check_registration
|
|
|
|
|
from restoran_max_bot.common import *
|
|
|
|
|
@ -12,25 +13,13 @@ from restoran_max_bot.utils import has_key, is_json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ---------- вспомогательные функции ----------
|
|
|
|
|
def send_booking_to_crm(client: Client, date, time, people, phone, name):
|
|
|
|
|
# реализация бронирования столика
|
|
|
|
|
msg = f'Бронирование столика:\nНа дату: {date}-{time} \nКоличество: {people}\nКонтакт: {phone}\nИмя: {name}'
|
|
|
|
|
send_message_all_manager(client, msg)
|
|
|
|
|
def send_booking_to_crm(chat_id, date, time, people, phone):
|
|
|
|
|
# TODO: реализовать отправку в CRM
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def send_contact_to_admin(client: Client, phone, contact_method, question, preferred_time, name):
|
|
|
|
|
# реализовать отправку администратору
|
|
|
|
|
msg = (f'Гость попросил связаться:\n {contact_method}\nВопрос: {question}\n'
|
|
|
|
|
f'Удобное время: {preferred_time}\nКонтакт: {phone}\nИмя: {name}')
|
|
|
|
|
send_message_all_manager(client, msg)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def send_feedback_to_crm(client: Client, rating, feedback_text, name, phone):
|
|
|
|
|
# реализовать отправку отзыва в CRM
|
|
|
|
|
msg = f'Отзыв от {name} (тел. {phone}):\nОценка: {rating}/5\nТекст: {feedback_text}'
|
|
|
|
|
send_message_all_manager(client, msg)
|
|
|
|
|
def send_contact_to_admin(chat_id, phone, contact_method, question, preferred_time, contact):
|
|
|
|
|
# TODO: реализовать отправку администратору
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -104,41 +93,6 @@ def bot_message(client: Client, message: dict, settings_max: dict, message_type)
|
|
|
|
|
if not contact:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
# ---------- проверка и запрос имени ----------
|
|
|
|
|
meta = get_contact_meta(contact)
|
|
|
|
|
real_name = meta.get('real_name')
|
|
|
|
|
name_asked = meta.get('name_asked', False)
|
|
|
|
|
|
|
|
|
|
# Если имя ещё не запрашивали и нет реального имени
|
|
|
|
|
if not real_name and not name_asked:
|
|
|
|
|
# Проверяем имя, которое пришло из мессенджера (contact.name)
|
|
|
|
|
if is_valid_name(contact.name):
|
|
|
|
|
# Если валидное, сохраняем как реальное
|
|
|
|
|
set_contact_meta(contact, 'real_name', contact.name.strip())
|
|
|
|
|
real_name = contact.name.strip()
|
|
|
|
|
else:
|
|
|
|
|
# Если невалидное — запрашиваем
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'],
|
|
|
|
|
"Как мне к вам обращаться? Напишите ваше имя, чтобы я мог обращаться к вам лично.")
|
|
|
|
|
set_contact_meta(contact, 'name_asked', True)
|
|
|
|
|
# Завершаем обработку, ждём ответ
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
# Если имя уже запрашивали, но пользователь не ответил, а сейчас прислал сообщение
|
|
|
|
|
if name_asked and not real_name:
|
|
|
|
|
potential_name = message['message']['body']['text'].strip()
|
|
|
|
|
if is_valid_name(potential_name):
|
|
|
|
|
set_contact_meta(contact, 'real_name', potential_name)
|
|
|
|
|
real_name = potential_name
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'],
|
|
|
|
|
f"Приятно познакомиться, {potential_name}! Чем могу помочь?")
|
|
|
|
|
# После приветствия продолжаем обработку (не завершаем)
|
|
|
|
|
else:
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'],
|
|
|
|
|
"Пожалуйста, напишите ваше настоящее имя (от 2 символов).")
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
# ---------- обработка стандартных команд (меню, бонусы и т.п.) ----------
|
|
|
|
|
data = None
|
|
|
|
|
if message_type == 'message_created':
|
|
|
|
|
data = common_get_data(client=client, key=str(message['message']['body']['text']).lower())
|
|
|
|
|
@ -146,6 +100,7 @@ def bot_message(client: Client, message: dict, settings_max: dict, message_type)
|
|
|
|
|
payload = json.loads(message['callback']['payload'])
|
|
|
|
|
data = common_get_data(client=client, key=str(payload['data']).lower())
|
|
|
|
|
|
|
|
|
|
# ---------- обработка стандартных команд (меню, бонусы и т.п.) ----------
|
|
|
|
|
if data:
|
|
|
|
|
for dt in data:
|
|
|
|
|
if dt.title == '##bonus##':
|
|
|
|
|
@ -197,12 +152,11 @@ def bot_message(client: Client, message: dict, settings_max: dict, message_type)
|
|
|
|
|
message='👇 Выберите раздел', client=client)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
# Вызываем AI-агента через универсальную функцию, передавая реальное имя
|
|
|
|
|
# Вызываем AI-агента через универсальную функцию
|
|
|
|
|
response = call_ai_agent(
|
|
|
|
|
client=client,
|
|
|
|
|
session_id=str(chat_id),
|
|
|
|
|
user_query=message['message']['body']['text'],
|
|
|
|
|
contact_name=real_name # передаём имя для персонализации
|
|
|
|
|
user_query=message['message']['body']['text']
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# ---------- обработка ответа AI ----------
|
|
|
|
|
@ -223,10 +177,9 @@ def bot_message(client: Client, message: dict, settings_max: dict, message_type)
|
|
|
|
|
people = entities.get('people')
|
|
|
|
|
phone = entities.get('phone')
|
|
|
|
|
if date and time and people:
|
|
|
|
|
success = send_booking_to_crm(client, date, time, people, phone, real_name)
|
|
|
|
|
success = send_booking_to_crm(chat_id, date, time, people, phone)
|
|
|
|
|
if success:
|
|
|
|
|
confirm_msg = (f"✅ Бронирование на {date} в {time} на {people} чел. принято! "
|
|
|
|
|
f"Администратор свяжется с вами.")
|
|
|
|
|
confirm_msg = f"✅ Бронирование на {date} в {time} на {people} чел. принято! Администратор свяжется с вами."
|
|
|
|
|
else:
|
|
|
|
|
confirm_msg = "❌ Не удалось забронировать. Попробуйте позже."
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'], confirm_msg)
|
|
|
|
|
@ -244,7 +197,7 @@ def bot_message(client: Client, message: dict, settings_max: dict, message_type)
|
|
|
|
|
question = entities.get('question', '')
|
|
|
|
|
preferred_time = entities.get('preferred_time', '')
|
|
|
|
|
if phone and contact_method:
|
|
|
|
|
success = send_contact_to_admin(client, phone, contact_method, question, preferred_time, real_name)
|
|
|
|
|
success = send_contact_to_admin(chat_id, phone, contact_method, question, preferred_time, contact)
|
|
|
|
|
if success:
|
|
|
|
|
confirm_msg = f"✅ Ваш запрос передан администратору. Способ связи: {contact_method}. Скоро с вами свяжутся."
|
|
|
|
|
else:
|
|
|
|
|
@ -256,24 +209,6 @@ def bot_message(client: Client, message: dict, settings_max: dict, message_type)
|
|
|
|
|
else:
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'], message_text)
|
|
|
|
|
|
|
|
|
|
elif intent == 'feedback':
|
|
|
|
|
if status == 'need_more_info':
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'], message_text)
|
|
|
|
|
elif status == 'complete':
|
|
|
|
|
rating = entities.get('rating')
|
|
|
|
|
feedback_text = entities.get('feedback_text', '')
|
|
|
|
|
if rating and feedback_text:
|
|
|
|
|
success = send_feedback_to_crm(client, rating, feedback_text, real_name, contact.phone)
|
|
|
|
|
if success:
|
|
|
|
|
confirm_msg = "✅ Спасибо за ваш отзыв! Мы учтём его."
|
|
|
|
|
else:
|
|
|
|
|
confirm_msg = "❌ Не удалось отправить отзыв. Попробуйте позже."
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'], confirm_msg)
|
|
|
|
|
else:
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'], "⚠️ Не хватает данных для отзыва.")
|
|
|
|
|
else:
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'], message_text)
|
|
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
maxbot_send_text_message(chat_id, settings_max['token'], message_text)
|
|
|
|
|
|
|
|
|
|
|