Example #1
0
def download_icon(num, types):
    url = f'https://redive.estertion.win/icon/{types}/{num}.webp'
    save_path = R.img(f'priconne/{types}/icon_{types}_{num}.png').path
    logger.info(f'Downloading {types} icon from {url}')
    try:
        rsp = requests.get(url, stream=True, timeout=5)
    except Exception as e:
        logger.error(f'Failed to download {url}. {type(e)}')
        logger.exception(e)
    if 200 == rsp.status_code:
        img = Image.open(BytesIO(rsp.content))
        img.save(save_path)
        logger.info(f'Saved to {save_path}')
    else:
        logger.error(f'Failed to download {url}. HTTP {rsp.status_code}')
Example #2
0
async def ban_word(session):
    ctx = session.ctx
    user_id = ctx['user_id']
    msg_from = str(user_id)
    if ctx['message_type'] == 'group':
        msg_from += f'@[群:{ctx["group_id"]}]'
    elif ctx['message_type'] == 'discuss':
        msg_from += f'@[讨论组:{ctx["discuss_id"]}]'
    logger.critical(
        f'Self: {ctx["self_id"]}, Message {ctx["message_id"]} from {msg_from}: {ctx["message"]}'
    )
    # await session.send(random.choice(BANNED_WORD))
    Service.set_block_user(user_id, timedelta(hours=8))
    pic = R.img(f"chieri{random.randint(1, 4)}.jpg").cqcode
    await session.send(f"バーカー", at_sender=True)
Example #3
0
async def process(bot, event):
	user_id = event['user_id']
	msg_from = str(user_id)
	if event['message_type'] == 'group':
		group_id=event["group_id"]
	elif event['message_type'] == 'discuss':
		group_id=event["discuss_id"]
	else:
		group_id = None

	if (group_id is not None and priv.check_block_group(group_id)) or priv.check_block_user(user_id):
		return

	hoshino.priv.set_block_user(user_id, timedelta(hours=1))
	pic = R.img(f"angry.jpg").cqcode
	await bot.send(event,f"不理你啦!バーカー\n{pic}", at_sender=True)
Example #4
0
async def answer(bot, context):
    ans = answers.get(context['raw_message'])
    if ans:
        a = ans.get(union(context['group_id'], context['user_id']))
        if a:
            if 'granbluefantasy.jp' in a:
                await bot.send(context,
                               '骑空士还挺会玩儿?爬!\n' + R.img('qksimg.jpg').cqcode,
                               at_sender=True)
                return
            await bot.send(context, f'{a}', at_sender=False)
            return
        b = ans.get(union(context['group_id'], 1))
        if b:
            await bot.send(context, f'{b}', at_sender=False)
            return
Example #5
0
async def comic(bot, ev: CQEvent):
    episode = ev.message.extract_plain_text()
    if not re.fullmatch(r'\d{0,3}', episode):
        return
    episode = episode.lstrip('0')
    if not episode:
        await bot.send(ev, '请输入漫画集数 如:官漫132', at_sender=True)
        return
    index = load_index()
    if episode not in index:
        await bot.send(ev, f'未查找到第{episode}话,敬请期待官方更新', at_sender=True)
        return
    title = index[episode]['title']
    pic = R.img('priconne/comic/', get_pic_name(episode)).cqcode
    msg = f'プリンセスコネクト!Re:Dive公式4コマ\n第{episode}話 {title}\n{pic}'
    await bot.send(ev, msg, at_sender=True)
Example #6
0
async def net_ease_cloud_word(bot,ev:CQEvent):
    uid = ev.user_id
    if not _lmt.check(uid):
        await bot.finish(ev, '你今天吃的已经够多的了!', at_sender=True)
    match = ev['match']
    time = match.group(1).strip()
    food = random.choice(os.listdir(imgpath))
    name = food.split('.')
    to_eat = f'{time}去吃{name[0]}吧~\n'
    try:
        foodimg = R.img(f'foods/{food}').cqcode
        to_eat += str(foodimg)
    except Exception as e:
        hoshino.logger.error(f'读取食物图片时发生错误{type(e)}')
    await bot.send(ev, to_eat, at_sender=True)
    _lmt.increase(uid)
