コード例 #1
0
ファイル: handler.py プロジェクト: Zhao-FlorenCE/CSC_Code
async def get_result(bot: Bot, event: Event, state: T_State):
    at = MessageSegment.at(event.get_user_id())
    if not state.get("content"):
        result = await get_help()
    elif str(state.get("content")).lower() == "list":
        plugin_set = nonebot.plugin.get_loaded_plugins()
        plugin_names = []
        for plugin in plugin_set:
            try:
                name = f'{plugin.name} | ' \
                    f'{plugin.module.__getattribute__("__help_plugin_name__")}'
            except:
                name = f'{plugin.name}'
            try:
                version = plugin.module.__getattribute__("__help_version__")
            except:
                version = ""
            plugin_names.append(f'{name} {version}')
        plugin_names.sort()
        newline_char = '\n'
        result = f'已加载插件:\n{newline_char.join(plugin_names)}'
    else:
        try:
            plugin = nonebot.plugin.get_plugin(state.get("content"))
        except AttributeError:
            plugin = None
        try:
            result = plugin.module.__getattribute__("__usage__")
        except:
            try:
                result = plugin.module.__doc__
            except AttributeError:
                result = f'{state.get("content")}插件不存在或未加载'
    await helper.finish(Message().append(at).append(
        MessageSegment.text(result)))
コード例 #2
0
ファイル: handler.py プロジェクト: XZhouQD/MirageBot
async def get_result(bot: Bot, event: Event, state: T_State):
    if state.get("content") in ('help', 'h'):
        at_user = MessageSegment.at(event.get_user_id())
        result = await get_help()
    else:
        at_user = MessageSegment.at(event.get_user_id())
        roll_result = await roll_dice(state.get("content"))
        result = MessageSegment.text(roll_result)
    await dice.finish(Message().append(at_user).append(result))
コード例 #3
0
ファイル: R.py プロジェクト: 851957361/SalmonBot
 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('[图片出错]')
コード例 #4
0
    def text(
        obj_in: Union[schema.UserInfo, schema.UserBest30, schema.SongInfo,
                      schema.SongScore]
    ) -> MessageSegment:
        if isinstance(obj_in, schema.UserInfo):
            info_msg = '\n'.join(
                (f"name: {obj_in.name}", f"PTT: {obj_in.rating}"))
            recent = obj_in.recent_score
            recent_msg = '\n'.join(
                (f"最近游玩: {recent.song_id}", f"难度: {recent.difficulty}",
                 f"Score: {recent.score}", f"PTT: {recent.rating:.2f}",
                 f"大 P: {recent.shiny_perfect_count}",
                 f"小 P: {recent.perfect_count - recent.shiny_perfect_count}",
                 f"count P: {recent.perfect_count}",
                 f"count FAR: {recent.near_count}",
                 f"count MISS: {recent.miss_count}",
                 f"Time: {recent.time_played:%F %X}")) if recent else None
            msg = '\n'.join(
                [x for x in [info_msg, recent_msg] if isinstance(x, str)])
            return MessageSegment.text(msg)
        if isinstance(obj_in, schema.UserBest30):

            def songscore_msg_lambda(s: schema.SongScore) -> str:
                return '\n'.join(
                    (f"{s.song_id} {s.difficulty}", f"  Score: {s.score}",
                     f"  PTT: {s.rating:.2f}"))

            info_msg = '\n'.join((f"b30_avg: {obj_in.best30_avg}",
                                  f"r10_avg: {obj_in.recent10_avg}"))
            songs_msg = '\n'.join(f"{i + 1}: {val}" for i, val in enumerate(
                map(songscore_msg_lambda, obj_in.best30_list)))
            msg = '\n'.join((info_msg, songs_msg))
            return MessageSegment.text(msg)
        if isinstance(obj_in, schema.SongInfo):

            def songinfo_perlevel(s: schema.SongInfoPerLevel) -> str:
                return '\n'.join(
                    (f"- 难度: {s.ratingClass}",
                     f"  等级: {s.rating}{'+' if s.ratingPlus else ''}",
                     f"  定数: {s.ratingReal}", f"  物量: {s.totalNotes}"))

            info_msg = '\n'.join(
                (f"song_id: {obj_in.id}", f"artist: {obj_in.artist}",
                 f"bpm: {obj_in.bpm}", f"date: {obj_in.date:%F %X}"))
            levels_msg = '\n'.join(map(songinfo_perlevel, obj_in.difficulties))
            msg = '\n'.join((info_msg, levels_msg))
            return MessageSegment.text(msg)
        if isinstance(obj_in, schema.SongScore):
            songscore_msg = text_utils.songscore(obj_in)
            return MessageSegment.text(songscore_msg)
