Example #1
0
 def cqcode(self) -> MessageSegment:
     if salmon.configs.RES_PROTOCOL == 'http':
         return MessageSegment.image(self.url)
     elif salmon.configs.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:
             salmon.logger.exception(e)
             return MessageSegment.text('[图片出错]')
Example #2
0
async def gacha_300(bot, event: GroupMessageEvent):

    await check_tenjo_num(bot, event)
    tenjo_limit.increase(event.user_id)

    gid = str(event.group_id)
    gacha = Gacha(_group_pool[gid])
    result = gacha.gacha_tenjou()
    up = len(result['up'])
    s3 = len(result['s3'])
    s2 = len(result['s2'])
    s1 = len(result['s1'])

    res = [*(result['up']), *(result['s3'])]
    random.shuffle(res)
    lenth = len(res)
    if lenth <= 0:
        res = "竟...竟然没有3★?!"
    else:
        step = 4
        pics = []
        for i in range(0, lenth, step):
            j = min(lenth, i + step)
            pics.append(chara.gen_team_pic(
                res[i:j], star_slot_verbose=False))
        res = concat_pic(pics)
        res = pic2b64(res)
        res = MessageSegment.image(file=res)

    msg = f"\n素敵な仲間が増えますよ!\n" + \
          res + "\n" + \
          f"★★★×{up+s3} ★★×{s2} ★×{s1}\n" + \
          f"获得记忆碎片×{100*up}与女神秘石×{50*(up+s3) + 10*s2 + s1}!\n第{result['first_up_pos']}抽首次获得up角色" if up else f"获得女神秘石{50*(up+s3) + 10*s2 + s1}个!\n"

    if up == 0 and s3 == 0:
        msg += "太惨了,咱们还是退款删游吧...\n"
    elif up == 0 and s3 > 7:
        msg += "up呢?我的up呢?\n"
    elif up == 0 and s3 <= 3:
        msg += "这位酋长,梦幻包考虑一下?\n"
    elif up == 0:
        msg += "据说天井的概率只有12.16%\n"
    elif up <= 2:
        if result['first_up_pos'] < 50:
            msg += "你的喜悦我收到了,滚去喂鲨鱼吧!\n"
        elif result['first_up_pos'] < 100:
            msg += "已经可以了,您已经很欧了\n"
        elif result['first_up_pos'] > 290:
            msg += "标 准 结 局\n"
        elif result['first_up_pos'] > 250:
            msg += "补井还是不补井,这是一个问题...\n"
        else:
            msg += "期望之内,亚洲水平\n"
    elif up == 3:
        msg += "抽井母五一气呵成!多出30等专武~\n"
    elif up >= 4:
        msg += "记忆碎片一大堆!您是托吧?\n"

    await bot.send(event, msg, at_sender=True)
    silence_time = (100*up + 50*(up+s3) + 10*s2 + s1) * 1
Example #3
0
async def handle_semimonthly(bot: Bot, event: Event, state: T_State):
    data = open_jsonfile(plugin_path + "/data.json")
    if not data["semimonthly"].get(state["semimonthly_name"]):
        await semimonthly.reject("你想查询的半月刊暂不支持,请重新输入!\neg:2-1,2-2,3-1\n默认为最新一期"
                                 )
    if state["semimonthly_name"] == "new":
        state["semimonthly_name"] = data["semimonthly"]["new"]
    filename = data["semimonthly"][state["semimonthly_name"]]

    from nonebot.adapters.cqhttp.message import MessageSegment

    img = os.path.join(semimonthly_folder, filename)
    await semimonthly.finish(MessageSegment.image(rf"file:///{img}"))
Example #4
0
async def noticeReceive(bot: Bot, event: NoticeEvent, state: str):
    msg = str(event)[23:].replace("'", '"')
    image = json.loads(msg)
    imageName = image['file']['name']
    imageUrl = image['file']['url']
    processPicture(imageName, imageUrl)
    if os.path.exists(resolutionPath):
        try:
            await pictureNotice.send(MessageSegment.image(imagePath))
        except:
            await pictureNotice.send(exception)
        finally:
            os.remove(outputPath)