Example #7
0
async def del_deffend(session: CommandSession):
    ev = session.event
    uid = ev.user_id
    bot = hoshino.get_bot()
    if uid not in bot.config.SUPERUSERS:
        return
    defen = ev.message.extract_plain_text()
    defen = re.sub(r'[??,,_]', '', defen)
    defen, unknown = chara.roster.parse_team(defen)

    if unknown:
        _, name, score = chara.guess_id(unknown)
        if score < 70 and not defen:
            return  # 忽略无关对话
        msg = f'无法识别"{unknown}"' if score < 70 else f'无法识别"{unknown}" 您说的有{score}%可能是{name}'
        await session.finish(msg)
    if not defen:
        return
    if len(defen) > 5:
        await session.finish('编队不能多于5名角色')
    if len(defen) < 5:
        await session.finish('编队不能少于5名角色')
    if len(defen) != len(set(defen)):
        await session.finish('编队中含重复角色')
    if any(chara.is_npc(i) for i in defen):
        await session.finish('编队中含未实装角色')
    if 1004 in defen:
        await session.send('\n⚠️您正在查询普通版炸弹人\n※万圣版可用万圣炸弹人/瓜炸等别称')

    # 预处理缓存图片
    defen_list = defen.copy()
    defen_list.sort()
    filename = '-'.join(str(v) for v in defen_list)
    filename = f'{filename}.jpg'
    save_path = R.img('tmp/', filename).path
    if os.path.exists(save_path):
        os.remove(save_path)

    attack = ",".join(str(v) for v in defen_list)
    # zuoye = jijian.get_attack(attack)
    # if zuoye is None:
    #     await bot.send(ev, '作业不存在')
    # else:
    #     jijian.del_attack(attack)
    #     await bot.send(ev, '删除作业完了')
    jijian.del_attack(attack)
    await session.send('删除作业完了')
Example #8
0
async def check_online_data():
    global startup_job
    if startup_job:
        startup_job.remove()
        startup_job = None

    res = R.img(f'priconne/quick/pcr-rank_data')
    if not os.path.exists(res.path):
        repo = await run_sync_func(
            Repo.clone_from, 'https://github.com/pcrbot/pcr-rank_data.git',
            res.path)
    else:
        repo = Repo(res.path)
    if repo:
        await run_sync_func(repo.remote().pull)
    else:
        print('check_online_data failed')
Example #9
0
async def ban_word(session):
    ctx = session.ctx
    user_id = ctx['user_id']
    if hoshino.priv.check_block_user(user_id):
        return
    msg_from = str(user_id)
    if ctx['message_type'] == 'group':
        msg_from += f'@[群:{ctx["group_id"]}]'
    elif ctx['message_type'] == 'discuss':
        msg_from += f'@[讨论组:{ctx["discuss_id"]}]'
    hoshino.logger.critical(
        f'Self: {ctx["self_id"]}, Message {ctx["message_id"]} from {msg_from}: {ctx["message"]}'
    )
    hoshino.priv.set_block_user(user_id, timedelta(hours=8))
    pic = R.img(f"chieri{random.randint(1, 4)}.jpg").cqcode
    await session.send(f"不理你啦!バーカー\n{pic}", at_sender=True)
    await util.silence(session.ctx, 8 * 60 * 60)
Example #10
0
async def cardguess(bot, ev: CQEvent):

    if ev['message_type'] != 'group':
        await bot.send(ev, '小游戏仅支持群组游玩,好孩子要学会和伙伴一起玩哦~')
        return

    try:
        gid = str(ev.group_id)
        if _group_game[gid]:
            await bot.send(ev, '游戏进行中,好孩子要学会耐心等候哦~')
            return
        _group_game[gid] = 'cardguess'
        card = random.choice(os.listdir(cardpath))
        card_id = int(re.compile(r'^card_(\d{4}).*').match(card).group(1))
        c = chara.fromid(card_id)
        _group_parameter[gid] = card_id

        img = Image.open(os.path.join(cardpath, card))
        h = img.height
        w = img.width
        box = random.choice([(0, 0, 200, 200), (w - 200, 0, w, 200),
                             (0, h - 200, 200, h), (w - 200, h - 200, w, h)])
        res = img.crop(box)
        res = pic2b64(res)
        res = MessageSegment.image(res)

        await bot.send(ev, f'猜猜这张卡面来自哪位角色? ({ONE_TURN_TIME}s后公布答案)\n{res}')
        glmt.start_cd(gid)
        await asyncio.sleep(ONE_TURN_TIME)
        imgcard = R.img(f'priconne/card/{card}').cqcode
        msg = [f'锵锵,正确答案是: \n{imgcard}{c.name}']
        if not _group_winner[gid]:
            msg.append('很遗憾,没有人答对呢~')
            await bot.send(ev, '\n'.join(msg))
        else:
            _group_winner[gid] = list(set(_group_winner[gid]))
            msg.append(f'ヤバイですね!一共有{len(_group_winner[gid])}人答对,他们是:')
            for n in _group_winner[gid]:
                msg.append(str(n))
            await bot.send(ev, '\n'.join(msg))
    except Exception as e:
        logger.error(f'{e}')
        await bot.send(ev, '佩可似乎出错了o(╥﹏╥)o,快联系主人来看看吧~')
    del _group_game[gid]
    del _group_winner[gid]
