Exemple #1
0
    def __init__(self):
        """Constructor"""

        self.textProcessor = TextProcessor()
        self.search = searchProcessor()
        self.tonque = Tonque()
        self.users = UserProcessor()
        self.replics = Replics()
        self.funnel = funnelProcessor()
        self.timertask = TimerProcessor()
        self.playlist = PlaylistProcessor()
        self.tracker = gaTracker()
Exemple #2
0
class processChat:
    def __init__(self):
        """Constructor"""

        self.textProcessor = TextProcessor()
        self.search = searchProcessor()
        self.tonque = Tonque()
        self.users = UserProcessor()
        self.replics = Replics()
        self.funnel = funnelProcessor()
        self.timertask = TimerProcessor()
        self.playlist = PlaylistProcessor()
        self.tracker = gaTracker()

    def response(self, json_string):
        update = types.Update.de_json(json_string)
        try:
            if update.callback_query is not None:

                self.send_debug('process_callback')
                response = self.process_callback(update.callback_query)
                chat_id = update.callback_query.message.chat.id
            else:

                self.send_debug('process')
                response = self.process(update.message)
                chat_id = update.message.from_user.id

            if 'message_id' in response:
                message_id = response['message_id']
                del response['message_id']
                self.tonque.edit_message_text(chat_id, message_id, response)

            else:
                self.tonque.send_message(chat_id, response)

            self.tracker.storeInputMessage(update.message)

        except Exception as e:
            self.tracker.storeInputMessage(str(e))
            return str(e) + str(update.message)

        return response

    def process(self, message):
        """Принимает запрос пользователя и отдает ответ в виде словаря с ключем text и markup"""
        response = None
        # if message.text[0] != '/':
        self.users.user_update(message, message.from_user.id)

        if message.reply_to_message is not None:
            return self.message_from_admin(message)

        chat_id = message.chat.id
        self.send_debug('textProcessor')
        text, text_raw, emoji = self.textProcessor.get_content(message)

        self.send_debug('add_context')

        text = self.funnel.add_context(chat_id, text)

        self.send_debug('handle_request')
        meaning_nodes = self.search.handle_request(text, d_type='words')

        self.send_debug(str(meaning_nodes))
        if len(meaning_nodes) > 0:

            if self.check_reset(meaning_nodes[0]):

                self.send_debug('process_reset')
                ##Собщение об отмене действия
                response = self.process_reset(chat_id, meaning_nodes[0], text)
            else:

                ##Проверка воронки
                self.send_debug('process_funnel')
                meaning_defined, response = self.process_funnel(
                    chat_id, 0, text, 'text_raw')
                if meaning_defined:
                    return response

                else:
                    self.send_debug('process_function')
                    ##Проверка воронки
                    response = self.process_function(chat_id, meaning_nodes[0],
                                                     text)

        else:
            self.send_debug('process_not_defined')
            response = self.not_defined(chat_id, message.message_id, text)

        return response

    def process_callback(self, callback_query):
        """Обработка Коллбэка для inline кнопок"""
        response = None
        message_id = callback_query.message.message_id
        chat_id = callback_query.message.chat.id

        command_split = callback_query.data.split('_')

        try:
            if len(command_split) > 1:

                callback_types = {
                    'start': self.timertask.timer_start,
                    'checktime': self.timertask.timer_checktime,
                    'delete': self.timertask.timer_delete,
                    'addlink': self.playlist.playlist_confirm,
                    'droplink': self.playlist.playlist_drop
                }

                if command_split[0] in callback_types:
                    functionName = callback_types[command_split[0]]
                    response = functionName(chat_id, command_split[1],
                                            message_id)

        except Exception as e:
            response = {'text': '_process_callback ' + str(e)}

        return response

    def process_function(self, user_id, meaning, text):
        """Обработка функци назначенных интентам в common.js"""

        self.send_debug('process_function')

        functions = {
            'drop': self.process_reset,
            'hello': self.process_hello,
            'playlist': self.process_playlist,
            'tomato': self.process_tomato,
            'feedback': self.process_feedback
        }

        if meaning['function'] in functions:
            function_name = functions[meaning['function']]
            response = function_name(user_id, meaning, text)
        else:
            response = self.process_text(user_id, meaning, text)

        return response

    def process_text(self, user_id, meaning, text):
        """Ответ тектом в common.js без дополгнительной обработки фугкциями"""

        self.send_debug('process_text')

        response = {'text': meaning['text']}
        if 'menu' in meaning:
            response['reply_markup'] = [i['title'] for i in meaning['menu']]

        if 'funnel' in meaning:
            self.funnel.set_funnel(user_id, meaning['funnel'], '')

        return response

    def check_reset(self, meaning):
        """Проверка на отмену действия"""

        self.send_debug('check_reset')
        if meaning['function'] == 'drop':
            return True
        else:
            return False

    def not_defined(self, chat_id, message_id, text):
        """Генерим ответ со ссылкой на оператора, если тема не найдена"""

        response = self.replics.not_defined(chat_id)  #not_defined.format(text)
        self.tonque.send_alert_admin(chat_id, message_id, text)
        return response

    def process_hello(self, chat_id, meaning, text):
        response = self.replics.tomato_hello(chat_id)
        return response

    def process_tomato(self, chat_id, meaning, text):
        response = self.replics.tomato(chat_id)
        return response

    def process_reset(self, chat_id, meaning, text):
        response = self.replics.reset(chat_id)
        self.funnel.set_funnel(chat_id, 'drop', '')
        return response

    def process_feedback(self, chat_id, meaning, text):
        pass

    def process_playlist(self, chat_id, meaning, text):
        response = self.replics.playlist_process(chat_id)
        self.funnel.set_funnel(chat_id, 'playlist_confirm', text)
        return response

    def process_funnel(self, chat_id, message_id, text, text_raw):
        """"""
        meaning_defined = False
        response = False

        funnels = {'playlist_confirm': self.playlist.playlist_confirm}

        funnel_current = self.funnel.last_funnel(chat_id)
        funnel_current = funnel_current['chatfunnel']

        if funnel_current in funnels:

            meaning_defined = 1
            functionName = funnels[funnel_current]
            response = functionName(chat_id, message_id, text)

        return meaning_defined, response

    def message_from_admin(self, message):
        response = {}
        # Ответ пользователю от Админа
        if message.reply_to_message.forward_from is not None:
            client_id = message.reply_to_message.forward_from.id
            # response = self.replySupport(text, message.chat.id)
            response = {'text': 'Вы ответили клиенту', 'reply_markup': ''}
            message_to_client = {'text': message.text}
            self.tonque.send_message(client_id, message_to_client)

        return response

    def send_debug(self, txt):
        if config.debug == 1:
            for a in config.admin_ids:
                self.tonque.send_message(a, {'text': txt})
        return True
