示例#1
0
def callback_return_current_communic(call):

    if call.message:
        pre = util.get_prefix_for_servicebutton_reply(call.data)
        u_chat_id = db.get_user_chat_id_by_responsible(call.from_user.id)
        if u_chat_id:
            u = db.get_user_namedtuple(u_chat_id)
            ui = util.print_userinfo(u_chat_id)
            db.append_message_to_history(
                u_chat_id, '[ServiceBot]: Специалист ' +
                util.get_support_name_by_chat_id(call.from_user.id) +
                ' перевел коммуникацию в незакрепленное состояние.')
            db.set_user(u_chat_id,
                        current_communic_is_appointed=0,
                        current_communic_responsible=0,
                        last_msg_time_from_user=int(time()))
            message_to_specialist = 'Вы перевели коммуникацию с пользователем\n\n' + ui + '\nв незакрепленное состояние.'
            message_to_group = '[ServiceBot] Специалист ' + util.get_support_name_by_chat_id(call.from_user.id) +\
                               ' перевел активную коммуникацию с пользователем\n\n' + ui + '\nв незакрепленное состояние.\n\nВы можете перевести на себя коммуникацию, нажав кнопку, следующую за данным сообщением.'
            bot.send_message(call.from_user.id, pre + message_to_specialist)
            button = [[
                'Перевести на себя коммуникацию с ' + u.first_name + ' ' +
                u.last_name, 'take_open_communic' + u.chat_id
            ]]
            keyboard = util.get_keyboard(button)
            for gr in SUPPORTGROUPS:
                bot.send_message(gr, message_to_group, reply_markup=keyboard)
        elif u_chat_id == None:
            bot.answer_callback_query(call.id,
                                      pre +
                                      config.REPLY['no_active_communics'],
                                      show_alert=True)
示例#2
0
def message_from_support(message):

    user_id = db.get_user_chat_id_by_responsible(message.chat.id)
    if user_id != None and message.text != '/service':
        if message.text:
            db.append_message_to_history(
                user_id,
                '[' + util.get_support_name_by_chat_id(message.chat.id) +
                ']: ' + message.text)
        elif message.photo or message.document:
            util.process_content(message)
        db.set_user(user_id, last_msg_time_from_specialist=int(time()))
        if message.text:
            bot.send_message(user_id, message.text)
        elif message.photo:
            mark = util.get_support_name_by_chat_id(
                message.chat.id) + ' отправил Вам фото:'
            if message.caption:
                mark = mark[:-1] + '. Подпись к фото: ' + message.caption
            bot.send_message(user_id, mark)
            bot.send_photo(user_id, util.get_file_photo_id(message))
        elif message.document:
            mark = util.get_support_name_by_chat_id(
                message.chat.id) + ' отправил Вам файл:'
            if message.caption:
                mark = mark[:-1] + '. Подпись к файлу: ' + message.caption
            bot.send_message(user_id, mark)
            bot.send_document(user_id, message.document.file_id)
    elif user_id != None:
        bot.reply_to(message, config.REPLY['incorrect_request'])
    elif user_id == None:
        bot.reply_to(message, config.REPLY['no_active_communics'])
示例#3
0
def message_second_message_of_new_communic_before_communic_appointment(
        message):

    if message.text:
        db.append_message_to_history(message.chat.id, message.text)
    elif message.photo or message.document:
        util.process_content(message)
示例#4
0
def message_first_message_of_new_communic(message):

    if message.text:
        db.append_message_to_history(message.chat.id, message.text)
    elif message.photo or message.document:
        util.process_content(message)
    db.set_user(message.chat.id,
                has_active_communics=1,
                last_msg_time_from_user=int(time()))
    template = config.REPLY['new_communication'].format(
        util.print_userinfo(message.chat.id, with_log=False))
    user = db.get_user_namedtuple(message.chat.id)
    button2 = [[
        'Перевести на себя коммуникацию с ' + user.first_name + ' ' +
        user.last_name, 'take_open_communic' + user.chat_id
    ]]
    keyboard = util.get_keyboard(button2)
    for gr in SUPPORTGROUPS:
        if message.text:
            util.send_history(gr, template, reply_markup=keyboard)
        elif message.photo:
            util.send_history(gr, template, reply_markup=keyboard)
            bot.send_message(gr,
                             '[ServiceBot]: Отправленное пользователем фото:')
            bot.send_photo(gr, util.get_file_photo_id(message))
        elif message.document:
            util.send_history(gr, template, reply_markup=keyboard)
            bot.send_message(gr,
                             '[ServiceBot]: Отправленный пользователем файл:')
            bot.send_document(gr, message.document.file_id)