Example #11
0
async def clock(bot, ev):
    #仅开放七曜群和塞姆利亚群
    if ev.group_id == 1058019377 or ev.group_id == 602138153:
        if not clock_limit.check(ev.group_id):
            return
        clock_limit.increase(ev.group_id)
        text = datetime.now().strftime('%H:%M')
        imgFont = ImageFont.truetype(font=fontPath, size=90)
        textSize = imgFont.getsize(text=text)
        img = R.img(f'clock/{random.randint(1, 5)}.JPG').open()

        draw = ImageDraw.Draw(img)
        xy = (332 - textSize[0] / 2, 310 - textSize[1] / 2)
        draw.text(xy=xy, text=text, font=imgFont, fill='black')

        res = pic2b64(img)
        res = MessageSegment.image(res)
        await bot.send(ev, res)
Example #12
0
def download_chara_icon(id_, star):
    url = f'https://redive.estertion.win/icon/unit/{id_}{star}1.webp'
    save_path = R.img(f'priconne/unit/icon_unit_{id_}{star}1.png').path
    logger.info(f'Downloading chara icon from {url}')
    try:
        rsp = requests.get(url, stream=True, timeout=10)
    except Exception as e:
        logger.error(f'Failed to download {url}. {type(e)}')
        #logger.exception(e)
        return False
    if 200 == rsp.status_code:
        img = Image.open(BytesIO(rsp.content))
        img.save(save_path)
        logger.info(f'Saved to {save_path}')
        return True
    else:
        logger.error(f'Failed to download {url}. HTTP {rsp.status_code}')
        return False
Example #13
0
async def whois_dragon_king(bot, ev):
    gid = ev.group_id
    self_info = await util.self_member_info(bot, ev, gid)
    sid = self_info['user_id']
    honor_type = 'talkative'
    ta_info = await util.honor_info(bot, ev, gid, honor_type)
    if 'current_talkative' not in ta_info:
        await bot.send(ev, '本群没有开启龙王标志哦~')
        return
    dk = ta_info['current_talkative']['user_id']
    if sid == dk:
        pic = R.img('dk_is_me.jpg').cqcode
        await bot.send(ev, f'啊,我是龙王\n{pic}')
    else:
        action = random.choice(['龙王出来挨透', '龙王出来喷水'])
        dk_avater = ta_info['current_talkative']['avatar'] + '640' + f'&t={dk}'
        await bot.send(
            ev, f'[CQ:at,qq={dk}]\n{action}\n[CQ:image,file={dk_avater}]')
Example #14
0
async def rank_sheet(bot, ev):
    match = ev['match']
    if not match.group(2):
        server = None
    elif match.group(2) in '国陆b':
        server = 'xtt'
    elif match.group(2) == 'x':
        server = 'xbg'
    elif match.group(2) == 'f':
        server = 'ffby'
    elif match.group(2) in '日':
        server = 'sl'
    elif match.group(2) in '台':
        server = 'wy'
    elif match.group(2) == 'y':
        server = 'ymnt'
    else:
        server = None

    if not server:
        await bot.send(ev,
                       '\n请问您要查询哪个服务器的rank表?\n*日rank表\n*台rank表\n*陆rank表',
                       at_sender=True)
        return

    msg = [
        '\n※表格仅供参考,升r有风险,强化需谨慎\n※一切以会长要求为准——',
    ]

    flist = get_rank_pic(server)

    if len(flist) == 0:
        await bot.send(ev, '无数据', at_sender=True)
        return

    args = re.split(r'\.|-|_', flist[0])
    msg.append(f'{args[0]}-{args[1]} rank表:')

    for fn in flist:
        p = R.img('priconne/quick/pcr-rank_data' + route[server] + fn).cqcode
        print(p)
        msg.append(f'{p}')
    await bot.send(ev, '\n'.join(msg), at_sender=True)
    await util.silence(ev, 60)
