Exemple #1
0
def say_random(text):
    word = text.split()[0]
    if random.randint(0, 1) == 1:
        if random.randint(0, 1) == 1:
            word = word + " "
        else:
            word = " " + word
    msg = ""
    n = 0
    r = Message.select().where(Message.message.contains(word))
    count = r.count()
    if count > 0:
        while n < 3:
            msg = r[random.randrange(0, count)]
            if len(msg.message) < 100:
                break
            n += 1

    if msg == "":
        n = 0
        while n < 3:
            msg = Message.select()[random.randrange(0, Message.select().count())]
            n += 1
            if len(msg.message) < 100:
                break
    return msg.message
 def record_message_and_payload(self,
                                message,
                                payload,
                                with_follow_up=False):
     """Save conversation Message and Mark message to followup """
     conversation = Conversation.set_postback(self.conversation, payload)
     Message.save_text(conversation, message, with_follow_up=with_follow_up)
    def process_text(self, message_text):
        """ 
        Understand text, process something and create response
        random text: outputs Default Options
        lyrics text (with previous Postback) : process request text
        """
        (conversation, needs_follow_up,
         payload) = Conversation.get_last_message(self.conversation)
        Message.save_text(conversation, message_text)
        if needs_follow_up:
            if payload == "LYRICS_PAYLOAD":
                found_songs_data = MusixMatchAPI.search_lyrics(message_text)
                if len(found_songs_data) < 1:
                    sorry_message = "Lo siento, No pudimos encontrar la canción :("
                    return (sorry_message, ResponseType.text)
                else:
                    response_message = "Encontré {} canciones, espero esté la que buscabas".format(
                        len(found_songs_data))
                    response_data = {
                        "text": response_message,
                        "data": found_songs_data,
                        "buttons": {
                            "title": "Favorita",
                            "payload": "FAVORITE_{}_PAYLOAD",
                        }
                    }
                    return (response_data, ResponseType.results)

        return (message_text, ResponseType.default)
Exemple #4
0
def callbackapi(request):
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    if body['type'] == 'confirmation':

        return HttpResponse(settings.VK_CONFIRMATION_KEY) # подтверждение запроса от вк

    elif body['type'] == 'message_new':
        user_id = body['object']['user_id'] # получить id пользователя
        body = body['object']['body'] # получить тело сообщения
        reply_body =  '' # возвращаемое сообщение
        reply_delimeters = '' # возвращаемый разделитель

        user_context = redis_connection.get( 'vk:{user_id}'.format(user_id=user_id) ) # получить предыдущий контекст сохраненный в redis
        if user_context is not None:
            context = json.loads( user_context.decode("utf-8") ) # если контекст существует в бд, то десериализовать его в объект
        else:
            context = {'status': 'clear', 'messages': []} # иначе создать новый объект контекста

        if body.lower().strip() == 'привет' and context['status'] != 'record': # если введена команда привет и до это не было команды начать запись
            context['status'] = 'new' # установить статус
            context['messages'] = [] # установить пустой массив сообщений
            reply_delimeters = 'Запись началась.' # вернуть ответ о начале записи

        elif body.lower().strip() == 'пока': # если введена команда пока
            context['status'] = 'closed' # установить статус закрыто
            reply_delimeters = 'Запись завершена.' # вернуть запись завершена

        if context['status'] == 'record': # если статус record
            context['messages'].append(body) # добавить сообщение в массив messages в контексте
            message = Message(
                user_id = user_id,
                body = body,
                source = Message.SOURCE_VK
            )
            message.save() # сохранить запись в вк
        elif context['status'] == 'new': # если статус new
            if context.get('count'): # если в контексте есть кол-во слов
                reply_body = 'В прошлом диалоге было {count} слов.'.format(count=context['count']) # вернуть кол-во слов
                del context['count'] # удалить кол-во слов из контекста
            context['status'] = 'record' # установить статус запись
        elif context['status'] == 'closed': # если статус closed
            messages = context['messages']
            count = 0
            for message in messages: # посчитать кол-во слов
                count += len(message.strip().split(' '))
            context['count'] = count
            context['status'] = 'unknown' # установить статус unknown
        elif context['status'] == 'clear': # если статус clear
            reply_body = 'Для начала диалога напишите мне Привет, а для окончания Пока' # вернуть сообщение
        elif context['status'] == 'unknown': # если статус unknown
            reply_body = 'Для начала диалога напишите мне Привет' # вернуть сообщение

        redis_connection.set( 'vk:{user_id}'.format(user_id=user_id), json.dumps( context ) ) # сохранить контекст в redis

        api.message_send(reply_delimeters + "\n" + reply_body, user_id) # написать пользователю сформированный ответ

        return HttpResponse('ok') # вернуть ответ вк, чтобы он не повторял запросы
Exemple #5
0
def say_random():
    msg = ""
    n = 0
    while n < 3:
        msg = Message.select()[random.randrange(0, Message.select().count())]
        n += 1
        if len(msg.message) < 100:
            break
    return msg.message
Exemple #6
0
def stats(cmd):
    msg_q = Message.select()
    msgs = [msg for msg in msg_q]
    s = _("""Total number of messages:
    {msg_count}""").format(
            msg_count=len(msgs))
    return s