コード例 #5
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
コード例 #6
0
ファイル: utils.py プロジェクト: nightingu/damebot
 async def cmd_handler(self, bot: Bot, event: Event, state: T_State, matcher: Matcher, cmd=None):
     # get real command content
     cwd, msg, task = await self.cmd_run(bot=bot, event=event, state=state, matcher=matcher, cmd_replaced=cmd, empty_hint=True)
     if self.workspace_mode == WorkspaceMode.serial:
         queue = self.running_queues[cwd]
         task = queue.run(task)
     output = await task
     if self.reply_notify:
         if hasattr(event, "group_id") and hasattr(event, "message_id"):
             # reply Mode
             output = MessageSegment.reply(event.message_id) + output
         else:
             output = MessageSegment.at(event.get_user_id()) + "\n" + output
     extra_msgs = {}
     if self.hidden_result:
         extra_msgs.update({"message_type": "private"})
     logger.info(f"{msg} ===> {output}")
     await matcher.send(output, **extra_msgs)
コード例 #7
0
ファイル: __init__.py プロジェクト: hailong-z/nonebot2_miya
async def miya_button(bot: Bot, event: GroupMessageEvent, state: T_State):
    arg = str(event.get_plaintext()).strip().lower()
    voice = re.sub('喵一个', '', arg)
    voice_file = MiyaVoice().get_voice_filepath(voice=voice)
    if not os.path.exists(voice_file):
        await bot.send(event=event, message='喵?')
    else:
        msg = MessageSegment.record(file=f'file:///{voice_file}')
        await bot.send(event=event, message=msg)
コード例 #8
0
ファイル: jrrp.py プロジェクト: Zeta-qixi/nonebot2-plugins
async def _(bot: Bot, event: GroupMessageEvent):
    print('tt')
    msg = event.raw_message
    user_id = event.user_id
    jp = rpbot.RP(user_id)

    if jp:
        msg= f'今天的人品值是:{jp}'
        if nn.my_name(user_id):
            await bot.send(event, message=f'{nn.my_name(user_id)}{msg}')
        else:
            await bot.send(event, message=MessageSegment.at(user_id)+msg)
コード例 #9
0
ファイル: __init__.py プロジェクト: hailong-z/nonebot2_miya
async def handle_group_increase(bot: Bot, event: GroupIncreaseNoticeEvent,
                                state: T_State):
    user_id = event.user_id
    group_id = event.group_id
    detail_type = event.notice_type
    if detail_type == 'group_increase' and DBGroup(
            group_id=group_id).permission_command().result == 1:
        # 发送欢迎消息
        at_seg = MessageSegment.at(user_id=user_id)
        msg = f'{at_seg}欢迎新朋友~\n进群请先看群公告~\n一起愉快地聊天吧!'
        await bot.send(event=event, message=Message(msg))
        logger.info(f'群组: {group_id}, 有新用户: {user_id} 进群')
コード例 #10
0
ファイル: __init__.py プロジェクト: zfjdhj/momobot
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}"))
コード例 #11
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}"))
コード例 #12
0
ファイル: __init__.py プロジェクト: Zhao-FlorenCE/CSC_Code
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)
コード例 #13
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)}')
コード例 #14
0
ファイル: combat.py プロジェクト: epicteller/epicteller
async def format_token_message(token: CombatToken) -> Message:
    default_msg = Message(f'「{token.name}」')
    if not token.character_id:
        return default_msg
    character = await character_ctl.get_character(token.character_id)
    if not character:
        return default_msg
    external_id = await character_ctl.get_character_external_id(
        character.id, ExternalType.QQ)
    if not external_id:
        return default_msg
    if character.name == token.name:
        return Message(MessageSegment.at(external_id))
    return Message(f'「{token.name}」(控制者:{MessageSegment.at(external_id)})')