Example #15
0
async def bilibili(bot, ev):

    message = ev.message.extract_plain_text()
    my_spider = spider()
    bvid = 'BV' + message
    try:
        title, avid, image_url, owner, url, data = my_spider.get_info(bvid)
        my_spider.get_image()
        data = data['data']
        pic = R.img('bili/video_info.jpg').cqcode
        out_message1 = "标题:{0}\nAV号:{1}\nBV号:{2}\nup主:{3}\n".format(
            title, avid, bvid, owner)
        out_message2 = "播放量:{0}\n点赞数:{1}\n投币数:{2}\n收藏:{3}\n".format(
            data["view"], data["like"], data["coin"], data["favorite"])
        out_message3 = "链接:{0}".format(url)
        await bot.send(ev,
                       out_message1 + f'{pic}' + out_message2 + out_message3)
    except error.HTTPError:
        await bot.send(ev, '解析失败')
Example #16
0
async def get_setu_online():
    image = await query_setu()
    #检查本地是否存在该图片
    path = f'setu_mix/acggov/{image["id"]}.jpg'
    res = R.img(path)
    if os.path.exists(res.path):
        image['data'] = res.path
        image['native'] = True
    else:
        image['data'] = await download_acggov_image(image['url'])
        image['native'] = False
        if not image['data']:
            image['id'] = 0
            image['title'] = '图片下载失败'
            return image
        if get_config('acggov', 'mode') == 2:
            save_image(image)
            image['data'] = res.path
    return image
Example #17
0
 def icon(self):
     star = '3' if 1 <= self.star <= 5 else '6'
     res = R.img(f'priconne/blhx/icon_unit_{self.id}{star}1.png')
     if not res.exist:
         res = R.img(f'priconne/blhx/icon_unit_{self.id}31.png')
     if not res.exist:
         res = R.img(f'priconne/blhx/icon_unit_{self.id}11.png')
     if not res.exist:
         res = R.img(f'priconne/blhx/icon_unit_{self.id}31.png')
     if not res.exist:
         res = R.img(f'priconne/blhx/icon_unit_{self.id}11.png')
     if not res.exist:
         res = R.img(f'priconne/blhx/icon_unit_{UNKNOWN}31.png')
     return res
Example #18
0
async def update_seeker():
    '''
    轮询官方四格漫画更新
    若有更新则推送至订阅群
    '''
    index_api = 'https://comic.priconne-redive.jp/api/index'
    index = load_index()

    # 获取最新漫画信息
    resp = await aiorequests.get(index_api, timeout=10)
    data = await resp.json()
    id_ = data['latest_cartoon']['id']
    episode = data['latest_cartoon']['episode_num']
    title = data['latest_cartoon']['title']

    # 检查是否已在目录中
    # 同一episode可能会被更新为另一张图片(官方修正),此时episode不变而id改变
    # 所以需要两步判断
    if episode in index:
        qs = urlparse(index[episode]['link']).query
        old_id = parse_qs(qs)['id'][0]
        if id_ == old_id:
            sv.logger.info('未检测到官漫更新')
            return

    # 确定已有更新,下载图片
    sv.logger.info(f'发现更新 id={id_}')
    await download_comic(id_)

    # 推送至各个订阅群
    pic = R.img('priconne/comic', get_pic_name(episode)).cqcode
    msg = f'プリンセスコネクト!Re:Dive公式4コマ更新!\n第{episode}話 {title}\n{pic}'
    await sv.broadcast(msg, 'PCR官方四格', 0.5)


# @sv.scheduled_job('cron', hour = '18', minute='05')
# async def pixivPictyreGet():
#     today=datetime.date.today()
#     oneday=datetime.timedelta(days=1)
#     yesterday=today-oneday
#     msg = f'pixiv搜图:type=rank mode=day_male page=1 date={yesterday}'
#     await sv.broadcast(msg, '', 0.5)
Example #19
0
def get_rank_pic(server='xbg'):
    path = f'priconne/quick/pcr-rank_data'
    res = R.img(path + route[server])
    if not os.path.exists(res.path):
        return None
    fnlist = os.listdir(res.path)
    rank_list = []
    maxn = 0
    for fn in fnlist:
        args = re.split(r'\.|-|_', fn)
        if len(args) < 4 or not args[0].isdigit() or not args[1].isdigit():
            continue
        n = int(args[0]) * 10 + int(args[1])
        if n > maxn:
            maxn = n
            rank_list = [fn]
        elif n == maxn:
            rank_list.append(fn)
    rank_list.sort()
    return rank_list
