예제 #1
0
async def _query_command(bot, update, user_record):
    query = get_cleaned_text(update, bot, [
        'query',
    ])
    query_id = None
    if len(query) == 0:
        return bot.get_message('admin',
                               'query_command',
                               'help',
                               update=update,
                               user_record=user_record)
    try:
        with bot.db as db:
            record = db.query(query)
            try:
                record = list(record)
            except ResourceClosedError:
                record = bot.get_message('admin',
                                         'query_command',
                                         'no_iterable',
                                         update=update,
                                         user_record=user_record)
            query_id = db['queries'].upsert(dict(query=query), ['query'])
            if query_id is True:
                query_id = db['queries'].find_one(query=query)['id']
        result = json.dumps(record, indent=2)
        if len(result) > 500:
            result = (
                f"{result[:200]}\n"  # First 200 characters
                f"[...]\n"  # Interruption symbol
                f"{result[-200:]}"  # Last 200 characters
            )
    except Exception as e:
        result = "{first_line}\n{e}".format(first_line=bot.get_message(
            'admin',
            'query_command',
            'exception',
            update=update,
            user_record=user_record),
                                            e=e)
    result = ("<b>{first_line}</b>\n".format(
        first_line=bot.get_message('admin',
                                   'query_command',
                                   'result',
                                   update=update,
                                   user_record=user_record)) +
              f"<code>{query}</code>\n\n"
              f"{result}")
    if query_id:
        reply_markup = make_inline_keyboard([
            make_button(
                text='CSV', prefix='db_query:///', data=['csv', query_id])
        ], 1)
    else:
        reply_markup = None
    return dict(chat_id=update['chat']['id'],
                text=result,
                parse_mode='HTML',
                reply_markup=reply_markup)
예제 #2
0
 def get_keyboard(chosen_button=-1):
     return make_inline_keyboard([
         make_button(
             prefix='button:///',
             delimiter='|',
             data=[i],
             text=f"{'✅' if chosen_button == i else '☑️'} Button #{i}")
         for i in range(1, 13)
     ], 3)
예제 #3
0
async def _stop_command(bot, update, user_record):
    text = bot.get_message('admin',
                           'stop_command',
                           'text',
                           update=update,
                           user_record=user_record)
    reply_markup = make_inline_keyboard([
        make_button(text=bot.get_message('admin',
                                         'stop_button',
                                         'stop_text',
                                         update=update,
                                         user_record=user_record),
                    prefix='stop:///',
                    data=['stop']),
        make_button(text=bot.get_message('admin',
                                         'stop_button',
                                         'cancel',
                                         update=update,
                                         user_record=user_record),
                    prefix='stop:///',
                    data=['cancel'])
    ], 1)
    return dict(text=text, parse_mode='HTML', reply_markup=reply_markup)
예제 #4
0
async def start_session(bot, other_user_record, admin_record):
    """Start talking session between user and admin.

    Register session in database, so it gets loaded before message_loop starts.
    Send a notification both to admin and user, set custom parsers and return.
    """
    with bot.db as db:
        db['talking_sessions'].insert(
            dict(user=other_user_record['id'],
                 admin=admin_record['id'],
                 cancelled=0))
    await bot.send_message(chat_id=other_user_record['telegram_id'],
                           text=bot.get_message('talk',
                                                'user_warning',
                                                user_record=other_user_record,
                                                u=get_user(admin_record)))
    await bot.send_message(chat_id=admin_record['telegram_id'],
                           text=bot.get_message('talk',
                                                'admin_warning',
                                                user_record=admin_record,
                                                u=get_user(other_user_record)),
                           reply_markup=make_inline_keyboard([
                               make_button(
                                   bot.get_message('talk',
                                                   'stop',
                                                   user_record=admin_record),
                                   prefix='talk:///',
                                   data=['stop', other_user_record['id']])
                           ]))
    bot.set_individual_text_message_handler(
        await async_wrapper(_forward_to,
                            sender=other_user_record['telegram_id'],
                            addressee=admin_record['telegram_id'],
                            is_admin=False), other_user_record['telegram_id'])
    bot.set_individual_text_message_handler(
        await async_wrapper(_forward_to,
                            sender=admin_record['telegram_id'],
                            addressee=other_user_record['telegram_id'],
                            is_admin=True), admin_record['telegram_id'])
    return
예제 #5
0
def get_talk_panel(bot, update, user_record=None, text=''):
    """Return text and reply markup of talk panel.

    `text` may be:
    - `user_id` as string
    - `username` as string
    - `''` (empty string) for main menu (default)
    """
    users = []
    if len(text):
        with bot.db as db:
            if text.isnumeric():
                users = list(db['users'].find(id=int(text)))
            else:
                users = list(
                    db.query("SELECT * "
                             "FROM users "
                             "WHERE COALESCE( "
                             "    first_name || last_name || username, "
                             "    last_name || username, "
                             "    first_name || username, "
                             "    username, "
                             "    first_name || last_name, "
                             "    last_name, "
                             "    first_name "
                             f") LIKE '%{text}%' "
                             "ORDER BY LOWER( "
                             "    COALESCE( "
                             "        first_name || last_name || username, "
                             "        last_name || username, "
                             "        first_name || username, "
                             "        username, "
                             "        first_name || last_name, "
                             "        last_name, "
                             "        first_name "
                             "    ) "
                             ") "
                             "LIMIT 26"))
    if len(text) == 0:
        text = (bot.get_message('talk',
                                'help_text',
                                update=update,
                                user_record=user_record,
                                q=escape_html_chars(remove_html_tags(text))))
        reply_markup = make_inline_keyboard([
            make_button(bot.get_message('talk',
                                        'search_button',
                                        update=update,
                                        user_record=user_record),
                        prefix='talk:///',
                        data=['search'])
        ], 1)
    elif len(users) == 0:
        text = (bot.get_message('talk',
                                'user_not_found',
                                update=update,
                                user_record=user_record,
                                q=escape_html_chars(remove_html_tags(text))))
        reply_markup = make_inline_keyboard([
            make_button(bot.get_message('talk',
                                        'search_button',
                                        update=update,
                                        user_record=user_record),
                        prefix='talk:///',
                        data=['search'])
        ], 1)
    else:
        text = "{header}\n\n{u}{etc}".format(
            header=bot.get_message('talk',
                                   'select_user',
                                   update=update,
                                   user_record=user_record),
            u=line_drawing_unordered_list(
                [get_user(user) for user in users[:25]]),
            etc=('\n\n[...]' if len(users) > 25 else ''))
        reply_markup = make_inline_keyboard([
            make_button('👤 {u}'.format(u=get_user({
                key: val
                for key, val in user.items()
                if key in ('first_name', 'last_name', 'username')
            })),
                        prefix='talk:///',
                        data=['select', user['id']]) for user in users[:25]
        ], 2)
    return text, reply_markup
예제 #6
0
def _make_button(text=None, callback_data='',
                 prefix='help:///', delimiter='|', data=[]):
    return make_button(text=text, callback_data=callback_data,
                       prefix=prefix, delimiter=delimiter, data=data)