コード例 #1
0
def botcmd_list_newfound(data):
    cmd, args = data['text'].split(' ', 1)
    skip = 0

    if '/' in args:
        args, skip = args.split('/', 1)
        skip = int(skip)

    notify = load_notify(data, args)

    if notify and skip < notify.found_new:
        count = settings.CHATBOT_SERP_COUNT
        data['text'] = notify.task.query
        found_new = notify.found_new
        plural = ukr_plural(found_new, 'нову декларацію', 'нові декларації',
                            'нових декларацій')
        message = 'За підпискою: {}'.format(notify.task.query_title)
        message += '\n\nЗнайдено {} {}'.format(found_new, plural)
        message += '\n\nПоказані {} починаючи з {}'.format(count, skip + 1)
        message = TABLE_LINE + "\n\n{}\n\n".format(message) + TABLE_LINE
        new_decl = load_declarations(notify.new_ids[skip:])
        attachments = decl_list_to_chat_cards(new_decl,
                                              data,
                                              settings,
                                              notify.task.deepsearch,
                                              skip=skip,
                                              total=found_new,
                                              notify_id=notify.id)
        chat_response(data, message, attachments=attachments)
    else:
        message = 'Більше немає результатів.'
        chat_response(data, message)
コード例 #2
0
ファイル: views.py プロジェクト: andyfuse/declarations.com.ua
def send_greetings(data):
    for member in data.get('membersAdded', []):
        if 'bot' in member.get('name', '').lower():
            continue
        data['from'] = {'id': data['conversation']['id']}
        message = 'Вітаю!\n\nЯку декларацію ти шукаєш сьогодні?'
        chat_response(data, message)
        # send greetings only once
        break
コード例 #3
0
def botcmd_list_subscribe(data):
    channel = data.get('channelId', '')
    attachments = []
    for task in list_subscriptions(data):
        plural = ukr_plural(task.found_total, 'декларацію', 'декларації',
                            'декларацій')
        # telegram fix
        if channel == 'telegram':
            query = task.id
        else:
            query = task.query or task.id
        att = {
            "contentType": "application/vnd.microsoft.card.hero",
            "content": {
                "title":
                "За запитом: {}".format(task.query),
                "subtitle":
                "Знайдено {} {}".format(task.found_total, plural),
                "text":
                "Щоб відписатись він наступних повідомлень по цьому запиту, оберіть:",
                "buttons": [{
                    "type": "imBack",
                    "title": "Відписатись",
                    "value": "відписатись {}".format(query)
                }]
            }
        }

        attachments.append(att)

    sbcount = len(attachments)
    splural = ukr_plural(sbcount, "підписка", "підписки", "підписок")
    message = "У вас {} {}".format(sbcount, splural)

    return chat_response(data, message, attachments=attachments)
コード例 #4
0
def botcmd_help(data):
    message = (
        "Вітаю, я бот для пошуку декларацій депутатів та чиновників.\n\n-\n\n"
        +
        "Мені можна відправити будь-який запит і я негайно знайду декларації. "
        +
        "Ще можна підписатись на оновлення і першим отримувати сповіщення про нові "
        + "декларації за вашим запитом. А ще я розумію команди: \n\n-\n\n" +
        "“підписатись” — моніторити останній запит, отримувати оновлення в чат,\n\n"
        +
        "“підписки” — показати список підписок моніторингу, там же можна відписатись.\n\n"
        +
        "“вхід” — перейти до власного кабінету на сайті декларацій.\n\n-\n\n" +
        "Щоб дізнатись більше, завітайте на наш сайт. Дякую, що користуєтесь.")

    attachments = [{
        "contentType": "application/vnd.microsoft.card.hero",
        "content": {
            "buttons": [{
                "type": "imBack",
                "title": "Мої підписки",
                "value": "підписки"
            }, {
                "type": "openUrl",
                "title": "Перейти на сайт",
                "value": settings.SITE_URL
            }]
        }
    }]
    return chat_response(data, message, attachments=attachments)
