예제 #1
0
def start_poll(query: catbot.CallbackQuery):
    data_token = query.data.split('_')
    try:
        cmd_chat_id = int(data_token[1])
        cmd_id = int(data_token[2])
    except ValueError:
        bot.answer_callback_query(query.id)
        return

    with t_lock:
        poll_list, rec = record_empty_test('poll', list)
        for i in range(len(poll_list)):
            p = Poll.from_json(poll_list[i])
            if p.chat_id == cmd_chat_id and p.init_id == cmd_id:
                break
        else:
            bot.answer_callback_query(
                query.id, text=config['messages']['start_poll_not_found'])
            return

        p.start()

        button_list = []
        for j in range(len(p.option_list)):
            option = p.option_list[j]
            button_list.append([
                catbot.InlineKeyboardButton(
                    option['text'],
                    callback_data=f'vote_{p.chat_id}_{p.init_id}_{j}')
            ])
        button_list.append([
            catbot.InlineKeyboardButton(
                config['messages']['stop_poll_button'],
                callback_data=f'vote_{p.chat_id}_{p.init_id}_stop')
        ])
        keyboard = catbot.InlineKeyboard(button_list)

        poll_msg: catbot.Message = bot.send_message(
            query.msg.chat.id,
            text=get_poll_text(p),
            reply_markup=keyboard,
            reply_to_message_id=query.msg.id,
            parse_mode='HTML')
        bot.edit_message(query.msg.chat.id,
                         query.msg.id,
                         text=query.msg.html_formatted_text,
                         parse_mode='HTML')
        bot.answer_callback_query(query.id,
                                  text=config['messages']['start_poll_answer'])

        p.poll_id = poll_msg.id
        poll_list[i] = p.to_json()
        rec['poll'] = poll_list
        json.dump(rec,
                  open(config['record'], 'w', encoding='utf-8'),
                  indent=2,
                  ensure_ascii=False)
def confirm(msg: catbot.Message):
    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)

        entry_index = -1
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == msg.from_.id:
                if entry.confirmed:
                    bot.send_message(msg.chat.id, text=config['messages']['confirm_already'].format(
                        wp_name=get_mw_username(entry.mw_id)
                    ))
                    return
                elif entry.confirming:
                    bot.send_message(msg.chat.id, text=config['messages']['confirm_confirming'])
                    return
                elif entry.refused:
                    bot.send_message(msg.chat.id, text=config['messages']['confirm_ineligible'])
                    return
                else:
                    entry_index = i

        else:
            if entry_index == -1:
                entry = Ac(msg.from_.id)
                ac_list.append(entry.to_dict())
            entry = Ac.from_dict(ac_list[entry_index])
            entry.confirming = True
            ac_list[entry_index] = entry.to_dict()

        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    button = catbot.InlineKeyboardButton(config['messages']['confirm_button'], callback_data=f'confirm')
    keyboard = catbot.InlineKeyboard([[button]])
    bot.send_message(msg.chat.id, text=config['messages']['confirm_wait'].format(
        link=config['oauth_auth_url'].format(telegram_id=msg.from_.id),
    ),
                     parse_mode='HTML', disable_web_page_preview=True, reply_markup=keyboard)
예제 #3
0
def vote(query: catbot.CallbackQuery):
    callback_token = query.data.split('_')
    voter_dict = record_empty_test('voter', dict)[0]
    trusted_list = record_empty_test('trusted', list)[0]
    ac_list = record_empty_test('ac', list, file=config['ac_record'])[0]

    if str(query.msg.chat.id) in voter_dict.keys():
        voter_list = voter_dict[str(query.msg.chat.id)] + trusted_list
    else:
        voter_list = trusted_list

    if not len(callback_token) == 4:
        bot.answer_callback_query(query.id)
        return
    try:
        callback_chat_id = int(query.data.split('_')[1])
        callback_init_id = int(query.data.split('_')[2])
        choice = int(query.data.split('_')[3])
    except ValueError:
        bot.answer_callback_query(query.id)
        return

    with t_lock:
        poll_list, rec = record_empty_test('poll', list)
        for i in range(len(poll_list)):
            p = Poll.from_json(poll_list[i])

            if p.chat_id == callback_chat_id and p.init_id == callback_init_id and p.open:
                # privilege check
                if p.privilege_level == 1 and query.from_.id not in voter_list:
                    bot.answer_callback_query(
                        query.id, text=config['messages']['vote_ineligible'])
                    return
                if p.privilege_level == 2 and query.from_.id not in voter_list:
                    for user in ac_list:
                        if user['telegram_id'] == query.from_.id and not user[
                                'confirmed']:
                            bot.answer_callback_query(
                                query.id,
                                text=config['messages']['vote_ineligible'])
                            return
                        if user['telegram_id'] == query.from_.id and user[
                                'confirmed']:
                            break
                    else:
                        bot.answer_callback_query(
                            query.id,
                            text=config['messages']['vote_ineligible'])
                        return

                p.vote(query.from_.id, choice)

                poll_list[i] = p.to_json()
                rec['poll'] = poll_list
                json.dump(rec,
                          open(config['record'], 'w', encoding='utf-8'),
                          indent=2,
                          ensure_ascii=False)

                bot.answer_callback_query(
                    query.id,
                    text=config['messages']['vote_received'],
                    show_alert=True)
                button_list = []
                for j in range(len(p.option_list)):
                    option = p.option_list[j]
                    button_list.append([
                        catbot.InlineKeyboardButton(
                            option['text'],
                            callback_data=f'vote_{p.chat_id}_{p.init_id}_{j}')
                    ])
                button_list.append([
                    catbot.InlineKeyboardButton(
                        config['messages']['stop_poll_button'],
                        callback_data=f'vote_{p.chat_id}_{p.init_id}_stop')
                ])
                keyboard = catbot.InlineKeyboard(button_list)

                bot.edit_message('-100' + str(callback_chat_id),
                                 p.poll_id,
                                 text=get_poll_text(p),
                                 reply_markup=keyboard,
                                 parse_mode='HTML')
                break

            elif p.chat_id == callback_chat_id and p.init_id == callback_init_id and not p.open:
                bot.answer_callback_query(
                    query.id,
                    text=config['messages']['vote_poll_stopped'],
                    show_alert=True)
                break
