v1.8.1: fix consent flow — split-based word matching, refuse words before quick_intent, operator handler, plain text phones, clarify_intent post-processing
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import datetime
|
||||
import re
|
||||
import logging
|
||||
from sqlalchemy import select
|
||||
from app.database import async_session
|
||||
@@ -10,6 +11,16 @@ from app.keyboards import contact_keyboard, consent_keyboard, return_to_consent_
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _matches_any(text: str, words: list) -> bool:
|
||||
text_words = set(text.split())
|
||||
for w in words:
|
||||
if w in text_words:
|
||||
return True
|
||||
if len(w) > 3 and w in text:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def handle_consent_callback(user_id: int, conv_id: int, callback_id: str) -> None:
|
||||
if callback_id == "consent_yes":
|
||||
await handle_consent_yes(user_id, conv_id)
|
||||
@@ -22,9 +33,9 @@ async def handle_consent_response(user_id: int, conv_id: int, text: str) -> None
|
||||
consent_words = ["да", "даю", "согласен", "согласна", "yes", "ok", "хорошо", "даю согласие"]
|
||||
refuse_words = ["нет", "не даю", "отказ", "no", "не согласен", "не согласна"]
|
||||
|
||||
if any(w in text_lower for w in consent_words):
|
||||
if _matches_any(text_lower, consent_words):
|
||||
await handle_consent_yes(user_id, conv_id)
|
||||
elif any(w in text_lower for w in refuse_words):
|
||||
elif _matches_any(text_lower, refuse_words):
|
||||
await handle_consent_no(user_id, conv_id)
|
||||
else:
|
||||
await max_api.send_message(
|
||||
@@ -77,17 +88,14 @@ async def handle_consent_no(user_id: int, conv_id: int) -> None:
|
||||
phones = config_reader.get_phones()
|
||||
email = config_reader.get_site_mail()
|
||||
|
||||
phone_text = "\n".join(
|
||||
f"📞 {phone} — [позвонить](tel:{link})"
|
||||
for phone, link in phones
|
||||
)
|
||||
phone_text = "\n".join(f"📞 {phone}" for phone, _ in phones)
|
||||
|
||||
try:
|
||||
await max_api.send_message(
|
||||
user_id,
|
||||
f"Без вашего согласия мы не можем обработать обращение.\n\n"
|
||||
f"Вы можете позвонить нам:\n{phone_text}\n\n"
|
||||
f"📧 [Написать на почту](mailto:{email})\n\n"
|
||||
f"📧 {email}\n\n"
|
||||
f"Если передумаете и захотите дать согласие — просто напишите об этом.",
|
||||
)
|
||||
except Exception as e:
|
||||
@@ -97,14 +105,35 @@ async def handle_consent_no(user_id: int, conv_id: int) -> None:
|
||||
async def handle_refused_again(user_id: int, conv_id: int, text: str) -> None:
|
||||
text_lower = text.strip().lower()
|
||||
consent_words = ["да", "даю", "согласен", "согласна", "yes", "ok", "хорошо", "даю согласие", "передумал", "согласен дать"]
|
||||
refuse_words = ["нет", "не даю", "не хочу", "отказ", "отмена", "no", "cancel", "я отказался"]
|
||||
|
||||
if any(w in text_lower for w in consent_words):
|
||||
if _matches_any(text_lower, consent_words):
|
||||
await handle_consent_yes(user_id, conv_id)
|
||||
elif _matches_any(text_lower, refuse_words):
|
||||
phones = config_reader.get_phones()
|
||||
email = config_reader.get_site_mail()
|
||||
phone_text = "\n".join(f"📞 {phone}" for phone, _ in phones)
|
||||
try:
|
||||
await max_api.send_message(
|
||||
user_id,
|
||||
f"Хорошо, без согласия мы не можем обработать обращение.\n\n"
|
||||
f"Вы можете позвонить нам:\n{phone_text}\n\n"
|
||||
f"📧 {email}\n\n"
|
||||
f"Если передумаете — напишите «Даю согласие».",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send refused_again message: {e}")
|
||||
else:
|
||||
async with async_session() as db:
|
||||
conv = await db.get(BotConversation, conv_id)
|
||||
if conv:
|
||||
conv.state = "completed"
|
||||
await db.commit()
|
||||
from app.handlers.greeting import analyze_and_respond
|
||||
await analyze_and_respond(user_id, conv_id, text)
|
||||
phones = config_reader.get_phones()
|
||||
email = config_reader.get_site_mail()
|
||||
phone_text = "\n".join(f"📞 {phone}" for phone, _ in phones)
|
||||
try:
|
||||
await max_api.send_message(
|
||||
user_id,
|
||||
f"Хорошо, без согласия мы не можем обработать обращение.\n\n"
|
||||
f"Вы можете позвонить нам:\n{phone_text}\n\n"
|
||||
f"📧 {email}\n\n"
|
||||
f"Если передумаете — напишите «Даю согласие».",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send refused_again message: {e}")
|
||||
|
||||
@@ -38,6 +38,18 @@ async def handle_contact_received(user_id: int, conv_id: int, contact_text: str)
|
||||
|
||||
async def handle_manual_contact(user_id: int, conv_id: int, text: str) -> None:
|
||||
text = text.strip()
|
||||
text_lower = text.lower()
|
||||
|
||||
refuse_words = ["нет", "не хочу", "отмена", "отказ", "no", "cancel"]
|
||||
if any(w in text_lower for w in refuse_words):
|
||||
async with async_session() as db:
|
||||
conv = await db.get(BotConversation, conv_id)
|
||||
if conv:
|
||||
conv.state = "consent_refused"
|
||||
await db.commit()
|
||||
from app.handlers.consent import handle_refused_again
|
||||
await handle_refused_again(user_id, conv_id, text)
|
||||
return
|
||||
|
||||
if PHONE_PATTERN.match(text) or EMAIL_PATTERN.match(text):
|
||||
await handle_contact_received(user_id, conv_id, text)
|
||||
@@ -45,7 +57,7 @@ async def handle_manual_contact(user_id: int, conv_id: int, text: str) -> None:
|
||||
await max_api.send_message(
|
||||
user_id,
|
||||
"Пожалуйста, введите корректный номер телефона (например, +7 (861) 203-33-30) "
|
||||
"или адрес электронной почты.",
|
||||
"или адрес электронной почты. Или напишите «Отмена» чтобы вернуться назад.",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -119,9 +119,45 @@ async def handle_message(user_id: int, text: str) -> None:
|
||||
state = conv.state
|
||||
logger.info(f"handle_message: user={user_id} state={state} conv_id={conv.id}")
|
||||
|
||||
text_lower = text.strip().lower()
|
||||
refuse_words = ["нет", "не даю", "не хочу", "отказ", "отмена", "no", "cancel", "я отказался"]
|
||||
operator_words = ["оператор", "живой человек", "связать с оператором", "переключить на оператора"]
|
||||
|
||||
if any(w in text_lower for w in operator_words):
|
||||
from app.config_reader import config_reader
|
||||
phones = config_reader.get_phones()
|
||||
email = config_reader.get_site_mail()
|
||||
phone_text = "\n".join(f"📞 {phone}" for phone, _ in phones)
|
||||
await max_api.send_message(
|
||||
user_id,
|
||||
"К сожалению, я не могу переключить вас на оператора.\n\n"
|
||||
"Но вы можете связаться с нами напрямую:\n"
|
||||
f"{phone_text}\n"
|
||||
f"📧 {email}\n\n"
|
||||
"Мы обязательно ответим и поможем!",
|
||||
)
|
||||
return
|
||||
|
||||
if state in ("greeting", "analyzing", "awaiting_input"):
|
||||
await analyze_and_respond(user_id, conv.id, text)
|
||||
elif state in ("awaiting_consent", "consent_refused", "awaiting_contact"):
|
||||
if any(w in text_lower for w in refuse_words):
|
||||
if state == "awaiting_consent":
|
||||
from app.handlers.consent import handle_consent_no
|
||||
await handle_consent_no(user_id, conv.id)
|
||||
elif state == "consent_refused":
|
||||
from app.handlers.consent import handle_refused_again
|
||||
await handle_refused_again(user_id, conv.id, text)
|
||||
elif state == "awaiting_contact":
|
||||
async with async_session() as db:
|
||||
conv_upd = await db.get(BotConversation, conv.id)
|
||||
if conv_upd:
|
||||
conv_upd.state = "consent_refused"
|
||||
await db.commit()
|
||||
from app.handlers.consent import handle_refused_again
|
||||
await handle_refused_again(user_id, conv.id, text)
|
||||
return
|
||||
|
||||
quick_intent = await yandex_gpt.analyze_intent(text)
|
||||
if quick_intent == "question":
|
||||
await analyze_and_respond(user_id, conv.id, text)
|
||||
@@ -272,19 +308,15 @@ async def _send_contacts(user_id: int) -> None:
|
||||
phones = config_reader.get_phones()
|
||||
email = config_reader.get_site_mail()
|
||||
|
||||
phone_text = "\n".join(
|
||||
f"📞 {phone} — [позвонить](tel:{link})"
|
||||
for phone, link in phones
|
||||
)
|
||||
phone_text = "\n".join(f"📞 {phone}" for phone, _ in phones)
|
||||
|
||||
message = (
|
||||
"Вы можете связаться с нами:\n\n"
|
||||
f"{phone_text}\n"
|
||||
f"📧 [Написать на почту](mailto:{email})\n\n"
|
||||
f"Или написать на почту: {email}"
|
||||
f"📧 {email}"
|
||||
)
|
||||
|
||||
await max_api.send_message(user_id, message, format="markdown")
|
||||
await max_api.send_message(user_id, message)
|
||||
|
||||
|
||||
async def _get_knowledge_base_context(query: str) -> str:
|
||||
|
||||
Reference in New Issue
Block a user