Example #20
0
 def icon(self):
     star = '3' if 1 <= self.star <= 5 else '6'
     res = R.img(f'priconne/unit/icon_unit_{self.id}{star}1.png')
     if not res.exist:
         res = R.img(f'priconne/unit/icon_unit_{self.id}31.png')
     if not res.exist:
         res = R.img(f'priconne/unit/icon_unit_{self.id}11.png')
     if not res.exist:  # FIXME: 不方便改成异步请求
         download_chara_icon(self.id, 6)
         download_chara_icon(self.id, 3)
         download_chara_icon(self.id, 1)
         res = R.img(f'priconne/unit/icon_unit_{self.id}{star}1.png')
     if not res.exist:
         res = R.img(f'priconne/unit/icon_unit_{self.id}31.png')
     if not res.exist:
         res = R.img(f'priconne/unit/icon_unit_{self.id}11.png')
     if not res.exist:
         res = R.img(f'priconne/unit/icon_unit_{UNKNOWN}31.png')
     return res
Example #21
0
async def finder(bot, ev: CQEvent):
    m = ev.message[0]
    m = m.data['text']
    m = m.replace("色图",'')
    m = m.replace('涩图','')
    m = m.replace('瑟图','')
    filepath = setu_folder+'/pixiv/temp/'
    mkdir(filepath)
    spider = pixiv_finder()
    pic_list = spider.get_id(m)
    pid_list = list(pic_list.keys())
    if(len(pid_list)==0):
        await bot.send(ev,'无法找到{0}的涩图,爪巴'.format(m), at_sender=True)
    else:
        pid = random.choice(pid_list)
        title = pic_list[pid]
        image_name = spider.get_image(m,pid)
        score = setu_score(image_name, 'model/setu-resnet-0825.pt',3)
        pic = R.img(image_name).cqcode
        string = "标题:{0}\npid:{1}\n涩图指数{2}".format(title,pid,score[0][0])
        await bot.send(ev,string+f'{pic}', at_sender=True)
Example #22
0
async def on_input_chara_name(bot, ev: CQEvent):
    try:
        if winner_judger.get_on_off_status(ev.group_id):
            for m in ev.message:
                if m.type == 'at' and m.data['qq'] != 'all':
                    atuid = int(m.data['qq'])
                    info = await bot.get_group_member_info(self_id=ev.self_id, group_id=ev.group_id, user_id=atuid)
                    card =  info['card']
                    nickname =  info['nickname']
                    s = card
                    if card == '' :
                        s = nickname
                    #await bot.send(ev, f'at解析为{s}')
                    break
                else:
                    s = ev.message.extract_plain_text()
                    break
            cid = winner_judger.get_correct_chara_id(ev.group_id)
            info = await bot.get_group_member_info(self_id=ev.self_id, group_id=ev.group_id, user_id=cid)
            card =  info['card']
            nickname =  info['nickname']
            #await bot.send(ev, f'匹配对象{s},匹配目标{card}、{nickname}')
            if (s == card or s == nickname) and winner_judger.get_winner(ev.group_id) == '':
                winner_judger.record_winner(ev.group_id, ev.user_id)
                winnerinfo = await bot.get_group_member_info(self_id=ev.self_id, group_id=ev.group_id, user_id=ev.user_id)
                winnercard =  winnerinfo['card']
                if winnercard ==  '':
                    winnercard =  winnerinfo['nickname']
                msg_part = f'{winnercard}猜对了,真厉害!\n(此轮游戏将在时间到后自动结束,请耐心等待)'

                dir_path = os.path.join(os.path.expanduser(hoshino.config.RES_DIR), 'img', 'memavatar')
                ava_path = os.path.join(dir_path, f'{ev.group_id}_memavatar.png')
                avaimg = R.img(f'{os.path.abspath(ava_path)}')
                avaimage = MessageSegment.image(f'file:///{os.path.abspath(ava_path)}')
                if card ==  '':
                    card =  nickname
                msg = f'正确答案是: {card}{avaimage}\n{msg_part}'
                await bot.send(ev, msg)
    except Exception as e:
        await bot.send(ev, '错误:\n' + str(e))