コード例 #15
0
ファイル: desc_guess.py プロジェクト: liwh011/Kaguya-QQBot
async def on_input_chara_name(bot, event: GroupMessageEvent):
    game = gm.get_game(event.group_id)
    if not game or game.winner:
        return

    dtime = int((datetime.now()-game.start_time).total_seconds())
    c = chara.fromname(event.message.extract_plain_text())
    if c.id != chara.UNKNOWN and c.id == game.answer:
        game.winner = event.user_id
        n = game.record()
        msg = f"正确答案是:{c.name}" + c.icon.cqcode+"\n"
        msg += MessageSegment.at(event.user_id) + \
            f"花了{dtime}秒就猜对了,真厉害!TA已经猜对{n}次了~\n(此轮游戏将在几秒后自动结束,请耐心等待)"
        await bot.send(event, msg)
        await sv.notify_others('pcr_guess_chara_name_win',
                               group_id=event.group_id, user_id=event.user_id, use_time=dtime, bot=bot, event=event)
コード例 #16
0
def _gen_namelist_text(bm: BattleMaster,
                       uidlist: List[int],
                       memolist: List[str] = None,
                       do_at=False):
    if do_at:
        mems = map(lambda x: str(ms.at(x)), uidlist)
    else:
        mems = map(
            lambda x: bm.get_member(x, bm.group) or bm.get_member(x, 0) or
            {'name': str(x)}, uidlist)
        mems = map(lambda x: x['name'], mems)
    if memolist:
        mems = list(mems)
        for i in range(len(mems)):
            if i < len(memolist) and memolist[i]:
                mems[i] = f"{mems[i]}:{memolist[i]}"
    return mems
コード例 #17
0
ファイル: __init__.py プロジェクト: Zhao-FlorenCE/CSC_Code
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)
コード例 #18
0
async def _code_runner(bot: Bot, event: MessageEvent):
    user_id = event.get_user_id()
    if not _flmt.check(user_id):
        await code_runner.finish(_flmt_notice)

    msg = str(event.get_message())
    args = msg.split("\n")

    if not args:
        content = f"> {MessageSegment.at(user_id)}\n" + "请键入 /code help 以获取帮助~!"
    elif args[0] == "help":
        content = f"> {MessageSegment.at(user_id)}\n" + CodeRunner().help()
    elif args[0] == "list":
        content = f"> {MessageSegment.at(user_id)}\n" + CodeRunner(
        ).list_supp_lang()
    else:
        content = MessageSegment.at(user_id) + await CodeRunner().runner(msg)

    _flmt.start_cd(user_id)
    await code_runner.finish(Message(content))
コード例 #19
0
async def call_subscribe(bot: Bot, ctx: Event, round_: int, boss: int):
    bm = BattleMaster(ctx.group_id)
    msg = []
    sub = _load_sub(bm.group)
    slist = sub.get_sub_list(boss)
    mlist = sub.get_memo_list(boss)
    tlist = sub.get_tree_list()
    if slist:
        msg.append(f"您们预约的老{BattleMaster.int2kanji(boss)}出现啦!")
        msg.extend(_gen_namelist_text(bm, slist, mlist, do_at=True))
    if slist and tlist:
        msg.append("==========")
    if tlist:
        msg.append(f"以下成员可以下树了")
        msg.extend(map(lambda x: str(ms.at(x)), tlist))
        sub.clear_tree()
        _save_sub(sub, bm.group)
    if msg:
        await bot.send(ctx, '\n'.join(msg),
                       at_sender=False)  # do not at the sender
コード例 #20
0
ファイル: live_pusher.py プロジェクト: zhzRedstone/HarukaBot
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
コード例 #21
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很遗憾,没有人答对~")
コード例 #22
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)
コード例 #23
0
ファイル: maidx.py プロジェクト: Zeta-qixi/nonebot2-plugins
    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
コード例 #24
0
ファイル: test.py プロジェクト: 89461561511656/nonebot2
async def h_r(bot: Bot, event: Event, state: T_State):
    id = str(event.get_user_id())
    biaoqing = f"[CQ:face,id=5]"  # 表情包使用
    await test.send(MessageSegment.at(id) + biaoqing + '呜呜,我真的哭了')
コード例 #25
0
ファイル: test.py プロジェクト: 89461561511656/nonebot2
async def h_r(bot: Bot, event: Event, state: T_State):
    id = str(event.get_user_id())
    # biaoqing = f"[CQ:face,id=182]"  # 表情包使用
    # await test.send(MessageSegment.at(id) + biaoqing + '哈哈,笑死我了')
    await test.send(MessageSegment.at(id) + MessageSegment.face(182) + '笑死我了')