Example #5
0
 async def format(self, img):
     type_msg = {
         0: "发布了新动态",
         1: "转发了一条动态",
         8: "发布了新投稿",
         16: "发布了短视频",
         64: "发布了新专栏",
         256: "发布了新音频"
     }
     self.message = (f"{self.name} " +
                     f"{type_msg.get(self.type, type_msg[0])}:\n" +
                     f"{self.url}\n" +
                     MessageSegment.image(f"base64://{img}"))
Example #6
0
 def best30(obj_in: schema.UserBest30) -> MessageSegment:
     current_path = Path(__file__).resolve().parent
     img = Image.open(current_path / 'assets/bg.png')
     draw = ImageDraw.ImageDraw(img)
     ft_normal = ImageFont.truetype(
         str(current_path / 'assets/Roboto-Bold.ttf'), 18)
     ft_low = ImageFont.truetype(
         str(current_path / 'assets/Roboto-Regular.ttf'), 14)
     ft_title = ImageFont.truetype(
         str(current_path / 'assets/Roboto-Bold.ttf'), 25)
     title_color = (230, 230, 230)
     inner_gap = [20, 52, 52]
     userptt = obj_in.best30_avg * 0.75 + obj_in.recent10_avg * 0.25
     b30_songids = [i.song_id for i in obj_in.best30_list]
     b30_scores = [i.score for i in obj_in.best30_list]
     b30_ratings = [i.rating for i in obj_in.best30_list]
     b30_difficulties = [i.difficulty for i in obj_in.best30_list]
     b30_len = len(obj_in.best30_list)
     for i in range(min(b30_len, 15)):
         # 绘制左边 15 条数据,数据不足 15 条可以兼容
         ylen = 60 * i
         draw.text((150, ylen + inner_gap[0]),
                   f'{b30_songids[i]} [{b30_difficulties[i].upper()}]',
                   title_color,
                   font=ft_title)
         draw.text((150, ylen + inner_gap[1]),
                   f'Score: {b30_scores[i]}', (255, 255, 255),
                   font=ft_normal)
         draw.text((400, ylen + inner_gap[2]),
                   f'PTT: {b30_ratings[i]:.2f}', (255, 255, 255),
                   font=ft_normal)
     if b30_len > 15:
         # 当数据数量大于 15 时,绘制右边 `b30_len` - 15 条数据,兼容数据不满 30 条但是满了 15 条的情况
         for i in range(b30_len - 15):
             ylen = 60 * i
             draw.text(
                 (600, ylen + inner_gap[0]),
                 f'{b30_songids[i + 15]} [{b30_difficulties[i + 15].upper()}]',
                 title_color,
                 font=ft_title)
             draw.text((600, ylen + inner_gap[1]),
                       f'Score: {b30_scores[i + 15]}', (255, 255, 255),
                       font=ft_normal)
             draw.text((850, ylen + inner_gap[2]),
                       f'PTT: {b30_ratings[i + 15]:.2f}', (255, 255, 255),
                       font=ft_normal)
     info_draw = f'Player PTT: {userptt:.2f}   b30_avg: {obj_in.best30_avg:.2f}   r10_avg: {obj_in.recent10_avg:.2f}'
     draw.text((800, 930), info_draw, (200, 200, 200), font=ft_low)
     author_draw = datetime.now().strftime("%F %X") + "   Powered by iyume"
     draw.text((20, 930), author_draw, (200, 200, 200), font=ft_low)
     return MessageSegment.image(f'base64://{imageobj_to_base64(img)}')
