Exemplo n.º 1
0
def _initialize_subscribed_list(universal_id: str, _type: str):
    """Initialize the subscribed list."""
    subscribed_list = load(universal_id, _type)
    if not subscribed_list:
        subscribed_list = {}
        save(universal_id, _type, subscribed_list)
    return subscribed_list
Exemplo n.º 2
0
async def subscriber_update(bot: Bot, event: Event, state: dict):
    """Handle the subscribe command."""
    universal_id = str(event.self_id) + str(event.group_id)
    subscribed_list = load(universal_id, 'subscribed_list')
    if not subscribed_list:
        subscribed_list = {}
        save(universal_id, 'subscribed_list', subscribed_list)

    operation = {
        '+': lambda x: subscribed_list.setdefault(x, False),
        '-': lambda x: subscribed_list.pop(x),
    }

    arg = str(event.message).strip()
    try:
        operator = arg[0]
        if operator == 'o':
            await bot.send(event=event,
                           message='当前订阅用户B站UID名单: %s' %
                           ', '.join(subscribed_list.keys()))
            return
        operand = str(int(arg[1:].strip()))
        operation[operator](operand)  # add or remove the word
        save(universal_id, 'subscribed_list', subscribed_list)
        await bot.send(event=event, message='订阅用户信息更新成功~')
    except Exception:
        logger.error(traceback.format_exc())
        await bot.send(event=event, message='订阅用户信息更新失败,请检查日志文件~')
Exemplo n.º 3
0
async def update_group_members(bot: Bot, group_id: str):
    """Update group members' information and store it to the database."""
    logger.info('Updating group [%s] members ...' % group_id)
    universal_id = str(bot.self_id) + str(group_id)

    # load the original information from the database
    members = load(universal_id, 'members')
    if not members:
        members = {}

    group_members_list = await bot.get_group_member_list(group_id=group_id)
    for member in group_members_list:
        group_member_info = await bot.get_group_member_info(
            group_id=group_id, user_id=member['user_id'], no_cache=True)

        user_id = str(group_member_info['user_id'])

        if user_id not in members:  # update the user information from the remote server
            members[user_id] = {}
        members[user_id]['id'] = group_member_info['title']
        members[user_id]['nickname'] = group_member_info['nickname']
        members[user_id]['card'] = group_member_info['card']

    for user_id in members:  # generate locally stored information
        members[user_id].setdefault('42score', 0)
        members[user_id].setdefault('42score_daily', 0)

    # save the updated information to the database
    save(universal_id, 'members', members)
Exemplo n.º 4
0
def _validate_id(universal_id: str, uid: str, gap: int) -> int:
    """Add id into colding list."""
    current = load(universal_id, 'id_colding_list')
    if not current:
        current = {}

    current_time = int(time.time())
    if uid not in current or current_time - current[uid] >= gap:
        current[uid] = current_time
        save(universal_id, 'id_colding_list', current)
        return 0
    else:
        return gap - current_time + current[uid]
Exemplo n.º 5
0
async def update_repeater_param(bot: Bot, event: Event, state: dict):
    """Set the parameters of the repeater."""
    universal_id = str(event.self_id) + str(event.group_id)
    try:
        args = map(int, str(event.message).split())
        mutate_prob = min(max(next(args), 0), 100)
        cut_in_prob = min(max(next(args), 0), 100)
        save(universal_id, 'mutate_probability', mutate_prob)
        save(universal_id, 'cut_in_probability', cut_in_prob)
        message = '复读参数设定成功,当前变形概率为%d%%,打断概率为%d%%' % (mutate_prob, cut_in_prob)
        await bot.send(event=event, message=message)
    except Exception:
        await bot.send(event=event, message='复读参数设定失败,请重试')
Exemplo n.º 6
0
def _save_daily_star(uid: str):
    """Save the daily star into database."""
    today = time.strftime('%Y-%m-%d', time.localtime())

    star_db = load('0', 'dailystar')
    if not star_db:
        star_db = {}

    star_db.setdefault(uid, [])

    if today not in star_db[uid]:
        star_db[uid].append(today)

    save('0', 'dailystar', star_db)
