Example #1
0
def close_current_communic_by_button(id_, support_chat_id, prefix):

    user_chat_id = db.get_user_chat_id_by_responsible(support_chat_id)
    u = db.get_user_namedtuple(user_chat_id)
    if user_chat_id != None:
        archive_communic_from_chat_id(user_chat_id)
        db.set_user(user_chat_id,
                    current_communic_is_appointed=0,
                    current_communic_responsible=0,
                    has_active_communics=0,
                    message_log='\'' + config.REPLY['communic_closed'] + '\'')
        reply_to_group = (
            ('Специалист {0} закрыл коммуникацию с пользователем: \n\n' +
             print_userinfo(user_chat_id, with_log=False)).format(
                 get_support_name_by_chat_id(support_chat_id)))
        reply_to_specialist = (
            '[ServiceBot] Вы закрыли коммуникацию с пользователем: \n\n' +
            print_userinfo(user_chat_id, with_log=False))
        bot.send_message(support_chat_id, prefix + reply_to_specialist)
        for gr in SUPPORTGROUPS:
            bot.send_message(gr, reply_to_group)
    elif user_chat_id == None:
        bot.answer_callback_query(id_,
                                  prefix + config.REPLY['no_active_communics'],
                                  show_alert=True)
Example #2
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)
Example #3
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'])
Example #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)
Example #5
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мена адреса электронной почты поддерживается при прохождении процедуры аутентификации'
            )
Example #6
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,
            'Это не похоже на адрес электронной почты. Введите Ваш рабочий адрес электронной почты для отправки Вам кода аутентификации'
        )
Example #7
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)
Example #8
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, 'Код аутентификации указан неверно')
Example #9
0
 def POST(self):
     data = web.input()
     user = {'name': data['name'],
             'pass': data['pass'],
             'hue': session.page_data['user']['hue'],
             'lang': data['lang']}
             
     for key in user.keys():
         session.page_data['user'][key] = user[key]
         
     if 'cancel' in data:
         raise web.seeother('/forum#top')
         
     elif 'apply' in data:
         if data['name']:
             # no errors
             db.set_user(session.uid, **user)
             raise web.seeother('/forum#top')
             
     elif 'color' in data:
         session.page_data['user']['hue'] = float(int(data.color)) / config.colorbar_len
         
     raise web.seeother(web.ctx.path) # stay here, only refresh
Example #10
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)
Example #11
0
def check_user_noreply_interval():

    communics = db.get_all_users_namedtuple()
    if communics:
        for u in communics:
            if u.last_msg_time_from_user != 0 and u.last_msg_time_from_specialist != 0 and u.current_communic_responsible != 0:
                if u.last_msg_time_from_user < u.last_msg_time_from_specialist and time(
                ) - u.last_msg_time_from_specialist > config.timeout_noreply:
                    archive_communic_from_chat_id(u.chat_id, timeout=True)
                    db.set_user(u.chat_id,
                                has_active_communics=0,
                                current_communic_is_appointed=0,
                                current_communic_responsible=0,
                                message_log='\'' +
                                config.REPLY['communic_closed'] + '\'')
                    bot.send_message(
                        u.current_communic_responsible,
                        'Коммуникация, закрепленная ранее за Вами, автоматически закрыта по таймауту.'
                    )
                    for gr in SUPPORTGROUPS:
                        bot.send_message(
                            gr, 'Коммуникация от пользователя: \n\n' +
                            print_userinfo(u.chat_id, with_log=False) +
                            '\nбыла автоматически закрыта по таймауту.')
Example #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'])
Example #13
0
def registration():
    clear_errors(session)
    if request.method == 'POST':
        set_user(request.form, db_session, session)
    return render_template('sign-up-page.html', session=session)