Example #7
0
async def messageReceive(bot: Bot, event: MessageEvent, state: str):
    msg = utils.escape(str(event.message)).replace(
        "&#91;CQ:",
        "{'CQ': '").replace("&#44;", "', '").replace("l=", "l': '").replace(
            "e=", "e': '").replace("&#93;", "'}").replace("'", '"')
    image = json.loads(msg)
    if image['CQ'] == 'image':
        imageName = image['file'][:-5] + 'png'
        imageUrl = image['url']
        processPicture(imageName, imageUrl)
        if os.path.exists(resolutionPath):
            try:
                await pictureMessage.send(MessageSegment.image(imagePath))
            except:
                await pictureMessage.send(exception)
            finally:
                os.remove(outputPath)
Example #8
0
async def live_sched():
    """直播推送"""

    async with DB() as db:
        uids = await db.get_uid_list('live')

    if not uids:
        return
    logger.debug(f'爬取直播列表,目前开播{sum(status.values())}人,总共{len(uids)}人')
    br = BiliReq()
    res = await br.get_live_list(uids)
    if not res:
        return
    for uid, info in res.items():
        new_status = 0 if info['live_status'] == 2 else info['live_status']
        if uid not in status:
            status[uid] = new_status
            continue
        old_status = status[uid]
        if new_status != old_status and new_status:  # 判断是否推送过
            room_id = info['short_id'] if info['short_id'] else info['room_id']
            url = 'https://live.bilibili.com/' + str(room_id)
            name = info['uname']
            title = info['title']
            cover = (info['cover_from_user']
                     if info['cover_from_user'] else info['keyframe'])
            logger.info(f"检测到开播:{name}({uid})")

            live_msg = (f"{name} 正在直播:\n{title}\n" +
                        MessageSegment.image(cover) + f"\n{url}")
            async with DB() as db:
                push_list = await db.get_push_list(uid, 'live')
                for sets in push_list:
                    await safe_send(bot_id=sets.bot_id,
                                    send_type=sets.type,
                                    type_id=sets.type_id,
                                    message=live_msg,
                                    at=sets.at)
                await db.update_user(uid, name)
        status[uid] = new_status
Example #9
0
async def avatar_guess(bot: Bot, event: GroupMessageEvent):
    if gm.is_playing(event.group_id):
        await bot.send(event, "游戏仍在进行中…")
        return
    with gm.start_game(event.group_id) as game:
        ids = list(_pcr_data.CHARA_NAME.keys())
        game.answer = random.choice(ids)
        while chara.is_npc(game.answer):
            game.answer = random.choice(ids)
        c = chara.fromid(game.answer)
        img = c.icon.open()
        w, h = img.size
        l = random.randint(0, w - PATCH_SIZE)
        u = random.randint(0, h - PATCH_SIZE)
        cropped = img.crop((l, u, l + PATCH_SIZE, u + PATCH_SIZE))
        cropped = MessageSegment.image(util.pic2b64(cropped))
        await bot.send(event,
                       f"猜猜这个图片是哪位角色头像的一部分?({ONE_TURN_TIME}s后公布答案)" + cropped)
        await asyncio.sleep(ONE_TURN_TIME)
        if game.winner:
            return
    await bot.send(event, f"正确答案是:{c.name}" + c.icon.cqcode + "\n很遗憾,没有人答对~")
Example #10
0
    def df2info(self, data):
        '''
        将df数据转换为bot输出的Message
        '''
        msg = []

        for item in data.iterrows():
            item = item[1]
            if 'dx' in item['rank']:
                rank = '[DX]'
            else:
                rank = '[标准]'

            for R in self.rank_color.keys():
                if R in str(item['rank']).split('_'):
                    rank = rank + self.rank_color[R]
                    break

            rank = rank + ' ' + item[item['rank']]
            img = MessageSegment.image(file=item['jacket'])
            msg.append(
                f"【{self.classes_list[item['catcode']]}】\n『{item['title']}』\n"
                + img + f"\n{rank}")
        return msg