Exemple #3
0
class funnelProcessor:
    def __init__(self):
        """Constructor"""
        self.textProcessor = TextProcessor()

    def add_context(self, chat_id, text):
        """добавление контекста к словам на основе предыдущих значений"""
        lf = self.last_funnel(chat_id)
        if lf['chatfunnel'] == 'location':

            if self.textProcessor.check_location(text):
                pass
            else:
                text_reach = '{} {}'.format(text, lf['message'])
                return text_reach

        if lf['chatfunnel'] == 'office':
            if 'курс' not in text:
                if self.textProcessor.check_location(text):
                    text_reach = '{} {}'.format(text, lf['message'])
                    return text_reach

        if lf['chatfunnel'] == 'currency':
            if 'офис' not in text:
                if self.textProcessor.check_location(text):
                    text_reach = '{} {}'.format(text, lf['message'])
                    return text_reach

        return text

    # def set_funnel_location(self,chat_id,text):
    #     location = self.textProcessor.check_location(text)
    #     if location:
    #         self.set_funnel(chat_id, 'location', location)
    #     return 1

    def set_funnel(self, chat_id, chat_funnel, message_text, type=1):
        """Сохранение состояния последней беседы. type: 1 запрос, 2 ответ."""

        funnel = ChatFunnel(chatuser_id=chat_id,
                            chatfunnel=chat_funnel,
                            message=message_text,
                            type=type)
        funnel.save()

        return 1

    def last_funnel(self, chat_id, funnel_name=None):
        """определяем была ли уже воронка с фильтром и смотрим какие данные висят в ней"""

        r = {'chatfunnel': None, 'message': None}

        q = ChatFunnel.select().where(ChatFunnel.chatuser_id == chat_id)
        if funnel_name:
            q = q.where(ChatFunnel.chatfunnel == funnel_name)

        last_funnel = q.order_by(ChatFunnel.id.desc())

        if len(last_funnel):
            last_funnel = last_funnel.get()
            r = {
                'chatfunnel': last_funnel.chatfunnel,
                'message': last_funnel.message
            }
        return r
Exemple #4
0
 def __init__(self):
     """Constructor"""
     self.textProcessor = TextProcessor()
Exemple #5
0
    def __init__(self):
        """Constructor"""
        self.TextProcessor = TextProcessor()
        self.Search = searchProcessor()

        pass
Exemple #6
0
class PlaylistProcessor:
    """Управление музыкой таймера"""
    def __init__(self):
        self.replics = Replics()
        self.funnel = funnelProcessor()
        self.textProcessor = TextProcessor()

    def get_random_link(self, chat_id):
        q = """SELECT p.url url, c
                FROM (
                    SELECT url, count(message_id) c
                    FROM timer_task tt
                    where tt.chat_id = 79711951
                    group by url
                ) tf

                right join playlist p on p.url = tf.url
                where p.status = 1
                order by c DESC
            """.format(chat_id)

        q = Playlist.raw(q).dicts()
        url_list = [i['url'] for i in q]
        url_list = url_list[5:]
        # q = Playlist.select(Playlist.url).where(Playlist.status==1).dicts()
        r = randint(0, len(url_list) - 1)

        return url_list[r]

    def playlist_drop(self, chat_id, command_id, message_id=0):

        response = self.replics.playlist_cancel(chat_id)
        self.funnel.set_funnel(chat_id, 'drop', '')

        # self.tonque.edit_message_text(chat_id, message_id, response)
        response['message_id'] = message_id

        return response

    def playlist_confirm(self, chat_id, command_id, message_id=0):

        funnel_current = self.funnel.last_funnel(
            chat_id, funnel_name='playlist_confirm')

        url = self.textProcessor.detect_url(funnel_current['message'])
        if url:

            playlist_data = {'chat_id': chat_id, 'status': 0, 'url': url}

            playlist = Playlist(**playlist_data)
            playlist.save()

            response = self.replics.playlist_confirm(chat_id)

        else:
            response = self.replics.playlist_cancel(chat_id)

        self.funnel.set_funnel(chat_id, 'drop', '')

        # self.tonque.edit_message_text(chat_id, message_id, response)
        response['message_id'] = message_id

        return response