Exemplo n.º 7
0
def get_repeated_message(universal_id: str) -> str:
    """Get repeated message and add some variations on it."""
    msg_base = load(universal_id, 'current_msg_base')
    left_increment = load(universal_id, 'current_left_increment')
    right_increment = load(universal_id, 'current_right_increment')
    combo = load(universal_id, 'current_combo')

    mutate_prob = load(universal_id, 'mutate_probability')
    if not mutate_prob:
        mutate_prob = 5
        save(universal_id, 'mutate_probability', mutate_prob)

    cut_in_prob = load(universal_id, 'cut_in_probability')
    if not cut_in_prob:
        cut_in_prob = 5
        save(universal_id, 'cut_in_probability', cut_in_prob)

    if random.randint(1, 100) <= cut_in_prob:
        # reset the combo counter here
        save(universal_id, 'current_combo', 0)
        return exclaim_msg('打断' * (msg_base[0:2] == '打断'), '4', True, 1)

    final = combo * left_increment + msg_base + combo * right_increment
    can_mutate = random.randint(1, 100) <= mutate_prob

    # add combo for self repetition if the message is not mutated
    save(universal_id, 'current_combo', (combo + 1) * (not can_mutate))
    return mutate_msg(final, mutate=can_mutate)
Exemplo n.º 8
0
async def repeat(bot: Bot, event: Event, state: dict):
    """Handle the repeat command."""
    message = str(slim_msg(event.message)).strip()
    universal_id = str(event.self_id) + str(event.group_id)

    # get current combo for repetition
    combo = load(universal_id, 'current_combo')
    if not combo:
        combo = 0  # initialization for current combo

    if check_block_wordlist(universal_id, message):
        return

    combo = update_combo(universal_id, message, combo)
    save(universal_id, 'current_combo', combo)

    if combo == 5:
        repeated_message = get_repeated_message(universal_id)
        await bot.send(event=event, message=repeated_message)
Exemplo n.º 9
0
async def update_block_word(bot: Bot, event: Event, state: dict):
    """Handle the blockword command."""
    universal_id = str(event.self_id) + str(event.group_id)
    wordlist = load(universal_id, 'block_wordlist')
    wordlist = set(wordlist) if wordlist else set()
    operation = {
        '+': lambda x: wordlist.add(x),
        '-': lambda x: wordlist.remove(x),
    }

    arg = str(event.message).strip()
    operator = arg[0]
    operand = arg[1:].strip()
    try:
        operation[operator](operand)  # add or remove the word
        save(universal_id, 'block_wordlist', list(wordlist))
        await bot.send(event=event, message='复读屏蔽词更新成功~')
    except Exception:
        logger.error(traceback.format_exc())
        await bot.send(event=event, message='复读屏蔽词更新失败,请检查日志文件~')
Exemplo n.º 10
0
async def push_live_message(bot: Bot, universal_id: str):
    """Push the live message."""
    group_id = int(universal_id[len(str(bot.self_id)):])
    subscribed_list = _initialize_subscribed_list(universal_id,
                                                  'subscribed_list')
    global_subscribed_list = _initialize_subscribed_list(
        '0', 'global_subscribed_list')

    uids = tuple(subscribed_list.keys())
    if not uids:
        return

    uid = uids[0]  # get the first item in the subscribed list

    if uid in global_subscribed_list:
        status = global_subscribed_list[uid][
            'status']  # fetch the status from the global list
    else:
        status = await get_user_info(uid)  # fetch the status first
        global_subscribed_list[uid] = {}
        global_subscribed_list[uid][
            'status'] = status  # assign the status to the global list

    # refresh the active counter
    global_subscribed_list[uid]['active'] = 5

    status = await get_user_info(uid)
    if status['live_status'] and not subscribed_list[uid]:
        url_msg = '订阅用户%s开播了~\n' % status['name']
        share_msg = '[CQ:share,url=%s,title=订阅用户%s开播了~,content=%s]' % (
            status['live_room_url'], status['name'], status['live_title'])
        message = url_msg + share_msg
        # post the subscribe message
        await bot.send_group_msg(group_id=group_id, message=message)

    subscribed_list.pop(uid)  # pop the first item in the subscribed list
    subscribed_list[uid] = status[
        'live_status']  # update the live status and move the item to the end
    save(universal_id, 'subscribed_list', subscribed_list)
    save('0', 'global_subscribed_list', global_subscribed_list)