Example #11
0
async def gacha_10(bot, event: GroupMessageEvent):
    SUPER_LUCKY_LINE = 170

    await check_jewel_num(bot, event)
    jewel_limit.increase(event.user_id, 1500)

    gid = str(event.group_id)
    gacha = Gacha(_group_pool[gid])
    result, hiishi = gacha.gacha_ten()
    silence_time = hiishi * 6 if hiishi < SUPER_LUCKY_LINE else hiishi * 60

    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'\n{res1}\n{res2}'
    msg = f'素敵な仲間が増えますよ!\n' + res
    if hiishi >= SUPER_LUCKY_LINE:
        await bot.send(event, '恭喜海豹!おめでとうございます!')
    await bot.send(event, msg, at_sender=True)
Example #12
0
async def _(bot: Bot, event: Event, state: T_State):
    h, _ = get_time()
    if h >= 21 or h <= 2:
        img_src = path + '/data/睡觉.png'
        img = MessageSegment.image(f'file://{img_src}')
        await bot.send(event, message=img)
Example #13
0
from nonebot import on_command, on_message, on_notice, get_bots
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.event import (Event, GroupMessageEvent,
                                           MessageEvent)
from nonebot.adapters.cqhttp.message import Message, MessageSegment
from nonebot.typing import T_State
from nonebot import require
from os import path
import time
scheduler = require('nonebot_plugin_apscheduler').scheduler
groups = [648868273]

path = path.abspath(__file__).split('__')[0]
img_src = path + '/data/sleep.png'
sleep_img = MessageSegment.image(f'file://{img_src}')


@scheduler.scheduled_job('cron', hour='23', minute='0',
                         misfire_grace_time=60)  # = UTC+8 1445
async def sleep():
    for bot in get_bots().values():
        for group in groups:
            await bot.send_group_msg(group_id=group, message=sleep_img)


def get_time():
    now = (time.strftime("%H:%M", time.localtime()))
    h = int(now[:2])
    m = int(now[3:])
    return (h, m)
Example #14
0
async def get_momo(bot: Bot, event: Event):
    print("get_momo")
    files = os.listdir(momo_folder)
    filename = random.choice(files)
    img = os.path.join(momo_folder, filename)
    await bot.send(event, MessageSegment.image(rf"file:///{img}"))
Example #15
0
async def setu_handle(bot: Bot, event: Event, state: T_State):

    #获取关键词,数量 并处理
    comman = str(event.message).split(' ')
    keyword = ''
    num = 1
    print(comman)
    # 变量只有一个 判定是keyword还是num
    try:
        if len(comman) == 1:
            if len(comman[0]) == 1 and comman[0].isdigit():
                num = int(comman[0])
            else:
                keyword = (comman[0])
        else:
            keyword = comman[0]
            num = int(comman[1])
    except:
        pass

    user_id = event.user_id
    try:
        if user_id not in times.keys():
            times[user_id] = 0
        if (user_id not in master):

            if times[user_id] > MAX:
                times[user_id] = 0
                await bot.send(event, message=img)
                return 0

            if int(num) > 3:
                num = 3
                await bot.send(event, message=f'一次最多3张哦~')

        setu_url = []
        print(keyword)
        print(keyword.isdigit())
        if keyword == 'rank':
            setu_url = random.sample(setubot.rank(), num)
        elif keyword.isdigit():
            setu_url = setubot.artist(int(num), keyword)
        else:
            setu_url = setubot.getpic(int(num), keyword)
        if len(setu_url) == 0:
            setu_url = setubot.getpic()
            await bot.send(event, message=f'找不到{keyword}的色图哦,随机一张吧')

        ###获取到url
        for i, u in enumerate(setu_url):
            ourl = f'/home/admin/bot/plugins/setu/setu/{i}.jpg'
            ml = f'wget {u} -O {ourl}'
            os.system(ml)
            #await bot.send(event, message = MessageSegment.image(f'file://{ourl}'))
            pic_id = await bot.send_group_msg(
                group_id=event.group_id,
                message=MessageSegment.image(f'file://{ourl}'))
            setubot.pic_id = pic_id['message_id']
            os.system(f'rm {ourl} -f')
        times[user_id] += num
    except:
        await bot.send_private_msg(user_id=master[0], message='error setu')