コード例 #5
0
def send_greetings(data):
    # dont send greetings if chat already started
    message = chat_last_message(data, not_older_than=1)
    if message:
        return

    # send greetings to first not bot in membersAdded
    for member in data.get('membersAdded', []):
        if 'bot' in member.get('name', '').lower():
            continue
        data['from'] = {'id': data['conversation']['id']}
        message = (
            'Вітаю, яку декларацію ти шукаєш сьогодні? Щоб дізнатись більше напишіть "довідка".'
        )
        chat_response(data, message)
        # send greetings only once
        break
コード例 #6
0
def botcmd_subscribe(data):
    text = clean_botcmd_arg(data)

    if not text or is_bot_command(text):
        return chat_response(data, 'Спочатку зробіть запит')

    try:
        create_subscription(data, text)
    except ValueError as e:
        chat_response(data, 'Не вдалось створити підписку: {}'.format(e))
        return
    except Exception as e:
        chat_response(
            data,
            'От халепа! Трапилась помилка при створені підписки: {}'.format(e))
        raise

    message = ""
    attachments = [{
        "contentType": "application/vnd.microsoft.card.hero",
        "content": {
            "title":
            "Створено підписку: {}".format(text),
            "subtitle":
            "Щоб переглянути всі підписки, оберіть:",
            "buttons": [{
                "type": "imBack",
                "title": "Мої підписки",
                "value": "підписки"
            }]
        }
    }]
    chat_response(data, message, attachments=attachments)
コード例 #7
0
def botcmd_unsubscribe(data):
    text = clean_botcmd_arg(data)

    if not text or is_bot_command(text):
        return chat_response(data, 'Спочатку зробіть запит')

    task = find_subscription(data, text)

    if not task:
        return chat_response(data, 'Завдання з таким запитом не знайдено')

    task.is_enabled = False
    task.is_deleted = True
    task.save()

    chat_response(
        data,
        'Підписка відмінена, ви більше не будете отримувати повідомлень за цим запитом.'
    )
コード例 #8
0
def botcmd_login_url(data):
    login_link = settings.SITE_URL + get_chat_login_link(data)
    message = ""
    attachments = [{
        "contentType": "application/vnd.microsoft.card.hero",
        "content": {
            "title":
            "Перейти до кабінету на сайті",
            "text":
            "Посилання для входу на сайт діятиме протягом 15 хвилин",
            "buttons": [{
                "type": "openUrl",
                "title": "Перейти на сайт",
                "value": login_link
            }]
        }
    }]
    return chat_response(data, message, attachments=attachments)
コード例 #9
0
def search_reply(data):
    if not data.get('text') or len(data['text']) > 100:
        return chat_response(data, 'Не зрозумів, уточніть запит.')

    text = data['text'].strip(' .,;:!-()\n').lower()

    for r, message in QUICK_ANSWERS:
        if r.match(text):
            if isinstance(message, (list, tuple, set)):
                message = choice(message)
            return chat_response(data, message)

    for r, handler in CHATBOT_COMMANDS:
        if r.match(text):
            return handler(data)

    # deepsearch switch
    deepsearch = False
    if ' /' in text:
        for deep in (' /deep', ' /всюди'):
            if deep in data['text']:
                deepsearch = True
                data['text'] = data['text'].replace(deep, '')

    # pagination in format query /skip
    skip = 0
    count = settings.CHATBOT_SERP_COUNT
    if re.search(r' /\d+$', text):
        text, skip = data['text'].rsplit(' ', 1)
        data['text'] = text
        skip = int(skip[1:])

    search = simple_search(data['text'], deepsearch=deepsearch)

    # it found nothing try again with deepsearch
    if search.found_total == 0 and not deepsearch:
        deepsearch = True
        search = simple_search(data['text'], deepsearch=deepsearch)

    found_total = search.found_total
    plural = ukr_plural(found_total, 'декларацію', 'декларації', 'декларацій')
    message = 'Знайдено {} {}'.format(found_total, plural)

    if found_total == 0:
        message = 'За запитом "{}" декларацій не знайдено.'.format(
            data['text'])
        message += '\n\n-\n\n'
        message += choice(NOT_FOUND_RESPONSES)

    elif found_total > skip + count:
        if skip:
            message += '\n\nПоказано {} починаючи з {}'.format(count, skip + 1)
        else:
            message += '\n\nПоказано перші {}'.format(count)

    if found_total > 0:
        message = TABLE_LINE + "\n\n{}\n\n".format(message) + TABLE_LINE

    if found_total > 0 and skip > 0:
        search = search[skip:]

    attachments = decl_list_to_chat_cards(search,
                                          data,
                                          settings,
                                          deepsearch,
                                          skip=skip,
                                          total=found_total)

    return chat_response(data, message, attachments=attachments)