Exemple #7
0
    def _add_message_to_db(json_dict: dict) -> (None, True):
        try:
            sender_id = json_dict['message']['from'].get('id')
            sender_object = User.objects.filter(user_id__exact=sender_id).get()
            update_id = json_dict.get('update_id')
            message_text = json_dict['message'].get('text')
            message_date = json_dict['message'].get('date')
        except KeyError:
            return None
        if None in (sender_id, update_id, message_text, message_date):
            return None

        if _update_id_exists(update_id):
            return True

        if _is_user_registered(sender_id):
            try:
                Message(
                    update_id=int(update_id),
                    text=str(message_text),
                    sender=sender_object,
                    date=datetime.fromtimestamp(int(message_date)),
                ).save()
                return True
            except (KeyError, ValueError):
                return None
        else:
            raise ValueError('Sender is rejected')
Exemple #8
0
def do_echo(update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    text = update.message.text

    print("Echo")

    profile, _ = Profile.objects.get_or_create(
        telegram_id=chat_id,
        defaults={
            'name': update.message.from_user.username,
        })

    m = Message(
        profile=profile,
        text=text,
    )
    m.save()

    reply_text = f'Profile ID: {chat_id}\nText: {text}\nMessage ID: {m.pk}'
    update.message.reply_text(text=reply_text)
Exemple #9
0
def button(update: Update, context: CallbackContext):
    query = update.callback_query
    chat_id = update.callback_query.message.chat_id
    name = update.callback_query.message.chat.username

    profile, _ = Profile.objects.get_or_create(telegram_id=chat_id,
                                               defaults={
                                                   'name': name,
                                               })

    store = Store.objects.get(id=int(query.data), )

    m = Message(
        profile=profile,
        text='Зарезервировано',
        store=store,
    )
    m.save()

    query.edit_message_text(text="Selected option: {}".format(query.data))
Exemple #10
0
    def get_context(self, bot, update, **kwargs):
        user_id = update.message.chat.id  # id пользователя
        body = update.message.text  # тело сообщения
        reply_body = ''

        user_context = redis_connection.get(
            'telegram:{user_id}'.format(user_id=user_id)
        )  # получить предыдущий контекст сохраненный в redis
        if user_context is not None:
            context = json.loads(
                user_context.decode("utf-8")
            )  # если контекст существует в бд, то десериализовать его в объект
        else:
            context = {
                'status': 'clear',
                'messages': []
            }  # иначе создать новый объект контекста

        if context['status'] == 'record':  # если статус record
            context['messages'].append(
                body)  # добавить сообщение в messages в объекте контекст
            message = Message(user_id=user_id,
                              body=body,
                              source=Message.SOURCE_TELEGRAM)
            message.save()  # сохранить в базу данных сообщение
            reply_body = 'Записал: {body}'.format(
                body=body)  # ответное сообщение после сохранения
        elif context['status'] == 'clear':  # если статус clear
            reply_body = 'Для начала диалога напишите мне /hello, а для окончания /bye'  # ответное сообщение с уведомлением
        elif context['status'] == 'closed':  # если статус clear
            reply_body = 'Для начала диалога напишите мне /hello'  # ответное сообщение с уведомлением

        redis_connection.set('telegram:{user_id}'.format(user_id=user_id),
                             json.dumps(context))  # сохранить контекст в redis

        response = {
            self.context_object_name: reply_body
        }  # переопределение контекста шаблона

        return response
Exemple #11
0
def do_echo(update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    text = update.message.text

    p, _ = Profile.objects.get_or_create(external_id=chat_id,
                                         defaults={
                                             'name':
                                             update.message.from_user.username,
                                         })

    Message(profile=p, text=text).save()

    reply_text = f'Hi, id - {chat_id}, txt = {p.name}'
    update.message.reply_text(text=reply_text, )
Exemple #12
0
def load_history(pk):
    """Task for first time grab. """
    from bot.models import Message, Workspace

    workspace = Workspace.objects.get(id=pk)
    parser = LoadHistory(workspace)
    rocket = RocketChat(ROCKET_USER, ROCKET_PASS, server_url=ROCKET_URL)
    for channel in workspace.channels.all():
        print(channel.name)
        history = parser.load_history_v2(channel.name)
        messages_obj = [Message(**message) for message in history]
        Message.objects.bulk_create(messages_obj)
        for message in history:
            send_message_to_rocket(rocket,
                                   f"{channel.name}: {message['text']}",
                                   ROCKET_CHANNEL)
Exemple #13
0
def workspace_supervisor():
    from bot.models import Workspace, Message
    workspaces = Workspace.objects.all()
    messages = []
    rocket = RocketChat(ROCKET_USER, ROCKET_PASS, server_url=ROCKET_URL)
    for workspace in workspaces:
        parser = LastMessagesParser(workspace=workspace)
        for channel in workspace.channels.all():
            all_last_messages = parser.get_messages(channel.name)
            for message in all_last_messages:
                send_message_to_rocket(rocket,
                                       f"{channel.name}: {message['text']}",
                                       ROCKET_CHANNEL)
            messages += [Message(**message) for message in all_last_messages]

    Message.objects.bulk_create(messages)
Exemple #14
0
def write_stats(msg):
    if msg.content:
        db.connect(reuse_if_open=True)
        db.create_tables([User, Message])
        user_q = User.select().where(User.user_id == msg.user['id'])
        users = [user for user in user_q]
        if len(users) == 0:
            is_telegram = True if msg.is_telegram else False
            user = User.create(user_id=msg.user['id'],
                               is_telegram=is_telegram,
                               username=msg.user['name'])
            user.save()
        else:
            user = users[0]
        msg = Message.create(user=user,
                             message=msg.content,
                             timestamp=round(datetime.now().timestamp()))
        msg.save()