Exemple #7
0
 def __init__(self):
     self.replics = Replics()
     self.funnel = funnelProcessor()
     self.textProcessor = TextProcessor()
Exemple #8
0
 def __init__(self):
     """Constructor"""
     self.replics = Replics()
     self.funnel = funnelProcessor()
     self.textProcessor = TextProcessor()
     self.email = EmailSender()
Exemple #9
0
class feedbackChat:
    def __init__(self):
        """Constructor"""
        self.replics = Replics()
        self.funnel = funnelProcessor()
        self.textProcessor = TextProcessor()
        self.email = EmailSender()

    def new_chat(self, chat_id, message_id, text, text_raw):
        fb = ChatFeedback(chatuser_id=chat_id)
        fb.save()
        return fb.id

    def open_last_chat(self, chat_id):
        fb = ChatFeedback.select().where(
            (ChatFeedback.chatuser_id == chat_id)).order_by(
                ChatFeedback.id.desc()).dicts()
        if len(fb):
            fb = fb.get()

        return fb

    def update_chat(self, id, fields):
        # query = ChatFeedback.update(**fields).where(ChatFeedback.id == id)
        query = ChatFeedback.update(**fields).where(ChatFeedback.id == id)
        query.execute()
        return query

    def name_add(self, chat_id, message_id, text, text_raw):

        last_chat = self.open_last_chat(chat_id)
        self.update_chat(last_chat['id'], {'name': text_raw})

        response = self.replics.feedback_name_confirm(chat_id, text_raw)
        self.funnel.set_funnel(chat_id, 'feedback_phone', '')
        return response

    def name_confirm(self, chat_id, message_id, text, text_raw):
        pass

    def phone_add(self, chat_id, message_id, text, text_raw):
        response = self.replics.feedback_phone(chat_id, text_raw)

        last_chat = self.open_last_chat(chat_id)
        self.update_chat(last_chat['id'], {'phone': text_raw})

        self.funnel.set_funnel(chat_id, 'feedback_city', '')
        return response

    def phone_confirm(self, chat_id, message_id, text, text_raw):
        pass

    def city_add(self, chat_id, message_id, text, text_raw):

        last_chat = self.open_last_chat(chat_id)
        self.update_chat(last_chat['id'], {'location': text_raw})

        response = self.replics.feedback_city(chat_id, text_raw)
        self.funnel.set_funnel(chat_id, 'feedback_form_confirm', '')

        return response

    def text_add(self, chat_id, message_id, text, text_raw):

        last_chat = self.open_last_chat(chat_id)
        self.update_chat(last_chat['id'], {'message': text_raw})

        response = self.replics.feedback_name(chat_id, text_raw)
        self.funnel.set_funnel(chat_id, 'feedback_name', '')

        return response

    def city_confirm(self, chat_id, message_id, text, text_raw):
        pass

    def time_add(self, chat_id, message_id, text, text_raw):
        pass

    def time_confirm(self, chat_id, message_id, text, text_raw):
        pass

    def form_confirm(self, chat_id, message_id, text, text_raw):
        # last_chat = self.open_last_chat(chat_id)
        # self.update_chat(last_chat['id'], {'location':text_raw})

        sentiment = self.textProcessor.define_positive(text_raw)

        if sentiment == 1:
            response = self.replics.feedback_confirm(chat_id)
            self.funnel.set_funnel(chat_id, 'drop', '')
        else:
            response = self.replics.feedback_cancel(chat_id)
            self.funnel.set_funnel(chat_id, 'drop', '')

        self.send_email(chat_id)

        return response

    def get_username(self, chat_id):
        fb = ChatUser.select().where((ChatUser.id == chat_id)).get()
        if fb.username:
            un = '(ник: @{})'.format(fb.username)
        else:
            un = ''
        return un

    def send_email(self, chat_id):
        last_chat = self.open_last_chat(chat_id)
        username = self.get_username(chat_id)

        message = 'Клиент: {} {}\n\nГород: {}\n\nТелефон: {}\n\nСообщение: {}'.format(
            last_chat['name'], username, last_chat['location'],
            last_chat['phone'], last_chat['message'])
        self.email.send_email(message)

        return 1