示例#5
0
def process_content(message):

    dir_log = config.archive + str(message.chat.id)
    if (isdir(dir_log) == False):
        mkdir(dir_log)
    if message.photo:
        content = get_file_photo_id(message)
        filename_suff = content[-10:] + '.jpg'
        a = 'фото'
        b = '. Подпись к фото: ' + message.caption if message.caption else ''
    elif message.document:
        content = message.document.file_id
        filename_suff = message.document.file_name
        a = 'файл ' + message.document.file_name
        b = '. Подпись к файлу: ' + message.caption if message.caption else ''
    if message.chat.id in SUPPORTS:
        h = db.get_user_chat_id_by_responsible(message.chat.id)
        c = 'Специалист'
    else:
        h = message.chat.id
        c = 'Пользователь'
    filename = dir_log + '/' + strftime('%Y%m%d_%H%M%S',
                                        localtime()) + '__' + filename_suff
    db.append_message_to_history(
        h, config.REPLY['sent_content'].format(c, a, b, filename))
    download_content(content, filename)
示例#6
0
def callback_change_email_address(call):

    if call.message:
        if db.get_user(call.from_user.id, 'auth_code_is_sent',
                       'is_authenticated') == (1, 0):
            db.append_message_to_history(
                call.from_user.id,
                '[ServiceBot]: Пользователь запросил смену адреса электронной почты'
            )
            db.set_user(call.from_user.id, auth_code_is_sent=0)
            bot.send_message(call.from_user.id,
                             'Введите адрес электронной почты')
        else:
            bot.send_message(
                call.from_user.id,
                'Cмена адреса электронной почты поддерживается при прохождении процедуры аутентификации'
            )
示例#7
0
def message_with_email_address(message):

    db.append_message_to_history(message.chat.id, message.text)
    pattern = r'^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$'
    reg = re.compile(pattern)
    if reg.match(message.text):
        reply = (
            'На указанный Вами адрес электронной почты направлено сообщение, содержащее код аутентификации. '
            'Если Вы ввели некорректный адрес электронной почты, введите \'/\', в появившемся всплывающем меню выберите "/service Сервисное меню" и нажмите кнопку "Сменить адрес электронной почты".'
        )
        bot.reply_to(message, reply)
        util.send_authcode(message.text,
                           db.get_user(message.chat.id, 'auth_code')[0])
        db.set_user(message.chat.id, auth_code_is_sent=1)
        email = '\'' + message.text + '\''
        db.set_user(message.chat.id, email_address=email)
    else:
        bot.reply_to(
            message,
            'Это не похоже на адрес электронной почты. Введите Ваш рабочий адрес электронной почты для отправки Вам кода аутентификации'
        )
示例#8
0
def first_message(message):

    user = db.get_user_namedtuple(message.chat.id)
    if not user:
        regcode = randint(1111, 9999)
        new_user = (['first_name', message.chat.first_name], [
            'last_name', message.chat.last_name
        ], ['chat_id', message.chat.id
            ], ['auth_code',
                regcode], ['email_address', 'email_address_is_not_defined'], [
                    'message_log',
                    '[ServiceBot] Получено сообщение от нового пользователя'
                ])
        db.create_user(new_user)
        reply = (
            'Судя по всему, Вы обращаетесь к Сервисному боту впервые.\n'
            'Давайте познакомимся. Пожалуйста, укажите ваш рабочий адрес электронной почты, чтобы я Вас узнал:'
        )
        bot.reply_to(message, reply)
        db.set_user(message.chat.id, email_is_requested=1)
    db.append_message_to_history(message.chat.id, message.text)