Exemplo n.º 11
0
async def show_poke_greet(bot: Bot, event: Event, state: dict):
    """Greet the person when the bot is poked, and repeat the poke action."""
    if event.target_id == event.self_id and event.sender_id != event.self_id:  # ensure poking target
        await show_greet(bot, event, state)

    universal_id = str(event.self_id) + str(event.group_id)
    poke_combo = load(universal_id, 'current_poke_combo')
    if not poke_combo:
        poke_combo = 0  # initialization for current poke combo

    poke_target = load(universal_id, 'current_poke_target')
    if not poke_target:
        poke_target = -1

    poke_combo = poke_combo + 1 - poke_combo * (poke_target != event.target_id)

    if poke_combo == 5:
        poke_combo += 1
        await bot.send(event=event,
                       message=slim_msg('[CQ:poke,qq=%d]' % poke_target))

    save(universal_id, 'current_poke_combo', poke_combo)
    save(universal_id, 'current_poke_target', event.target_id)
Exemplo n.º 12
0
async def update_live_info():
    """Update the live info of bilipush every 20 seconds."""
    # the global subscribed list, contains full information
    global_subscribed_list = _initialize_subscribed_list(
        '0', 'global_subscribed_list')

    uid = None
    for uid in tuple(global_subscribed_list.keys()):
        if global_subscribed_list[uid]['active'] <= 0:  # inactive check
            global_subscribed_list.pop(uid)  # pop the uid if it's not active
            uid = None
            continue
        break

    if not uid:
        return  # if no uid is left after the active check, or the subscribed list doesn't contain any uid.

    info = global_subscribed_list.pop(
        uid)  # pop the first item in the subscribed list
    global_subscribed_list[uid] = info
    global_subscribed_list[uid]['active'] -= 1  # decrease the active counter
    global_subscribed_list[uid]['status'] = await get_user_info(
        uid)  # update the status
    save('0', 'global_subscribed_list', global_subscribed_list)
Exemplo n.º 13
0
async def scheduled_level_fetch():
    """Scheduled level information fetch at 00:10:00(weekly)."""
    level_list_data = await get_level_list()
    save('0', 'level_history', level_list_data)
Exemplo n.º 14
0
def update_combo(universal_id: str, message: str, combo: int) -> bool:
    """Update the current combo according to the message."""
    msg_base = load(universal_id, 'current_msg_base')
    left_increment = load(universal_id, 'current_left_increment')
    right_increment = load(universal_id, 'current_right_increment')

    if not msg_base:
        msg_base = message

    if combo <= 1:
        place = message.find(msg_base)
        left_increment = message[:place]
        right_increment = message[place + len(msg_base):]

    msg_append = combo * left_increment + msg_base + combo * right_increment
    if message == msg_append:
        save(universal_id, 'current_msg_base', msg_base)
        save(universal_id, 'current_left_increment', left_increment)
        save(universal_id, 'current_right_increment', right_increment)
        return combo + 1
    else:
        save(universal_id, 'current_msg_base', message)
        save(universal_id, 'current_left_increment', '')
        save(universal_id, 'current_right_increment', '')
        return 1
Exemplo n.º 15
0
 def _commit_to_database(self):
     """Commit the changed data to the database."""
     save(self.universal_id, 'members', self.members)