Example #23
0
 def card(self):
     star = '3' if 1 <= self.star <= 5 else '6'
     res = R.img(f'priconne/card/card_full_{self.id}{star}1.png')
     if not res.exist:
         res = R.img(f'priconne/card/card_full_{self.id}31.png')
     if not res.exist:   # FIXME: 不方便改成异步请求
         download_card_full(self.id, 6)
         download_card_full(self.id, 3)
         res = R.img(f'priconne/card/card_full_{self.id}{star}1.png')
     if not res.exist:
         res = R.img(f'priconne/card/card_full_{self.id}31.png')
     if not res.exist:
         res = R.img(f'priconne/card/card_full_{self.id}61.png')
     if not res.exist:
         res = R.img(f'priconne/card/card_full_{UNKNOWN}31.png')
     return res
Example #24
0
async def get_picture(bot, ev):
    date = datetime.datetime.now()
    delta = datetime.timedelta(days=2)
    date = date - delta
    path = '/lustre/qq_bot/res/img/pixiv/%02d%02d' % (date.month, date.day)
    is_dir = check_dir(path)
    if (is_dir):
        file_n, title, pid = get_pixiv_picture(path)
        file_p = path + '/' + file_n + '.png'
        if (check_dir(file_p)):
            file_n = 'pixiv/%02d%02d' % (date.month,
                                         date.day) + '/' + file_n + '.png'
        else:
            file_n = 'pixiv/%02d%02d' % (date.month,
                                         date.day) + '/' + file_n + '.jpg'
        pic = R.img(file_n).cqcode
        score = setu_score('../res/img/' + file_n, 'model/setu-resnet-0825.pt',
                           3)
        r_message = 'title: {0}, pixiv id:{1},涩图指数:{2}'.format(
            title, pid, score)
        await bot.send(ev, r_message + f'{pic}')
    else:
        await bot.send(ev, '尚未获得今日图片,请使用“爬取今日图片”命令获取')
Example #25
0
def get_rank_pic(server='cn'):
    path = f'priconne/quick'
    res = R.img(path)
    if not os.path.exists(res.path):
        return None
    fnlist = os.listdir(res.path)
    rank_list = []
    maxn = 0
    for fn in fnlist:
        if fn[0] != 'r' and fn[0] != 'R':
            continue
        args = re.split(r'\.|-', fn[1:])
        if len(args) < 4 or args[2] != server or not args[0].isdigit(
        ) or not args[1].isdigit():
            continue
        n = int(args[0]) * 10 + int(args[1])
        if n > maxn:
            maxn = n
            rank_list = [fn]
        elif n == maxn:
            rank_list.append(fn)
    rank_list.sort()
    return rank_list
Example #26
0
async def actual_guess(bot, ev: CQEvent):
    if gm.is_playing(ev.group_id):
        await bot.finish(ev, "游戏仍在进行中…")
    if not os.path.exists(DIR_PATH) or len(
            os.listdir(DIR_PATH)) < DOWNLOAD_THRESHOLD:
        await download_actual_photo(bot, ev)
        return
    # with gm.start_game(ev.group_id) as game:
    game = gm.start_game(ev.group_id)
    file_list = os.listdir(DIR_PATH)
    chosen_chara = random.choice(file_list)
    await bot.send(ev, f'猜猜这张图片是哪个角色? ({ONE_TURN_TIME}s后公布答案)')
    await bot.send(ev, R.img(f'priconne/unit/actual/{chosen_chara}').cqcode)
    game.answer = int(chosen_chara[0:4])
    game.set_schedule(
        scheduler.add_job(check,
                          'date',
                          args=(
                              bot,
                              ev,
                          ),
                          next_run_time=datetime.datetime.now() +
                          datetime.timedelta(seconds=ONE_TURN_TIME)))