示例#9
0
def message_with_auth_code(message):

    user = db.get_user_namedtuple(message.chat.id)
    db.append_message_to_history(message.chat.id, message.text)
    try:
        if int(message.text) == user.auth_code:
            db.set_user(message.chat.id,
                        is_authenticated=1,
                        last_msg_time_from_user=int(time()))
            reply = (
                'Отлично! Теперь я знаю, кто Вы, и запомню это на будущее. В любое время Вы можете написать сообщение мне с Вашим вопросом, '
                'и я постараюсь соединить Вас со специалистом, который Вам поможет.\n\nПожалуйста, напишите Ваш вопрос к технической поддержке:'
            )
            bot.reply_to(message, reply)
            template = config.REPLY['new_user_authenticated'].format(
                util.print_userinfo(message.chat.id, with_log=False))
            for gr in SUPPORTGROUPS:
                bot.send_message(gr, template)
        else:
            bot.reply_to(message, 'Код аутентификации указан неверно')
    except ValueError:
        bot.reply_to(message, 'Код аутентификации указан неверно')
示例#10
0
def archive_communic_from_chat_id(chat_id, timeout=False):

    if chat_id != None:
        u = db.get_user_namedtuple(chat_id)
        if timeout:
            db.append_message_to_history(
                chat_id,
                '[ServiceBot]: Коммуникация была автоматически закрыта по таймауту'
            )
        else:
            db.append_message_to_history(
                chat_id, '[ServiceBot]: ' +
                get_support_name_by_chat_id(u.current_communic_responsible) +
                ' закрыл коммуникацию')
        dir_log = config.archive + str(chat_id)
        file_log = config.archive + str(chat_id) + '/' + str(chat_id) + r'.txt'
        if (isdir(dir_log) == False):
            mkdir(dir_log)
        if (isfile(file_log) == False):
            f = open(file_log, 'w+')
            f.write(50 * '#' + '\n\n' + 'Архив сообщений по пользователю' +
                    '\n\n' + print_userinfo(chat_id) + '\n' + 50 * '#' +
                    '\n\n')
            f.close()
        f = open(file_log, 'a')
        f.write(60 * '_' + '\n\n' + 'Запись от ' +
                strftime('%d.%m.%Y %H:%M:%S', localtime()) +
                ' (локальное время сервера)' + '\n' + 60 * '_')

        # workaround for emoji logging
        res = ''
        for s in db.get_message_log_by_id(u.id):
            if (ord(s) > 0xfff):
                k = '[U+{:X}]'.format(ord(s))
                res += k
            else:
                res += s
        f.write('\n\n' + str(res) + '\n' + 60 * '_' + '\n\n')
        f.close()
示例#11
0
def message_after_appointment(message):
    if message.text:
        db.append_message_to_history(message.chat.id, message.text)
    elif message.photo or message.document:
        util.process_content(message)
    db.set_user(message.chat.id, last_msg_time_from_user=int(time()))
    user = db.get_user_namedtuple(message.chat.id)
    if message.text:
        bot.send_message(user.current_communic_responsible,
                         '[' + user.email_address + '] ' + message.text)
    elif message.photo:
        mark = '[' + user.email_address + '] Фото:'
        if message.caption:
            mark = mark[:-1] + '. Подпись к фото: ' + message.caption
        bot.send_message(user.current_communic_responsible, mark)
        bot.send_photo(user.current_communic_responsible,
                       util.get_file_photo_id(message))
    elif message.document:
        mark = '[' + user.email_address + '] Файл:'
        if message.caption:
            mark = mark[:-1] + '. Подпись к файлу: ' + message.caption
        bot.send_message(user.current_communic_responsible, mark)
        bot.send_document(user.current_communic_responsible,
                          message.document.file_id)
