|
| 1 | +from datetime import datetime |
| 2 | + |
| 3 | +import telebot |
| 4 | + |
| 5 | +from ..core.conversations import get_conversing, end_conversation |
| 6 | +from ..core.db_connector import PrettyCursor |
| 7 | +from ..core.invitations import invite_operators, clear_invitation_messages |
| 8 | +from ..core.users import add_user |
| 9 | +from ._bot import bot |
| 10 | +from .utils import nonfalling_handler, AnyContentType |
| 11 | +from .utils.callback_helpers import seconds_since_local_epoch, contract_callback_data_and_jdump |
| 12 | + |
| 13 | + |
| 14 | +@bot.message_handler(commands=['start', 'help']) |
| 15 | +@nonfalling_handler |
| 16 | +def start_help_handler(message: telebot.types.Message): |
| 17 | + bot.reply_to(message, "Привет. /request_conversation, чтобы начать беседу, /end_conversation чтобы завершить") |
| 18 | + add_user(message.chat.id) |
| 19 | + |
| 20 | + |
| 21 | +@bot.message_handler(commands=['request_conversation']) |
| 22 | +@nonfalling_handler |
| 23 | +def request_conversation_handler(message: telebot.types.Message): |
| 24 | + (tg_client_id, _), (tg_operator_id, _) = get_conversing(message.chat.id) |
| 25 | + if tg_operator_id == message.chat.id: |
| 26 | + bot.reply_to(message, "Операторы не могут запрашивать помощь, пока помогают кому-то") |
| 27 | + elif tg_client_id == message.chat.id: |
| 28 | + bot.reply_to(message, "Вы уже в беседе с оператором. Используйте /end_conversation чтобы прекратить") |
| 29 | + else: |
| 30 | + result = invite_operators(message.chat.id) |
| 31 | + if result == 0: |
| 32 | + bot.reply_to(message, "Операторы получили запрос на присоединение. Ждем оператора...\nИспользуйте " |
| 33 | + "/end_conversation, чтобы отменить запрос") |
| 34 | + elif result == 1: |
| 35 | + bot.reply_to(message, "Вы уже ожидаете присоединения оператора. Используйте /end_conversation, чтобы " |
| 36 | + "отказаться от беседы") |
| 37 | + elif result == 2: |
| 38 | + bot.reply_to(message, "Сейчас нет свободных операторов. Пожалуйста, попробуйте позже") |
| 39 | + elif result == 3: |
| 40 | + bot.reply_to(message, "Вы уже в беседе. Используйте /end_conversation, чтобы выйти из нее") |
| 41 | + else: |
| 42 | + raise NotImplementedError("`invite_operators` returned an unexpected value") |
| 43 | + |
| 44 | + |
| 45 | +@bot.message_handler(commands=['end_conversation']) |
| 46 | +@nonfalling_handler |
| 47 | +def end_conversation_handler(message: telebot.types.Message): |
| 48 | + (_, client_local), (operator_tg, operator_local) = get_conversing(message.chat.id) |
| 49 | + |
| 50 | + if operator_tg is None: |
| 51 | + if clear_invitation_messages(message.chat.id): |
| 52 | + bot.reply_to(message, "Ожидание операторов отменено. Используйте /request_conversation, чтобы запросить " |
| 53 | + "помощь снова") |
| 54 | + else: |
| 55 | + bot.reply_to(message, "В данный момент вы ни с кем не беседуете. Используйте /request_conversation, чтобы " |
| 56 | + "начать") |
| 57 | + elif operator_tg == message.chat.id: |
| 58 | + bot.reply_to(message, "Оператор не может прекратить беседу. Обратитесь к @kolayne для реализации такой " |
| 59 | + "возможности") |
| 60 | + else: |
| 61 | + keyboard = telebot.types.InlineKeyboardMarkup() |
| 62 | + d = {'type': 'conversation_rate', 'operator_ids': [operator_tg, operator_local], |
| 63 | + 'conversation_end_moment': seconds_since_local_epoch(datetime.now())} |
| 64 | + |
| 65 | + keyboard.add( |
| 66 | + telebot.types.InlineKeyboardButton("Лучше", |
| 67 | + callback_data=contract_callback_data_and_jdump({**d, 'mood': 'better'})), |
| 68 | + telebot.types.InlineKeyboardButton("Так же", |
| 69 | + callback_data=contract_callback_data_and_jdump({**d, 'mood': 'same'})), |
| 70 | + telebot.types.InlineKeyboardButton("Хуже", |
| 71 | + callback_data=contract_callback_data_and_jdump({**d, 'mood': 'worse'})) |
| 72 | + ) |
| 73 | + keyboard.add(telebot.types.InlineKeyboardButton("Не хочу оценивать", |
| 74 | + callback_data=contract_callback_data_and_jdump(d))) |
| 75 | + |
| 76 | + end_conversation(message.chat.id) |
| 77 | + bot.reply_to(message, "Беседа с оператором прекратилась. Хотите оценить свое самочувствие после нее? " |
| 78 | + "Вы остаетесь анонимным", reply_markup=keyboard) |
| 79 | + bot.send_message(operator_tg, f"Пользователь №{client_local} прекратил беседу") |
| 80 | + |
| 81 | + |
| 82 | +@bot.message_handler(content_types=['text']) |
| 83 | +@nonfalling_handler |
| 84 | +def text_message_handler(message: telebot.types.Message): |
| 85 | + (client_tg, _), (operator_tg, _) = get_conversing(message.chat.id) |
| 86 | + |
| 87 | + if client_tg is None: |
| 88 | + bot.reply_to(message, "Чтобы начать общаться с оператором, нужно написать /request_conversation. Сейчас у вас " |
| 89 | + "нет собеседника") |
| 90 | + return |
| 91 | + |
| 92 | + interlocutor_id = client_tg if message.chat.id != client_tg else operator_tg |
| 93 | + |
| 94 | + reply_to = None |
| 95 | + if message.reply_to_message is not None: |
| 96 | + with PrettyCursor() as cursor: |
| 97 | + cursor.execute("SELECT sender_message_id FROM reflected_messages WHERE sender_chat_id=%s AND " |
| 98 | + "receiver_chat_id=%s AND receiver_message_id=%s", |
| 99 | + (interlocutor_id, message.chat.id, message.reply_to_message.message_id)) |
| 100 | + try: |
| 101 | + reply_to, = cursor.fetchone() |
| 102 | + except TypeError: |
| 103 | + bot.reply_to(message, "Эта беседа уже завершилась. Вы не можете ответить на это сообщение") |
| 104 | + return |
| 105 | + |
| 106 | + for entity in message.entities or []: |
| 107 | + if entity.type in ('mention', 'bot_command'): |
| 108 | + continue |
| 109 | + if entity.type == 'url' and message.text[entity.offset: entity.offset + entity.length] == entity.url: |
| 110 | + continue |
| 111 | + |
| 112 | + bot.reply_to(message, "Это сообщение содержит форматирование, которое сейчас не поддерживается. Оно будет " |
| 113 | + "отправлено с потерей форматирования. Мы работаем над этим") |
| 114 | + break |
| 115 | + |
| 116 | + sent = bot.send_message(interlocutor_id, message.text, reply_to_message_id=reply_to) |
| 117 | + |
| 118 | + with PrettyCursor() as cursor: |
| 119 | + query = "INSERT INTO reflected_messages(sender_chat_id, sender_message_id, receiver_chat_id, " \ |
| 120 | + "receiver_message_id) VALUES (%s, %s, %s, %s)" |
| 121 | + cursor.execute(query, (message.chat.id, message.message_id, sent.chat.id, sent.message_id)) |
| 122 | + cursor.execute(query, (sent.chat.id, sent.message_id, message.chat.id, message.message_id)) |
| 123 | + |
| 124 | + |
| 125 | +@bot.message_handler(content_types=AnyContentType()) |
| 126 | +@nonfalling_handler |
| 127 | +def another_content_type_handler(message: telebot.types.Message): |
| 128 | + bot.reply_to(message, "Сообщения этого типа не поддерживаются. Свяжитесь с @kolayne, чтобы добавить поддержку") |
0 commit comments