Example #27
0
def load_native_info(sub_dir):
    info = {}
    path = f'setu_mix/' + sub_dir
    res = R.img(path)
    if not os.path.exists(res.path):
        return info
    fnlist = os.listdir(res.path)

    for fn in fnlist:
        s = fn.split('.')
        if len(s) != 2 or s[1] != 'json' or not s[0].isdigit():
            continue
        uid = int(s[0])
        try:
            with open(res.path + '/' + fn, encoding='utf8') as f:
                d = json.load(f)
                d['tags'].append(d['title'])
                d['tags'].append(d['author'])
                info[uid] = ','.join(d['tags'])
        except:
            pass
    print('[INFO]read', len(info), 'setu from', sub_dir)
    return info
async def net_ease_cloud_word(bot, ev: CQEvent):
    gid = ev.group_id
    if random.random() < 0.90:
        if not _lmt.check(gid):
            # 冲太多...哦不是, 抑郁太多对身体不好
            await bot.send(ev, '抑郁太多对身体不好,请等待一会儿哦', at_sender=True)
            return
        _lmt.start_cd(gid)
        try:
            sentences = pic_gender_cqcode('wcloud/success')
        except Exception as e:
            hoshino.logger.error(
                f'获取目录res/img/wcloud/success下的图片时发生错误{type(e)}, 请检查')
            sentences = ''

        nt_word = get_nt_words()
        sentences += nt_word
        await bot.send(ev, sentences)
    else:
        await bot.send(
            ev,
            R.img(f"wcloud/failed/nowc{random.randint(1, 7)}.jpg").cqcode)
        await bot.send(ev, f'上号失败,不准抑郁')
Example #29
0
async def voiceguess(bot, ev: CQEvent):

    if ev['message_type'] != 'group':
        await bot.send(ev, '小游戏仅支持群组游玩,好孩子要学会和伙伴一起玩哦~')
        return

    try:
        gid = str(ev.group_id)
        if _group_game[gid]:
            await bot.send(ev, '游戏进行中,好孩子要学会耐心等候哦~')
            return
        _group_game[gid] = 'voiceguess'
        voice = random.choice(os.listdir(voicepath))
        voice_id = int('1' + re.compile(
            r'^vo_title_(customize_)?(\d{4}).*').match(voice).group(2)[-3:])
        c = chara.fromid(voice_id)
        _group_parameter[gid] = voice_id

        await bot.send(ev, f'猜猜这个语音来自哪位角色? ({ONE_TURN_TIME}s后公布答案)')
        await bot.send(ev, R.record(f"title_silk/{voice}").cqcode)
        glmt.start_cd(gid)
        await asyncio.sleep(ONE_TURN_TIME)
        msg = [f'锵锵,正确答案是: \n{c.icon.cqcode}{c.name}']
        if not _group_winner[gid]:
            msg.append('很遗憾,没有人答对呢~')
            await bot.send(ev, '\n'.join(msg))
        else:
            _group_winner[gid] = list(set(_group_winner[gid]))
            msg.append(f'ヤバイですね!一共有{len(_group_winner[gid])}人答对,他们是:')
            for n in _group_winner[gid]:
                msg.append(str(n))
            await bot.send(ev, '\n'.join(msg))
    except Exception as e:
        logger.error(f'{e}')
        await bot.send(ev, '佩可似乎出错了o(╥﹏╥)o,快联系主人来看看吧~')
    del _group_game[gid]
    del _group_winner[gid]
Example #30
0
def get_setu():
    url = 'https://api.lolicon.app/setu/'
    params = {'apikey': apikey, 'r18': 0, 'num': 5, 'size1200': True}
    try:
        r = session.get(url=url, params=params, timeout=10)
    except (requests.exceptions.RequestException) as e:
        logger.error(f'[lolicon.app connect failed]{e}')
        return []

    results = r.json()
    setu_list = []
    for setu in results['data']:
        title = setu['title']
        pic_url = setu['url']
        try:
            r = session.get(url=pic_url, timeout=20)
        except (requests.exceptions.RequestException) as e:
            logger.error(f'[pixiv.cat connect failed]{e}')
            continue

        try:
            pic = Image.open(BytesIO(r.content))
            pic = pic.convert('RGB')
            title = title.replace('/', '-')
            date = datetime.datetime.now().strftime('%Y%m%d')
            setu['date'] = date
            datePath = f'/home/res/img/setu/{date}'
            if not os.path.exists(datePath):
                os.makedirs(datePath)
            pic.save(R.img(f'setu/{date}/', f'{title}.jpg').path)
        except OSError as e:
            logger.error(f'[pic save failed]{e}')
            continue

        setu_list.append(setu)
    return setu_list