示例#12
0
def take_open_communic_by_button(support_chat_id, user_chat_id):

    user = db.get_user_namedtuple(user_chat_id)
    specialist_has_communics = (
        False if db.get_user_chat_id_by_responsible(support_chat_id) == None
        else True)
    if not specialist_has_communics and user.current_communic_is_appointed == 0 and user.has_active_communics == 1:
        db.append_message_to_history(
            user_chat_id,
            '[ServiceBot]: ' + get_support_name_by_chat_id(support_chat_id) +
            ' перевел на себя коммуникацию')
        db.set_user(user_chat_id, last_msg_time_from_specialist=int(time()))
        reply_to_group = ('{0} взял коммуникацию с пользователем: \n\n' +
                          print_userinfo(user_chat_id, with_log=False))
        reply_to_specialist = (
            '{0}, Вы перевели на себя коммуникацию с пользователем: \n\n' +
            print_userinfo(user_chat_id, with_log=True) +
            '\nСообщения, которые Вы получаете от бота в личном чате, '
            'перенаправляются Вам в том виде, в каком пользователь направляет их боту.\n\nСообщения, отправляемые Вами боту '
            'в личном чате, перенаправляются пользователю.\n\nВсе сообщения попадают в историю коммуникации и после закрытия коммуникации архивируются.\n\nВам следует убедиться, что по данной коммуникации '
            'еще не зарегистрирована заявка в сервисдеске, и зарегистрировать ее самостоятельно.\n\nДля открытия сервисного меню нажмите кнопку "/" и выберите позицию "/service" во всплывающем меню.\n\n'
            'Для закрытия коммуникации нажмите кнопку "Закрыть текущую коммуникацию" в сервисном меню.'
        )
        reply_to_user = (
            'Ваша коммуникация была переведена на специалиста. Имя специалиста: '
            + get_support_name_by_chat_id(support_chat_id) + '.\n'
            'Сообщения, отправляемые Вами боту, перенаправляются специалисту.')
        for gr in SUPPORTGROUPS:
            bot.send_message(
                gr,
                reply_to_group.format(
                    get_support_name_by_chat_id(support_chat_id)))
        db.set_user(user_chat_id, current_communic_is_appointed=1)
        send_history(
            support_chat_id,
            reply_to_specialist.format(
                get_support_name_by_chat_id(support_chat_id)))
        db.set_user(user_chat_id, current_communic_responsible=support_chat_id)
        bot.send_message(user_chat_id, reply_to_user)
    elif not specialist_has_communics and user.current_communic_is_appointed == 0 and user.has_active_communics == 0:
        reply_to_specialist_1 = (
            '{0}, Вы хотели перевести на себя коммуникацию с пользователем {1}. Эта коммуникация уже закрыта. Пользователь не имеет активных коммуникаций.'
        )
        bot.send_message(
            support_chat_id,
            reply_to_specialist_1.format(
                get_support_name_by_chat_id(support_chat_id),
                user.first_name + user.last_name))
    elif user.current_communic_is_appointed == 1 and user.has_active_communics == 1 and support_chat_id == user.current_communic_responsible:
        reply_to_specialist_2 = (
            '{0}, Вы хотели перевести на себя коммуникацию с пользователем {1}. Эта коммуникация уже закреплена за Вами. Вы можете общаться с пользователем через личный чат с ботом.'
        )
        bot.send_message(
            support_chat_id,
            reply_to_specialist_2.format(
                get_support_name_by_chat_id(support_chat_id),
                user.first_name + user.last_name))
    elif user.current_communic_is_appointed == 1 and user.has_active_communics == 1 and support_chat_id != user.current_communic_responsible:
        reply_to_specialist_3 = (
            '{0}, Вы хотели перевести на себя коммуникацию с пользователем {1}. Эта коммуникация уже закреплена за другим специалистом.'
        )
        bot.send_message(
            support_chat_id,
            reply_to_specialist_3.format(
                get_support_name_by_chat_id(support_chat_id),
                user.first_name + user.last_name))
    elif specialist_has_communics:
        reply_to_specialist_4 = (
            '{0}, Вы хотели перевести на себя коммуникацию с пользователем {1}. У Вас есть текущая коммуникация. Для перевода на Вас новой коммуникации следует сначала закрыть текущую.'
        )
        bot.send_message(
            support_chat_id,
            reply_to_specialist_4.format(
                get_support_name_by_chat_id(support_chat_id),
                user.first_name + user.last_name))
    else:
        bot.send_message(support_chat_id, config.REPLY['incorrect_request'])