コード例 #26
0
ファイル: test.py プロジェクト: 89461561511656/nonebot2
async def h_r(bot: Bot, event: Event, state: T_State):
    id = str(event.get_user_id())
    # yuyin=f"[CQ:record,file=http://baidu.com/1.mp3]"
    # biaoqing=f"[CQ:face,id=123]"#表情包使用
    hongbao = f"[CQ:gift,qq={id},id=0]"  # 礼物使用
    await test.send(MessageSegment.at(id) + hongbao)
コード例 #27
0
ファイル: __init__.py プロジェクト: zfjdhj/momobot
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}"))
コード例 #28
0
async def hime_handle(bot: Bot, event: GroupUploadNoticeEvent, state: T_State):
    file_name = event.file.name
    file_url = event.file.dict().get('url')
    user_id = event.user_id

    # 不响应自己上传的文件
    if int(event.user_id) == int(bot.self_id):
        await zhouShenHime.finish()

    if file_name.split('.')[-1] not in ['ass', 'ASS']:
        await zhouShenHime.finish()

    # 只处理文件名中含"未校""待校""需校"的文件
    if not any(key in file_name for key in ['未校', '待校', '需校']):
        await zhouShenHime.finish()

    plugin_path = os.path.dirname(__file__)
    download_dir = os.path.join(plugin_path, 'file_downloaded')
    if not os.path.exists(download_dir):
        os.makedirs(download_dir)

    download_file_path = os.path.join(download_dir, file_name)
    dl_res = await download_file(url=file_url, file_path=download_file_path)
    if not dl_res.success():
        logger.error(f'下载文件失败: {dl_res.info}')
        await zhouShenHime.finish()

    at_msg = MessageSegment.at(user_id=user_id)
    msg = f'{at_msg}你刚刚上传了一份轴呢, 让我来帮你看看吧!'
    await zhouShenHime.send(Message(msg))

    checker = ZhouChecker(file_path=download_file_path, flash_mode=True)

    try:
        init_res = checker.init_file(auto_style=True)
        if not init_res.success():
            logger.error(f'初始化时轴文件失败: {init_res.info}')
            await zhouShenHime.finish('出错了QAQ')

        handle_res = checker.handle()
        if not handle_res.success():
            logger.error(f'处理时轴文件失败: {handle_res.info}')
            await zhouShenHime.finish('出错了QAQ')
    except Exception as e:
        logger.error(f'执行ZhouChecker时发生了意外的错误: {repr(e)}')
        await zhouShenHime.finish('出错了QAQ')
        return

    output_txt_path = os.path.abspath(handle_res.result.get('output_txt_path'))
    output_txt_filename = os.path.basename(output_txt_path)

    output_ass_path = os.path.abspath(handle_res.result.get('output_ass_path'))
    output_ass_filename = os.path.basename(output_ass_path)

    character_count = handle_res.result.get('character_count')
    overlap_count = handle_res.result.get('overlap_count')
    flash_count = handle_res.result.get('flash_count')

    # 没有检查到错误的话就直接结束
    if character_count + flash_count + overlap_count == 0:
        msg = f'看完了! 没有发现符号错误、疑问文本、叠轴和闪轴, 真棒~'
        await zhouShenHime.finish(msg)

    try:
        group_file_info = await bot.call_api(api='get_group_root_files',
                                             group_id=event.group_id)
        group_folders = group_file_info.get('folders')

        folder_id = None
        if group_folders:
            for folder in group_folders:
                if folder.get('folder_name') == '锤轴记录':
                    folder_id = folder.get('folder_id')
                    break

        if folder_id:
            await bot.call_api(api='upload_group_file',
                               group_id=event.group_id,
                               folder=folder_id,
                               file=output_txt_path,
                               name=output_txt_filename)
            await bot.call_api(api='upload_group_file',
                               group_id=event.group_id,
                               folder=folder_id,
                               file=output_ass_path,
                               name=output_ass_filename)
        else:
            await bot.call_api(api='upload_group_file',
                               group_id=event.group_id,
                               file=output_txt_path,
                               name=output_txt_filename)
            await bot.call_api(api='upload_group_file',
                               group_id=event.group_id,
                               file=output_ass_path,
                               name=output_ass_filename)
    except Exception as e:
        logger.error(f'上传结果时时发生了意外的错误: {repr(e)}')
        await zhouShenHime.finish('出错了QAQ')
        return

    msg = f'看完了! 以下是结果:\n\n符号及疑问文本共{character_count}处\n' \
          f'叠轴共{overlap_count}处\n闪轴共{flash_count}处\n\n锤轴结果已上传, 请参考修改哟~'
    await zhouShenHime.finish(msg)
コード例 #29
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)
コード例 #30
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)