コード例 #10
0
ファイル: views.py プロジェクト: andyfuse/declarations.com.ua
def search_reply(data):
    if not data.get('text') or len(data['text']) > 100:
        return chat_response(data, 'Не зрозумів, уточніть запит.')

    text = data['text'].strip(' .,;!\n').lower()

    for r, message in COMMON_ANSWERS:
        if r.match(text):
            if isinstance(message, (list, tuple, set)):
                message = choice(message)
            return chat_response(data, message)

    search = simple_search(data['text'])
    deepsearch = ''

    if search.found_total == 0:
        search = simple_search(data['text'], deepsearch=True)
        deepsearch = 'on'

    plural = ukr_plural(search.found_total, 'декларацію', 'декларації',
                        'декларацій')
    message = 'Знайдено {} {}'.format(search.found_total, plural)
    if search.found_total > 10:
        message += '\n\nПоказані перші 10'
    attachments = None

    if search.found_total:
        attachments = []
        for found in search:
            if 'date' in found.intro:
                found.intro.date = 'подана ' + str(found.intro.date)[:10]
            if 'corrected' in found.intro:
                if found.intro.corrected:
                    found.intro.corrected = 'Уточнена'
            # TODO replace EMAIL_SITE_URL -> SITE_URL
            url = settings.EMAIL_SITE_URL + reverse('details',
                                                    args=[found.meta.id])
            att = {
                "contentType": "application/vnd.microsoft.card.hero",
                "content": {
                    "title":
                    join_res(found.general,
                             ('last_name', 'name', 'patronymic'), ' '),
                    "subtitle":
                    join_res(
                        found.intro,
                        ('declaration_year', 'doc_type', 'corrected', 'date'),
                        ', '),
                    "text":
                    join_res(found.general.post, ('region', 'office', 'post'),
                             ', '),
                    "buttons": [{
                        "type": "openUrl",
                        "title": "Відкрити",
                        "value": url
                    }]
                }
            }
            if 'url' in found.declaration:
                button = {
                    "type": "openUrl",
                    "title": "Показати оригінал",
                    "value": found.declaration.url
                }
                att['content']['buttons'].append(button)

            attachments.append(att)

            if len(attachments) >= 10:
                # TODO replace EMAIL_SITE_URL -> SITE_URL
                url = settings.EMAIL_SITE_URL + reverse_qs(
                    'search', qs={
                        'q': data['text'],
                        'deepsearch': deepsearch
                    })
                att = {
                    "contentType": "application/vnd.microsoft.card.hero",
                    "content": {
                        "title":
                        "Більше декларацій",
                        "subtitle":
                        "Щоб побачити більше перейдіть на сайт",
                        "buttons": [{
                            "type": "openUrl",
                            "title": "Продовжити пошук на сайті",
                            "value": url
                        }]
                    }
                }
                attachments.append(att)
                break

    return chat_response(data, message, attachments=attachments)