예제 #4
0
def init_poll(msg: catbot.Message):
    user_input_token = msg.html_formatted_text.split()
    if len(user_input_token) == 1:
        bot.send_message(msg.chat.id,
                         text=config['messages']['init_poll_failed'],
                         reply_to_message_id=msg.id)
        return
    poll_chat_id = int(str(msg.chat.id).replace('-100', ''))
    p = Poll(poll_chat_id, msg.id)

    i = 1
    parser = parsedatetime.Calendar()
    while i < len(user_input_token):
        if user_input_token[i] == '-n':
            i += 1
            title_list = []
            while i < len(user_input_token
                          ) and not user_input_token[i].startswith('-'):
                title_list.append(user_input_token[i])
                i += 1
            p.title = ' '.join(title_list)

        elif user_input_token[i] == '-t':
            i += 1
            t_list = []
            while i < len(user_input_token
                          ) and not user_input_token[i].startswith('-'):
                t_list.append(user_input_token[i])
                i += 1
            t_str = ' '.join(t_list)
            p.last_time = time.mktime(
                parser.parse(datetimeString=t_str)[0]) - time.time()
            p.readable_time = t_str

        elif user_input_token[i] == '-o':
            i += 1
            option_text = ''
            while i < len(user_input_token
                          ) and not user_input_token[i].startswith('-'):
                option_text += user_input_token[i] + ' '
                i += 1
            options = option_text.split('!')
            for j in range(options.count('')):
                options.remove('')
            p.set_option(options)

        elif user_input_token[i] == '-ao':
            p.anonymous_open = True
            i += 1
        elif user_input_token[i] == '-ac':
            p.anonymous_closed = True
            i += 1
        elif user_input_token[i] == '-c':
            p.count_open = True
            i += 1
        elif user_input_token[i] == '-m':
            p.multiple = True
            i += 1
        elif user_input_token[i] == '-p':
            i += 1
            while i < len(user_input_token
                          ) and not user_input_token[i].startswith('-'):
                try:
                    p.privilege_level = int(user_input_token[i])
                except ValueError:
                    bot.send_message(
                        msg.chat.id,
                        text=config['messages']['init_poll_failed'],
                        reply_to_message_id=msg.id)
                    return
                else:
                    i += 1
                    break
        else:  # format error
            bot.send_message(msg.chat.id,
                             text=config['messages']['init_poll_failed'],
                             reply_to_message_id=msg.id)
            return

    if len(p.option_list) == 0:
        bot.send_message(msg.chat.id,
                         text=config['messages']['init_poll_failed'],
                         reply_to_message_id=msg.id)
        return

    with t_lock:
        poll_list, rec = record_empty_test('poll', list)
        poll_list.append(p.to_json())
        rec['poll'] = poll_list
        json.dump(rec,
                  open(config['record'], 'w', encoding='utf-8'),
                  indent=2,
                  ensure_ascii=False)

    resp_text = config['messages']['init_poll_succ'].format(
        title=p.title,
        last=p.readable_time,
        anon_open=p.anonymous_open,
        anon_closed=p.anonymous_closed,
        count_open=p.count_open,
        multiple=p.multiple,
        privilege=config['messages']['vote_privilege'][str(p.privilege_level)])
    start_button = catbot.InlineKeyboardButton(
        config['messages']['start_poll_button'],
        callback_data=f'vote_{p.chat_id}_{p.init_id}_start')
    abort_button = catbot.InlineKeyboardButton(
        config['messages']['abort_poll_button'],
        callback_data=f'vote_{p.chat_id}_{p.init_id}_abort')
    keyboard = catbot.InlineKeyboard([[start_button, abort_button]])
    bot.send_message(msg.chat.id,
                     text=resp_text,
                     reply_to_message_id=msg.id,
                     reply_markup=keyboard,
                     parse_mode='HTML')
def deconfirm(msg: catbot.Message):
    button = catbot.InlineKeyboardButton(config['messages']['deconfirm_button'], callback_data='deconfirm')
    keyboard = catbot.InlineKeyboard([[button]])
    bot.send_message(msg.chat.id, text=config['messages']['deconfirm_prompt'], reply_markup=keyboard)