@xx_RuBiCoN_xx

Почему не исполняется if elif elif?

Пишу по немногу чат поддержки в боте. В настоящий момент вот такой код:
operators_id = [мой айдишник]
operator_mode = {}
user_mode = {}


def supportConnect(bot, message):
   remove_keyboard = types.ReplyKeyboardRemove()
   keyboard = types.InlineKeyboardMarkup()
   keyboard.add(cancel_btn)
   bot.send_message(message.chat.id, text=text48, reply_markup=remove_keyboard)
   bot.send_message(message.chat.id, text=text49, reply_markup=keyboard)
   bot.register_next_step_handler(message, lambda msg: supportWait(bot, msg))

def supportWait(bot, message):
   for operator_id in operators_id:
      keyboard = types.InlineKeyboardMarkup()
      keyboard.add(join_dialog_btn)
      bot.send_message(operator_id, f"Поступило новое обращение в службу поддержки.\n\nUser ID: {message.from_user.id}\nUsername: @{message.from_user.username}\n\nВопрос клиента:\n*{message.text}*", parse_mode="Markdown", reply_markup=keyboard)
   bot.send_message(message.chat.id, text=text50)

   @bot.callback_query_handler(func=lambda call: call.data == 'join_dialog_btn')
   def join_dialog(call):
      print('def join_dialog(call)')
      # Получаем идентификатор оператора и пользователя
      operator_id = call.from_user.id
      print('operator_id = call.from_user.id')
      user_id = call.message.chat.id
      print('user_id = call.message.chat.id')
      
      # Проверяем, наличие и состояние оператора
      if operator_id in operator_mode and operator_mode[operator_id] == 'not_in_dialog':
         print('if')
         # Отправляем сообщение оператору о подключении к диалогу
         bot.send_message(call.message.chat.id, text53)
         # Устанавливаем состояние оператора как "в диалоге"
         operator_mode[call.from_user.id] = 'in_dialog'
         # Добавляем пользователя в user_mode
         user_mode[user_id] = 'in_dialog'

      elif operator_id in operator_mode and operator_mode[operator_id] == 'in_dialog':
         print('elif')
         # Отправляем сообщение оператору о том, что он уже в диалоге
         bot.send_message(call.message.chat.id, text54)
      
      elif user_id in user_mode and user_mode[user_id] == 'in_dialog':
         print('elif2')
         # Отправляем сообщение оператору о том, что кто-то уже подключился
         bot.send_message(call.message.chat.id, text55)


При исполнении кода выводятся такие принты:

print('def join_dialog(call)')
print('operator_id = call.from_user.id')
print('user_id = call.message.chat.id')


На этом моменте код останавливается, хотя в моём понимании он должен был продолжить читать if elif elif. Почему так?
  • Вопрос задан
  • 35 просмотров
Решения вопроса 1
RimMirK
@RimMirK
Вроде человек. Вроде учусь. Вроде пайтону
почитай про приоритеты ==, in, and
тебе надо другие группировки
if (operator_id in operator_mode) and (operator_mode[operator_id] == 'not_in_dialog'): ...
и вообще не советую так делать. Если у тебя в условиях повторяется operator_id in operator_mode то почему его не вынести? А operator_mode[operator_id] == _ можно заменить конструкцей match-case. Конструкция досутпна с питона 3.10.

if operator in operator_mode:
    match operator_mode[operator_id]:
        case 'not_in_dialog':
             pass
         case'in_dialog':
             pass

# а тут если такое условие одно, можно так оставить. Но если их будет больше, как выше, то лучше сделать так как выше
elif (user_id in user_mode) and (user_mode[user_id] == 'in_dialog'):
         pass
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы