Exemple #1
0
async def cough(session: CommandSession):
    session.finish('请见丁香园: https://ncov.dxy.cn/ncovh5/view/pneumonia')
    name = session.current_arg_text
    if name:  # look up province or city
        # data = nCoV2019.get_status(name)
        # if not data:
        #     return "未知省市"
        # info = '\n'.join([f"{city['cityName']} 确诊{city['confirmedCount']}例" for city in data['cities'] ])
        # text = f"新型冠状病毒肺炎疫情\n{info}\n💊 全国疫情 → t.cn/A6v1xgC0"
        # await session.send(text)
        await session.finish('省市查询维护中...')
    else:  # show overall
        if not nCoV2019.cache['overall']:
            await nCoV2019.get_overall()
        data = nCoV2019.cache['overall']
        if data:
            data['updateTimeStr'] = datetime.fromtimestamp(
                data['updateTime'] / 1000).strftime(r'%Y-%m-%d %H:%M')
            data['pic1'] = MessageSegment.image(data['dailyPics'][0])  # 新增图
            data['pic2'] = MessageSegment.image(data['dailyPics'][2])  # 累积图
            data['pic3'] = MessageSegment.image(data['dailyPics'][3])  # 治愈死亡图
            text = "新型冠状病毒肺炎疫情\n更新时间:{updateTimeStr}\n确诊{confirmedCount}例(+{confirmedIncr})\n疑似{suspectedCount}例(+{suspectedIncr})\n重症{seriousCount}例(+{seriousIncr})\n死亡{deadCount}例(+{deadIncr})\n治愈{curedCount}例(+{curedIncr})\n{pic1!s}{pic2!s}{pic3!s}\n更多请见丁香园:ncov.dxy.cn/ncovh5/view/pneumonia".format(
                **data)
            await session.send(text)
        else:
            await session.send('查询出错')
Exemple #2
0
def gacha_info(pool=DEFAULT_POOL):
    # 重载卡池数据,然后返回UP角色信息
    init_role_arms_list()  # 重新载入config.json的卡池数据
    info_txt = f'当前卡池为 {pool} ,UP信息如下:\n'

    _5_star_up_info = POOL[pool]["5星up"]
    _4_star_up_info = POOL[pool]["4星up"]
    up_info = ""

    for _5_star in ROLE_ARMS_LIST[_5_star_up_info]:
        im = Image.open(Gacha.get_png_path(_5_star))
        im = Gacha.pic2b64(im)
        up_info += str(MessageSegment.image(im))
        up_info += "\n"
        up_info += f"{_5_star} ★★★★★"

    for _4_star in ROLE_ARMS_LIST[_4_star_up_info]:
        im = Image.open(Gacha.get_png_path(_4_star))
        im = Gacha.pic2b64(im)
        up_info += str(MessageSegment.image(im))
        up_info += "\n"
        up_info += f"{_4_star} ★★★★"

    if up_info == "":
        # 如果up_info是空的,表示当前是常驻池没有UP
        up_info += "常驻池没有UP"

    info_txt += up_info
    return info_txt
Exemple #3
0
 def cqcode(self) -> MessageSegment:
     if get_bot().config.RESOURCE_URL:
         return MessageSegment.image(self.url)
     else:
         try:
             return MessageSegment.image(pic2b64(self.open()))
         except Exception as e:
             logger.exception(e)
             return MessageSegment.text('[图片]')
Exemple #4
0
 def cqcode(self) -> MessageSegment:
     if get_bot().config.RESOURCE_URL:
         return MessageSegment.image(self.url)
     else:
         try:
             return MessageSegment.image('file:///' + self.path)
         except Exception as e:
             logger.exception(e)
             return MessageSegment.text('[图片]')
Exemple #5
0
 def cqcode(self) -> MessageSegment:
     if hoshino.config.RES_PROTOCOL == 'http':
         return MessageSegment.image(self.url)
     elif hoshino.config.RES_PROTOCOL == 'file':
         return MessageSegment.image(f'file:///{os.path.abspath(self.path)}')
     else:
         try:
             return MessageSegment.image(util.pic2b64(self.open()))
         except Exception as e:
             hoshino.logger.exception(e)
             return MessageSegment.text('[图片出错]')
async def avatar_guess(bot, ev: CQEvent):
    try:
        uid = ev.user_id
        if winner_judger.get_on_off_status(ev.group_id):
            await bot.send(ev, "此轮游戏还没结束,请勿重复使用指令")
            return
        if not lmt.check(uid):
            await bot.send(ev, '您今天已经玩了10次猜群友了,休息一下,明天再来吧!', at_sender=True)
            return
        lmt.increase(uid)
        winner_judger.turn_on(ev.group_id)

        user_card_dict = await get_user_card_dict(bot, ev.group_id)
        user_id_list = list(user_card_dict.keys())
        while True:
            random.shuffle(user_id_list)
            if user_id_list[0] !=ev.self_id: break
        winner_judger.set_correct_chara_id(ev.group_id, user_id_list[0])
        dir_path = os.path.join(os.path.expanduser(hoshino.config.RES_DIR), 'img', 'memavatar')
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

        apiPath=f' http://q1.qlogo.cn/g?b=qq&nk={user_id_list[0]}&s=100'
        img = requests.get(apiPath, timeout=20).content
        ava_path = os.path.join(dir_path, f'{ev.group_id}_memavatar.png')
        with open(ava_path, 'wb') as f:
            f.write(img)

        avaimg = R.img(f'{os.path.abspath(ava_path)}').open()
        avaimage = MessageSegment.image(f'file:///{os.path.abspath(ava_path)}')
        left = math.floor(random.random() * (100 - PIC_SIDE_LENGTH))
        upper = math.floor(random.random() * (100 - PIC_SIDE_LENGTH))
        cropped = avaimg.crop((left, upper, left + PIC_SIDE_LENGTH, upper + PIC_SIDE_LENGTH))
        file_path = os.path.join(dir_path, f'{ev.group_id}_cropped_memavatar.png')
        cropped.save(file_path)
        image = MessageSegment.image(f'file:///{os.path.abspath(file_path)}')
        msg = f'猜猜这个图片是哪位群友头像的一部分?({ONE_TURN_TIME}s后公布答案){image}'
        await bot.send(ev, msg)
        await asyncio.sleep(ONE_TURN_TIME)

        if winner_judger.get_winner(ev.group_id) != '':
            winner_judger.turn_off(ev.group_id)
            return

        msg = f'正确答案是: {user_card_dict[user_id_list[0]]}{avaimage}\n很遗憾,没有人答对~'
        winner_judger.turn_off(ev.group_id)
        await bot.send(ev, msg)
    except Exception as e:
        winner_judger.turn_off(ev.group_id)
        await bot.send(ev, '错误:\n' + str(e))
Exemple #7
0
async def xcw_huhuhu(bot, ev) -> MessageSegment:
    file = get_xcw_huhuhu()
    try:
        rec = MessageSegment.image(f'file:///{os.path.abspath(file.path)}')
        await bot.send(ev, rec)
    except CQHttpError:
        sv.logger.error("发送失败")
Exemple #8
0
async def avatar_guess(bot, ev: CQEvent):
    try:
        if winner_judger.get_on_off_status():
            await bot.send(ev, "此轮游戏还没结束,请勿重复使用指令")
            return
        winner_judger.turn_on()
        chara_id_list = list(_pcr_data.CHARA_NAME.keys())
        while True:
            random.shuffle(chara_id_list)
            if chara_id_list[0] not in BLACKLIST_ID: break
        winner_judger.set_correct_chara_id(chara_id_list[0])
        dir_path = os.path.join(os.path.expanduser(hoshino.config.RES_DIR),
                                'img', 'priconne', 'unit')
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        c = chara.fromid(chara_id_list[0])
        img = c.icon.open()
        left = math.floor(random.random() * (129 - PIC_SIDE_LENGTH))
        upper = math.floor(random.random() * (129 - PIC_SIDE_LENGTH))
        cropped = img.crop(
            (left, upper, left + PIC_SIDE_LENGTH, upper + PIC_SIDE_LENGTH))
        file_path = os.path.join(dir_path, 'cropped_avatar.png')
        cropped.save(file_path)
        image = MessageSegment.image(f'file:///{os.path.abspath(file_path)}')
        msg = f'猜猜这个图片是哪位角色头像的一部分?({ONE_TURN_TIME}s后公布答案)'
        await bot.send(ev, msg + image)
        await asyncio.sleep(ONE_TURN_TIME)
        if winner_judger.winner != '':
            winner_judger.turn_off()
            return
        msg = f'正确答案是: {c.name}{c.icon.cqcode}\n很遗憾,没有人答对~'
        winner_judger.turn_off()
        await bot.send(ev, msg)
    except Exception as e:
        await bot.send(ev, '错误:\n' + str(e))
Exemple #9
0
async def longwang(session):
    global imgbase_path
    uid = session.ctx['user_id']
    if not _nlmt.check(uid):
        await session.send(EXCEED_NOTICE, at_sender=True)
        return
    if not _flmt.check(uid):
        await session.send('龙王她生气了,并堵上了你的嘴', at_sender=True)
        return
    _flmt.start_cd(uid)
    gid = session.ctx['group_id']
    dragon_king = await session.bot.get_group_honor_info(group_id=gid,
                                                         type='talkative')
    if not 'current_talkative' in dragon_king:
        await session.send('本群暂时还没有龙王哦……', at_sender=True)
        return
    dragon_king = dragon_king['current_talkative']['user_id']
    dir_list = os.listdir(imgbase_path)
    img_path = path.join(imgbase_path, random.choice(dir_list))
    count = 0
    while os.path.isdir(img_path) == True:
        img_path = path.join(imgbase_path, random.choice(dir_list))
        count += 1
        if count % 5 == 0:
            hoshino.logger.error('缺少龙王图片资源或目录下文件夹过多')
            return
    longwang_img = R.img(img_path).open()
    longwang_img_message = MessageSegment.image(pic2b64(longwang_img))
    reply = random.choice(['龙王出来挨透', '龙王出来喷水'])
    _nlmt.increase(uid)
    await session.finish(
        f'[CQ:at,qq={dragon_king}]\n{reply}\n{longwang_img_message}')
Exemple #10
0
async def _(session: CommandSession):
    account = session.state['account']

    today = dt.beijing_now().date()
    if account.last_sign_in_date and \
            today - account.last_sign_in_date < timedelta(days=1):
        session.finish('签到系统正处于删档测试阶段。你今天已经签过到啦\n明天再来吧~')

    last_sign_in_date = today
    total_sign_in = account.total_sign_in + 1
    earned = random.randint(1, 100)
    total_coins = account.total_coins + earned
    succeeded = await da.update(
        account,
        last_sign_in_date=last_sign_in_date,
        total_sign_in=total_sign_in,
        total_coins=total_coins,
    )
    if not succeeded:
        session.finish('签到失败,请稍后再试~')

    reply = str(MessageSegment.image(account.avatar_url))
    if session.ctx['message_type'] != 'private':
        reply += '\n' + str(MessageSegment.at(session.ctx['user_id']))

    reply += f'\n你已经累计签到了 {total_sign_in} 次\n' \
        f'本次签到获得了 {earned} 个金币~'
    session.finish(reply)
Exemple #11
0
async def common_multiuser_msgsender(session, uids: tuple):
    """
    通用多用户消息发送函数。
    参数:
        session
        uids: 作者uid组成的元组
    """
    msg = M()
    msglimit = 20
    msgcurrent = 0
    useb64 = False if session.self_id == SIGNAL['MainQQ'] else True
    for user in _pixiv_instance.getusers(uids, useb64):
        msgcurrent += 1
        if msgcurrent > msglimit:
            await session.send(msg)
            msgcurrent = 1
            msg.clear()
        msg.append(MS.text('-' * 20 + '\n'))
        msg.append(MS.text(f'用户名:{user["user"]["name"]}\n'))
        msg.append(MS.text(f'用户ID:{user["user"]["id"]}\n'))
        if SIGNAL['RegisteredQQ'][session.self_id][
                'coolq_edition'] == 'pro' and user['user']['profile_image']:
            msg.append(MS.text('用户头像:'))
            msg.append(MS.image(user['user']['profile_image']))
            msg.append(MS.text('\n'))
    if msg:
        await session.send(msg)
Exemple #12
0
async def tex(session: CommandSession):
    if session.is_first_run:
        stripped_text = session.current_arg_text.strip()
        if stripped_text:
            session.state['tex_code'] = stripped_text

    tex_code = session.get('tex_code',
                           prompt='请发送你想要生成图片的 TeX 公式',
                           arg_filters=[
                               extractors.extract_text,
                               str.strip,
                               validators.not_empty('公式不能为空,请重新发送~'),
                           ])

    await session.send('正在生成,请稍后……')
    resp = await requests.post(LATEX2PNG_API_URL,
                               data={
                                   'latex': tex_code,
                                   'res': '600',
                                   'color': '000000'
                               })
    if not resp.ok:
        session.finish('服务暂时不可用,请稍后再试')

    html = await resp.text
    m = re.search(r'latex_[0-9a-z]+\.png', html)
    if not m:
        session.finish('生成公式图片失败,请稍后再试')

    session.finish(
        MessageSegment.image(LATEX2PNG_IMAGE_URL_FORMAT.format(m.group(0))) +
        '\n' + ZHIHU_TEX_SVG_URL_FORMAT.format(quote_plus(tex_code)))
Exemple #13
0
async def pixiv(session: CommandSession):
    send = True
    params = {
        # "apikey":"",
        "r18": 0,
        "keyword": "",
        "size1200": True
    }
    params['keyword'] = session.current_arg_text.split()
    try:
        web = requests.get('https://api.lolicon.app/setu/',
                           params=params).json()
        if web['code'] != 0:
            await session.send(web['msg'])
        else:
            await session.send(
                f"PID:{str(web['data'][0]['pid'])}\n若图片发不出来请自行查看")
            web_image = requests.get(web['data'][0]['url'], timeout=10)
            if web_image.status_code == 200:
                with open(path + r"\Pixiv.jpg", "wb") as f:
                    f.write(web_image.content)
            await session.send(
                str(MessageSegment.image("file:///" + path + r"\Pixiv.jpg")))
    except:
        pass
    session.finish()
async def send_time_dist(bot, event):
    gid = event['group_id']
    year, month = get_ym()

    try:
        name, times = get_time(gid, year, month)
    except Exception as e:
        await bot.send(event, f"出现错误: {str(e)}\n请联系开发组调教。")
        return

    plt.rcParams['axes.unicode_minus'] = False
    prop = fm.FontProperties(fname=font_path)
    prop.set_size('large')
    fig, ax = plt.subplots(figsize=(12, 6), facecolor='white')
    ax.set_xlabel('时间', fontproperties=prop)
    ax.set_ylabel('刀数', fontproperties=prop)
    ax.set_title(f'{name}{year}年{month}月会战出刀时间统计', fontproperties=prop)
    ax.set_xlim((0 - 0.5, 24))
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    colors = (['#808080'] * 6) + (['#9bc5af'] * 6) + (['#c54731'] *
                                                      6) + (['#3a4a59'] * 6)

    labels = list(range(5, 24)) + list(range(5))
    labels = [str(s) for s in labels]
    plt.xticks(range(24), labels, fontproperties=prop)
    plt.bar(range(24), times, color=colors)

    pic = fig2b64(plt)
    plt.close()
    await bot.send(event, ms.image(pic))
async def avatar_guess(bot, ev: CQEvent):
    if winner_judger.get_on_off_status(ev.group_id):
        await bot.send(ev, "此轮游戏还没结束,请勿重复使用指令")
        return
    winner_judger.turn_on(ev.group_id)
    chara_id_list = list(_pcr_data.CHARA_NAME.keys())
    list_len = len(chara_id_list) - 1
    while True:
        index = random.randint(0, list_len)
        if chara_id_list[index] not in BLACKLIST_ID: break
    winner_judger.set_correct_chara_id(ev.group_id, chara_id_list[index])
    dir_path = os.path.join(os.path.expanduser(hoshino.config.RES_DIR), 'img', 'priconne', 'unit')
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    c = chara.fromid(chara_id_list[index])
    img = c.icon.open()
    left = math.floor(random.random()*(129-PIC_SIDE_LENGTH))
    upper = math.floor(random.random()*(129-PIC_SIDE_LENGTH))
    cropped = img.crop((left, upper, left+PIC_SIDE_LENGTH, upper+PIC_SIDE_LENGTH))
    cropped = MessageSegment.image(util.pic2b64(cropped))
    msg = f'猜猜这个图片是哪位角色头像的一部分?({ONE_TURN_TIME}s后公布答案){cropped}'
    await bot.send(ev, msg)
    await asyncio.sleep(ONE_TURN_TIME)
    if winner_judger.get_winner(ev.group_id) != '':
        winner_judger.turn_off(ev.group_id)
        return
    msg =  f'正确答案是: {c.name}{c.icon.cqcode}\n很遗憾,没有人答对~'
    winner_judger.turn_off(ev.group_id)
    await bot.send(ev, msg)
Exemple #16
0
async def send_manual_image(session: CommandSession, plugin_name: str) -> None:
    url_format = session.bot.config.MANUAL_IMAGE_URL_FORMAT
    if url_format.startswith('file:'):
        url = url_format.format(plugin_name)
    else:
        url = url_format.format(quote_plus(plugin_name))
    await session.send(MessageSegment.image(url))
Exemple #17
0
async def gacha_10(session: CommandSession):
    SUPER_LUCKY_LINE = 170
    uid = session.ctx['user_id']
    at = str(MessageSegment.at(session.ctx['user_id']))

    if not check_gacha_num(uid):
        await session.finish(f'{at} {GACHA_EXCEED_NOTICE}')
    _user_gacha_count[uid] += 1

    gacha = Gacha()
    result, hiishi = gacha.gacha_ten()
    silence_time = hiishi * 6 if hiishi < SUPER_LUCKY_LINE else hiishi * 60

    if get_bot().config.IS_CQPRO:
        res1 = Chara.gen_team_pic(result[:5], star_slot_verbose=False)
        res2 = Chara.gen_team_pic(result[5:], star_slot_verbose=False)
        res = concat_pic([res1, res2])
        res = pic2b64(res)
        res = MessageSegment.image(res)
        result = [f'{c.name}{"★"*c.star}' for c in result]
        res1 = ' '.join(result[0:5])
        res2 = ' '.join(result[5:])
        res = res + f'{res1}\n{res2}'
    else:
        result = [f'{c.name}{"★"*c.star}' for c in result]
        res1 = ' '.join(result[0:5])
        res2 = ' '.join(result[5:])
        res = f'{res1}\n{res2}'

    await silence(session.ctx, silence_time)
    msg = f'{at}\n素敵な仲間が増えますよ!\n{res}'
    await session.send(msg)
    if hiishi >= SUPER_LUCKY_LINE:
        await session.send('恭喜海豹!おめでとうございます!')
Exemple #18
0
def parseSingleImage(data: dict, mosaicR18: bool = True) -> dict:
    illustData = data["illust"]

    if illustData["page_count"] == 1:
        dwlLinks = [{
            "large":
            illustData["image_urls"]["large"],
            "medium":
            illustData["image_urls"]["medium"],
            "square_medium":
            illustData["image_urls"]["medium"],
            "original":
            illustData["meta_single_page"]["original_image_url"],
        }]
    else:
        dwlLinks = [
            perLink["image_urls"] for perLink in illustData["meta_pages"]
        ]

    hotRatio = ((illustData["total_bookmarks"] /
                 illustData["total_view"]) if illustData["total_view"] else 0)

    returnData = {
        "id": illustData["id"],
        "title": illustData["title"],
        "preview_link": dwlLinks[0]["medium"],
        "preview": str(MessageSegment.image(dwlLinks[0]["medium"])),
        "author": illustData["user"]["name"],
        "author_id": illustData["user"]["id"],
        "tags": [tag["name"] for tag in illustData["tags"]],
        "date": illustData["create_date"],
        "size": illustData["page_count"],
        "download": dwlLinks,
        "view": illustData["total_view"],
        "bookmark": illustData["total_bookmarks"],
        "ratio": hotRatio,
        "type": illustData["type"],
    }

    r18Status = _checkIsR18(returnData["tags"])
    previewDownload = str(
        MessageSegment.image(
            downloadImage(returnData["preview_link"],
                          mosaic=(mosaicR18 and r18Status))))

    returnData.update({"r-18": r18Status, "preview": previewDownload})
    return returnData
Exemple #19
0
async def stat_score(bot: NoneBot, ctx: Context_T, args: ParseResult):
    bm = BattleMaster(ctx['group_id'])
    now = datetime.now()
    clan = _check_clan(bm)
    yyyy, mm, _ = bm.get_yyyymmdd(now)
    stat = bm.stat_score(1, now)
    stat.sort(key=lambda x: x[3], reverse=True)

    if not len(stat):
        await bot.send(ctx,
                       f"{clan['name']}{yyyy}年{mm}月会战统计数据为空",
                       at_sender=True)
        return

    # msg = [ f"\n{yyyy}年{mm}月会战{clan['name']}分数统计:" ]
    # for _, _, name, score in stat:
    #     score = f'{score:,d}'           # 数字太多会被腾讯ban,用逗号分隔
    #     blank = '  ' * (11-len(score))  # QQ字体非等宽,width(空格*2) == width(数字*1)
    #     msg.append(f"{blank}{score}分 | {name}")

    # generate statistic figure
    fig, ax = plt.subplots()
    score = list(map(lambda i: i[3], stat))
    yn = len(stat)
    name = list(map(lambda i: i[2], stat))
    y_pos = list(range(yn))

    if score[0] >= 1e8:
        unit = 1e8
        unit_str = 'e'
    else:
        unit = 1e4
        unit_str = 'w'

    y_size = 0.3 * yn + 1.0
    fig.set_size_inches(10, y_size)
    bars = ax.barh(y_pos, score, align='center')
    ax.set_title(f"{clan['name']}{yyyy}年{mm}月会战分数统计")
    ax.set_yticks(y_pos)
    ax.set_yticklabels(name)
    ax.set_ylim((-0.6, yn - 0.4))
    ax.invert_yaxis()
    ax.set_xlabel('分数')
    ax.ticklabel_format(axis='x', style='plain')
    for rect in bars:
        w = rect.get_width()
        ax.text(w,
                rect.get_y() + rect.get_height() / 2,
                f'{w/unit:.2f}{unit_str}',
                ha='left',
                va='center')
    plt.subplots_adjust(left=0.12,
                        right=0.96,
                        top=1 - 0.35 / y_size,
                        bottom=0.55 / y_size)
    pic = util.fig2b64(plt)
    plt.close()

    await bot.send(ctx, ms.image(pic), at_sender=True)
Exemple #20
0
async def gomoku(session: CommandSession):

    if not __enabled__:
        logger.warning("Gomoku plugin is disabled due to the failure of loading clib. See https://233a344a455.github.io/DeltaBot/setup.html#gomoku%E6%A8%A1%E5%9D%97-%E4%BA%94%E5%AD%90%E6%A3%8B-%E5%AE%89%E8%A3%85.")
        await session.send('插件未启用!')
        return

    await session.send("游戏开始!\n"
                       "玩家黑棋,机器人白棋\n"
                       "落子格式: 例如'e9'或'E9'\n"
                       "字母在前数字在后,不分大小写")

    g = GomokuGame(clib, context_id(session.ctx, use_hash=True))
    await session.send(MessageSegment.image(g.get_img()))
    await asyncio.sleep(0.5)
    while True:
        inp = await session.aget('input', force_update=True, prompt="请玩家落子",
                                 arg_filters=[
                                     str.strip,
                                     not_empty(message="输入不能为空!请重新输入"),
                                     handle_cancellation(session),
                                     match_regex(r'[a-oA-O](1[0-5]|[1-9])', fullmatch=True,
                                                 message="无效的输入!请重新输入\n落子格式: 例如'e9'或'E9',"
                                                         "字母在前数字在后,不分大小写\n【发送'取消'结束游戏】")])
        x, y = re.match(r'([a-oA-O])(1[0-5]|[1-9])', inp).groups()
        x, y = ALPHABET.index(x.upper()), int(y) - 1
        if not g.set_chess(x, y, USER):
            await session.send(f"位置'{inp}'已存在旗子,请重新输入")
            continue

        sco = -g.estimate()
        g.update_display()
        if sco > 1e6:
            await session.send("恭喜!你赢了" + MessageSegment.image(g.get_img()))
            return

        x, y = g.search()
        g.set_chess(x, y, BOT)
        g.display.draw_chess(x, y, BOT, high_lighted=True)
        sco = -g.estimate()
        if sco < -1e6:
            await session.send("你输啦 ~\(≧▽≦)/~" + MessageSegment.image(g.get_img()))
            return

        await session.send(f"估计分数: {sco}" + MessageSegment.image(g.get_img()))
        await asyncio.sleep(0.8)
Exemple #21
0
async def find(session: CommandSession):
    img = await crawler()
    if img.startswith("http"):
        message = str(MessageSegment.image(img))
        print(message)
        await session.send(message)
    else:
        await session.send(img)
Exemple #22
0
async def setu1(bot, ev):
    r = requests.get('https://api.dihe.moe/setu/?r18=1')
    j = r.json()
    try:
        rec = MessageSegment.image(j['url'])
        await bot.send(ev, rec)
    except CQHttpError:
        sv.logger.error("发送失败")
Exemple #23
0
async def shangke(bot, ev):
    filename = 'shangke.jpg'
    file = R.get('img/xcw/image', filename)
    try:
        rec = MessageSegment.image(f'file:///{os.path.abspath(file.path)}')
        await bot.send(ev, rec)
    except CQHttpError:
        sv.logger.error("发送失败")
Exemple #24
0
async def picture(session: CommandSession):
    fileword = session.get('fileword', prompt='你想找哪个人物的图片呢?')
    picnum = random.randint(0, len(os.listdir('./' + fileword)) - 1)
    picname = os.listdir('./' + fileword)[picnum]

    picture = MessageSegment.image(f'C:\\pythonbot\\{fileword}\\{picname}')

    await session.send(picture)
Exemple #25
0
async def shigyi(bot, ev):
    if random.random() < 0.5:
        filename = '斯国一斯国一.mp3'
        file = R.get('img/xcw/record', filename)
        try:
            rec = MessageSegment.image(f'file:///{os.path.abspath(file.path)}')
            await bot.send(ev, rec)
        except CQHttpError:
            sv.logger.error("发送失败")
Exemple #26
0
async def fox(session: CommandSession):
    try:
        web_image = requests.get('https://foxrudor.de/', timeout=10)
        if web_image.status_code == 200:
            with open(path + r"\fox.jpg", "wb") as f:
                f.write(web_image.content)
    except:
        pass
    session.finish(str(MessageSegment.image("file:///" + path + r"\fox.jpg")))
Exemple #27
0
def gacha_10():
    # 抽10连

    last_time_4 = ""
    last_time_5 = ""
    gacha_txt = ""
    gacha_list = []

    last_4_up = 0
    last_5_up = 0  # 记录多少抽第一次出现UP

    distance_4_star = 0
    distance_5_star = 0

    for i in range(10):

        distance_4_star += 1
        distance_5_star += 1

        new_gacha = gacha(i + 1, last_time_4, last_time_5, distance_4_star,
                          distance_5_star)
        gacha_list.append(new_gacha)
        gacha_txt += new_gacha
        gacha_txt += is_star(new_gacha)
        if (i + 1) % 5 == 0:
            gacha_txt += '\n'

        if is_4_star(new_gacha):
            last_time_4 = new_gacha
            distance_4_star = 0

        if is_5_star(new_gacha):
            last_time_5 = new_gacha
            distance_5_star = 0

        if not last_4_up:
            if new_gacha in ROLE_ARMS_LIST['4_up']:
                last_4_up = i + 1

        if not last_5_up:
            if new_gacha in ROLE_ARMS_LIST['5_up']:
                last_5_up = i + 1

    mes = '本次祈愿得到以下角色装备:\n'
    res = concat_pic(gacha_list)
    res = pic2b64(res)
    mes += str(MessageSegment.image(res))
    mes += '\n'
    mes += gacha_txt

    if last_4_up:
        mes += f'第 {last_4_up} 抽首次出现4★UP!'
        mes += '\n'
    if last_5_up:
        mes += f'第 {last_5_up} 抽首次出现5★UP!'

    return mes
Exemple #28
0
async def cat(session: CommandSession):
    try:
        web_image = requests.get('https://thiscatdoesnotexist.com/',
                                 timeout=10)
        if web_image.status_code == 200:
            with open(path + r"\cat.jpg", "wb") as f:
                f.write(web_image.content)
    except:
        pass
    session.finish(str(MessageSegment.image("file:///" + path + r"\cat.jpg")))
Exemple #29
0
async def edgecat(session: CommandSession):
    try:
        web_image = requests.get('http://edgecats.net/', timeout=10)
        if web_image.status_code == 200:
            with open(path + r"\edgecat.gif", "wb") as f:
                f.write(web_image.content)
    except:
        pass
    session.finish(
        str(MessageSegment.image("file:///" + path + r"\edgecat.gif")))
Exemple #30
0
def mai_daode(ctx: Context_T, account: Account) -> str:
    maidaode = f'{ctx["sender"]["nickname"]}买到的宝贝\n'
    with open(settings.MAIDAODE_LIST, mode='r', encoding='utf-8') as f:
        for line in f:
            user, commodity, price, nums = line.strip().split('|')
            if user == ctx["sender"]["nickname"]:
                maidaode += commodity + '\t' + price + '\n'
            else:
                maidaode += '还不买些东西吗'
    return (MessageSegment.image(account.avatar_url) + f'\n' f'{maidaode}\n')