Esempio n. 1
0
    async def run_handler(self, handler: T_Handler, bot: "Bot", event: "Event",
                          state: T_State):
        if not hasattr(handler, "__params__"):
            self.process_handler(handler)
        params = getattr(handler, "__params__")

        BotType = ((params["bot"] is not inspect.Parameter.empty) and
                   inspect.isclass(params["bot"]) and params["bot"])
        if BotType and not isinstance(bot, BotType):
            logger.debug(
                f"Matcher {self} bot type {type(bot)} not match annotation {BotType}, ignored"
            )
            return

        EventType = ((params["event"] is not inspect.Parameter.empty) and
                     inspect.isclass(params["event"]) and params["event"])
        if EventType and not isinstance(event, EventType):
            logger.debug(
                f"Matcher {self} event type {type(event)} not match annotation {EventType}, ignored"
            )
            return

        args = {"bot": bot, "event": event, "state": state, "matcher": self}
        await handler(
            **{k: v for k, v in args.items() if params[k] is not None})
Esempio n. 2
0
    async def solve(
        self,
        **params: Any,
    ) -> Dict[str, Any]:
        values: Dict[str, Any] = {}

        for checker in self.pre_checkers:
            await checker._solve(**params)

        for param in self.parameterless:
            await param._solve(**params)

        for field in self.params:
            field_info = field.field_info
            assert isinstance(field_info,
                              Param), "Params must be subclasses of Param"
            value = await field_info._solve(**params)
            if value is Undefined:
                value = field.get_default()

            try:
                values[field.name] = check_field_type(field, value)
            except TypeMisMatch:
                logger.debug(
                    f"{field_info} "
                    f"type {type(value)} not match depends {self.call} "
                    f"annotation {field._type_display()}, ignored")
                raise

        return values
Esempio n. 3
0
async def _(session: NLPSession):
    # logger.debug(session.msg_text)
    # logger.debug(session.msg)
    group_id = context_id(session.ctx, mode='group')
    user_id = session.ctx['user_id']
    msg = session.msg

    record = records.get(group_id)  # 查找是否有原来的复读信息

    # 如果没有就添加进去
    if record is None:
        record = Record(last_msg=msg, last_usr_id=user_id, repeat_count=1)
        records[group_id] = record
        return

    # 如果之前已经有了不同人复读信息
    if record.last_msg != msg or \
            record.last_usr_id == user_id:
        record.last_msg = msg
        record.repeat_count = 1
        return

    record.last_usr_id = user_id
    record.repeat_count += 1

    logger.debug(record.repeat_count)
    logger.debug("msg" + msg)

    if record.repeat_count == 5:
        record.repeat_count = 1
        if record.repeat_msg != msg:
            record.repeat_msg = msg
            return IntentCommand(60.0, 'say', current_arg=msg)
    return
Esempio n. 4
0
def _check_nickname(bot: "Bot", event: "Event"):
    if event.type != "message":
        return

    first_msg_seg = event.message[0]
    if first_msg_seg.type != "text":
        return

    first_text = first_msg_seg.data["text"]

    if bot.config.NICKNAME:
        # check if the user is calling me with my nickname
        if isinstance(bot.config.NICKNAME, str) or \
                not isinstance(bot.config.NICKNAME, Iterable):
            nicknames = (bot.config.NICKNAME, )
        else:
            nicknames = filter(lambda n: n, bot.config.NICKNAME)
        nickname_regex = "|".join(nicknames)
        m = re.search(rf"^({nickname_regex})([\s,,]*|$)", first_text,
                      re.IGNORECASE)
        if m:
            nickname = m.group(1)
            logger.debug(f"User is calling me {nickname}")
            event.to_me = True
            first_msg_seg.data["text"] = first_text[m.end():]
Esempio n. 5
0
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    logger.debug(args)
    if args:
        state["content"] = args
    else:
        state["content"] = ""
Esempio n. 6
0
async def get_City_Weather(city: str):
    # global city_id
    city_info = await get_Location(city)
    logger.debug(city_info)
    if city_info["code"] == "200":
        city_id = city_info["location"][0]["id"]
        city_name = city_info["location"][0]["name"]

        # 3天天气
        daily_info = await get_WeatherInfo("3d", city_id)
        daily = daily_info["daily"]
        day1 = daily[0]
        day2 = daily[1]
        day3 = daily[2]

        # 实时天气
        now_info = await get_WeatherInfo("now", city_id)
        now = now_info["now"]

        # 天气预警信息
        warning = await get_WeatherWarning(city_id)

        return {
            "city": city_name,
            "now": now,
            "day1": day1,
            "day2": day2,
            "day3": day3,
            "warning": warning,
        }
    else:
        logger.error(
            f"错误: {city_info['code']} 请参考 https://dev.qweather.com/docs/start/status-code/ "
        )
        return int(city_info["code"])
Esempio n. 7
0
async def weather(session: CommandSession):
    ans = "NULL"
    # 从会话状态(session.state)中获取城市名称(city),如果当前不存在,则询问用户
    city = lcut(session.get('city', prompt='亲亲您想查询哪个城市的天气呢?'))[-1]
    logger.debug(city)
    # 异步获取 获取城市的天气预报
    city_weather = await get_weather_of_city(city)

    # 解析完成后搞事情
    status = city_weather['status']
    if status == 'ok':
        basic = city_weather['basic']
        now = city_weather['now']
        # 这里判断是否是城市
        # 这样子写乱了一点 因为有可能会有别的配置模式 以后也好改
        if basic['parent_city'] == basic['location']:
            if basic['admin_area'] == basic['parent_city']:
                ans = f"{basic['cnty']}{city}现在的天气状况:\n"
            else:
                ans = f"{basic['cnty']}{basic['admin_area']}{city}现在的天气状况:\n"
        else:
            ans = f"{basic['cnty']}{basic['admin_area']}省{basic['parent_city']}市{city}现在的天气状况:\n"

        ans += f"天气:{now['cond_txt']}\n" \
               f"此时实际气温:{now['tmp']}℃ \t体感气温:{now['fl']}℃\n" \
               f"能见度:{now['vis']}\t湿度:{now['hum']}\n" \
               f"风向:{now['wind_dir']}方向\t风力:{now['wind_sc']}级"
    elif status == 'no more requests':
        ans = '亲亲这边已经到查询上限了呢, 请明天再来呢'
    elif status == 'unknown location':
        ans = '您好这边找不到这个地方呢亲亲'
    elif status == 'error':
        ans = '亲亲请求失败呢'
    # 向用户发送天气预报
    await session.send(ans)
Esempio n. 8
0
async def addEvent(qq: str, stunum: str, matcher: Matcher):
    db = pymysql.connect(host=QQMAP_HOST,
                         port=3306,
                         user=QQMAP_USERNAME,
                         passwd=QQMAP_PASSWORD,
                         db="cpds_db",
                         charset='utf8')

    cursor = db.cursor()
    sql = """INSERT INTO twqd(QQ,STUNUM,NAME,SCHOOL,UNIVERSITY)
                 VALUES ('{}', '{}', '{}', '{}', '{}')"""
    try:
        # 执行sql语句
        logger.debug(sql.format(qq, stunum, '', '', ''))
        cursor.execute(sql.format(qq, stunum, '', '', ''))
        # 提交到数据库执行
        db.commit()
    except:
        # Rollback in case there is any error
        logger.debug(f'FAILED: qq:{qq}, stunum:{stunum}')
        matcher.send('FAILED')
        db.rollback()

    db.close()
    cursor.close()
Esempio n. 9
0
async def live_sched():
    """直播推送"""

    with Config() as config:
        uid = config.next_uid('live')
        if not uid:
            return
        if uid not in uids:
            uids[uid] = 1
        push_list = config.get_push_list(uid, 'live')

    old_status = uids[uid]
    api = BiliAPI()
    user_info = (await api.get_info(uid))['live_room']
    name = push_list[0]['name']
    logger.debug(f'爬取直播 {name}({uid})')
    new_status = user_info['liveStatus']
    if new_status == old_status:
        return

    uids[uid] = new_status
    if new_status:
        live_msg = f"{name} 开播啦!\n\n{user_info['title']}\n传送门→{user_info['url']}\n[CQ:image,file={user_info['cover']}]"
        for sets in push_list:
            at_msg = ''
            if sets['at']:
                at_msg = '[CQ:at,qq=all] '
            bot = nonebot.get_bots()[sets['bot_id']]
            await safe_send(bot, sets['type'], sets['type_id'],
                            at_msg + live_msg)
Esempio n. 10
0
 async def _solve(self, event: Event, **kwargs: Any) -> Any:
     field: ModelField = self.extra["field"]
     _, errs_ = field.validate(event, {}, loc=("event", ))
     if errs_:
         logger.debug(f"Event type {type(event)} not match "
                      f"annotation {field._type_display()}, ignored")
         raise TypeMisMatch(field, event)
    async def __call__(self, matcher: "Matcher", bot: "Bot", event: "Event",
                       state: T_State):
        BotType = ((self.bot_type is not inspect.Parameter.empty)
                   and inspect.isclass(self.bot_type) and self.bot_type)
        if BotType and not isinstance(bot, BotType):
            logger.debug(
                f"Matcher {matcher} bot type {type(bot)} not match annotation {BotType}, ignored"
            )
            return

        EventType = ((self.event_type is not inspect.Parameter.empty)
                     and inspect.isclass(self.event_type) and self.event_type)
        if EventType and not isinstance(event, EventType):
            logger.debug(
                f"Matcher {matcher} event type {type(event)} not match annotation {EventType}, ignored"
            )
            return

        args = {"bot": bot, "event": event, "state": state, "matcher": matcher}
        await self.func(
            **{
                k: v
                for k, v in args.items()
                if self.signature.parameters.get(k, None) is not None
            })
Esempio n. 12
0
async def handle(bot: Bot, event: Event, state: T_State):
    try:
        args = str(state["args"]).split()
        if len(args) != 3:
            await adduser.send(Message(ADDUSER_ARGS_PROMPT))

        username, password, email = args
        logger.debug(f'adduser: {username} {password} {email}')
        state['username'] = username
        state['password'] = password
        state['email'] = email
        code = await addUserEvent(state)
        if code == CODE_ADDUSER_ACCOUNT_EXIST:
            await adduser.send(Message(ADDUSER_ACCOUNT_EXIST_PROMPT))
        elif code == CODE_ADDUSER_ACCOUNT_ERROR:
            await adduser.send(Message(ADDUSER_ACCOUNT_ERROR_PROMPT))
        elif code == CODE_ADDUSER_EMAIL_ERROR:
            await adduser.send(Message(ADDUSER_EMAIL_ERROR_PROMPT))
        elif code == CODE_ADDUSER_TOKEN_ERROR:
            await adduser.send(Message(ADDUSER_TOKEN_ERROR_PROMPT))
        else:
            await adduser.send(Message(ADDUSER_SID_PROMPT))
    except Exception as e:
        msg = f"Exception: {Exception}\n"
        msg += f"str(e): {str(e)}\nrepr(e): {repr(e)}\n"
        msg += f"traceback.format_exc(): {traceback.format_exc()}"
        await exception_log(bot, msg)
Esempio n. 13
0
def callModuleAPI(
    method: str, params: Optional[dict] = {}, ignoreError: Optional[bool] = False
) -> Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]:
    """Call CQHTTP's underlying API

    Parameters
    ----------
    method : str
        The name of the method to call
    params : Optional[dict], optional
        Additional parameters for the call, by default {}

    Returns
    -------
    Callable
        The function that called the method
    """
    from .decorators import AsyncToSync

    botObject: NoneBot = get_bot()
    syncAPIMethod = AsyncToSync(botObject.call_action)
    logger.debug(
        "CQHTTP native API is being actively called, "
        + f"data: action={method}, params={str(params):.100s}"
    )
    try:
        return syncAPIMethod(method, **params)
    except ActionFailed as e:
        if ignoreError:
            return
        from .exception import BotMessageError, ExceptionProcess

        raise BotMessageError(
            reason=f"调用API出错,错误码:{e.retcode}", trace=ExceptionProcess.catch()
        )
Esempio n. 14
0
async def _run_matcher(Matcher: Type[Matcher], bot: Bot, event: Event,
                       state: dict) -> Union[None, NoReturn]:
    if Matcher.expire_time and datetime.now() > Matcher.expire_time:
        raise _ExceptionContainer([ExpiredException])

    try:
        if not await Matcher.check_perm(
                bot, event) or not await Matcher.check_rule(bot, event, state):
            return
    except Exception as e:
        logger.error(f"Rule check failed for matcher {Matcher}. Ignored.")
        logger.exception(e)
        return

    # TODO: log matcher
    logger.info(f"Event will be handled by {Matcher}")

    matcher = Matcher()
    # TODO: BeforeMatcherRun
    try:
        logger.debug(f"Running matcher {matcher}")
        await matcher.run(bot, event, state)
    except Exception as e:
        logger.error(f"Running matcher {matcher} failed.")
        logger.exception(e)

    exceptions = []
    if Matcher.temp:
        exceptions.append(ExpiredException)
    if Matcher.block:
        exceptions.append(StopPropagation)
    if exceptions:
        raise _ExceptionContainer(exceptions)
Esempio n. 15
0
async def handle(bot: Bot, event: Event, state: T_State):
    args = state["text"].split(' ')
    logger.debug(args)
    for i in args:
        res = await query(bot, i)
        for j in res:
            await hhsh.send(j)
Esempio n. 16
0
    def parse(self, token: str, preset=None, **placeholders) -> str:
        """
        解析字符串标签,根据风格预设配置信息获取字符串内容,并替换内容中的占位
        符(如果存在)。

        参数:
        - `token: str`:字符串标签。

        关键字参数:
        - `preset: str`:风格预设。默认为项目配置中设置的风格预设,未在配置中设
        置时为 `default`。
        - `**placeholders`:将被替换的占位符及替换内容。

        返回:
        - `str`:根据标签获取的字符串。
        """
        preset = self.preset if not preset else preset
        result = ''

        try:
            strings = self.__load_preset(preset)
            result = self.__token_parse(token, strings)
        except (exception.PresetFileError, exception.ResourcePathError,
                exception.TokenError) as err:
            err.log()
        else:
            if placeholders:
                result = self.__replace_placeholders(result, **placeholders)
            logger.debug(f'Token "{token}" parsed as expected.')

        return result
async def achat(session: CommandSession):
    logger.info('[一言]用户激活指令开始运行')
    aword = session.get('aword')
    logger.debug('[一言]向编译库发送请求获取信息')
    achat_report = await get_achat_of_chat(aword)
    logger.info('[一言]向用户发送运行结果,任务结束')
    await session.send(achat_report,at_sender=True)
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    print("狗屁不通生成器", args)
    logger.debug('开始进行狗屁不通生成器' + args)
    print(type(args))
    if args:
        state["theme"] = args
Esempio n. 19
0
async def handle(bot: Bot, event: Event, state: T_State):
    try:
        user_id = event.get_user_id()
        at_ = "[CQ:at,qq={}]".format(user_id)
        args = str(state["args"]).split()
        if len(args) != 2:
            await query.send(Message(QUERY_ARGS_PROMPT))
        db = pymysql.connect(host=QQMAP_HOST, port=3306, user=QQMAP_USERNAME,
                             passwd=QQMAP_PASSWORD, db="cpds_db", charset='utf8')

        cursor = db.cursor()
        type, key = args
        logger.debug(f'query: {type} {key}')
        if type == '学号':
            qq = await stunum2qq(key, cursor)
            if not qq:
                await query.send(Message(at_ + QUERY_NO_DATA_PROMPT))
            else:
                await query.send(Message(at_ + QUERY_DATA_FORMAT.format(key, qq)))
        elif str(type).lower() == 'qq':
            stunum = await qq2stunum(key, cursor)
            if not stunum:
                await query.send(Message(at_ + QUERY_NO_DATA_PROMPT))
            else:
                await query.send(Message(at_ + QUERY_DATA_FORMAT.format(stunum, key)))
        else:
            await query.send(Message(QUERY_NO_SUCH_TYPE_PROMPT))
        db.close()
        cursor.close()
    except Exception as e:
        msg = f"Exception: {Exception}\n"
        msg += f"str(e): {str(e)}\nrepr(e): {repr(e)}\n"
        msg += f"traceback.format_exc(): {traceback.format_exc()}"
        await exception_log(bot, msg)
Esempio n. 20
0
async def live_sched():
    """直播推送"""

    with Config() as config:
        uids = config.get_uid_list('live')
        if not uids:
            return
        logger.debug(f'爬取直播列表,目前开播{sum(status.values())}人,总共{len(status)}人')
        br = BiliReq()
        r = await br.get_live_list(uids)
        for uid, info in r.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']
                push_list = config.get_push_list(uid, 'live')

                live_msg = f"{name} 开播啦!\n\n{title}\n传送门→{url}\n[CQ:image,file={cover}]\n"
                for sets in push_list:
                    at_msg = '[CQ:at,qq=all] ' if sets['at'] else ''
                    await safe_send(sets['bot_id'], sets['type'],
                                    sets['type_id'], at_msg + live_msg)
            status[uid] = new_status
Esempio n. 21
0
async def handle_rawFuncName(bot: Bot, event: Event, state: T_State):
    rawModuleName = state["rawModuleName"]
    rawFuncName = state["rawFuncName"]
    if not hasattr(__import__(rawModuleName), rawFuncName):
        await itreflection.send(dir(__import__(rawModuleName)))
        await itreflection.reject("模块内只有以上方法!!")
    logger.debug("rawFuncName state recorded")
Esempio n. 22
0
async def handle(bot: Bot, event: Event, state: T_State):
    async with httpx.AsyncClient() as client:
        resp = await client.get('https://api.mtyqx.cn/api/random.php?return=json')
        logger.debug(resp.json())
        imgurl = resp.json()['imgurl']
        # cqimg = f"[CQ:image,file=1.{imgurl.split('.')[1]},url={imgurl}]"
        await setu.send(MessageSegment.image(imgurl))
Esempio n. 23
0
async def get_json(username: str):
    user = {'username': username}
    async with httpx.AsyncClient(verify=False) as client:
        resp = await client.post(ALKAID_TWQD_API, data=user)
    logger.debug(resp)

    return resp.json()
Esempio n. 24
0
async def _(session: CommandSession):
    logger.debug('[升职查询]开始过滤无效字符')
    stripped_arg = session.current_arg_text.replace(' ', '')
    stripped_arg = session.current_arg_text.replace('#', '')
    logger.debug('[升职查询]开始辨别部落代码')
    if f'大部落' in stripped_arg:
        logger.info('[升职查询]用户查询大部落可升职长老,作为参数传入并执行查询脚本')
        session.state['tag'] = 'dbl'
    elif f'小部落' in stripped_arg:
        logger.info('[升职查询]用户查询小部落可升职长老,作为参数传入并执行查询脚本')
        session.state['tag'] = 'xbl'
    elif f'同好会' in stripped_arg:
        logger.info('[升职查询]用户查询同好会信息,取消指令')
        session.finish('很抱歉,同好会暂未开放,无法查询,敬请谅解(ノへ ̄、)')
    elif not session.is_first_run:
        logger.debug('[升职查询]用户二次查询无结果,征求用户意见')
        if (f'嗯' or f'是' or f'继续' or f'还不' or '可以' or f'需要'
                or f'好') in stripped_arg:
            logger.debug('[升职查询]用户希望继续查询,重置指令')
            session.pause('请告诉我你想查询的部落等我消息吧')
        else:
            logger.info('[升职查询]用户放弃查询,取消指令')
            session.finish('你还是想好再来找我查询伸手党吧(⊙ω⊙)')
    else:
        logger.debug('[升职查询]一次查找无结果,重新查询中')
        session.pause('您想要查询什么部落可升职的长老?\n可用参数:大部落、小部落、同好会')
Esempio n. 25
0
async def query(bot: Bot, someShit):
    data = {"text": someShit}
    logger.debug(data)

    async with httpx.AsyncClient() as client:
        resp = await client.post(url, json=data)
        if resp.status_code != 200:
            return ["错误:" + str(resp.status)]
        ShitJson = resp.json()
    logger.debug(ShitJson)
    ans = []
    for RealShit in ShitJson:
        re = ""
        try:
            for i in RealShit["trans"]:
                re += i + "\n"
        except:
            try:
                for i in RealShit["inputting"]:
                    re += i + "\n"
            except:
                pass
        re = re[:-1]
        if re == "":
            ans.append(f"呐呐呐,没有查到 {RealShit['name']} 的相关结果")
        else:
            ans.append(f"""呐,{RealShit['name']} 可能是:
{re}""")

    return ans
Esempio n. 26
0
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(state["text"])
    logger.debug(args)
    db, cursor = await sql.get_connection()
    res = await sql.query_dt(args)
    logger.debug(res)
    await souti.send(Message(res))
    await sql.close()
Esempio n. 27
0
def save_all():
    logger.debug('Saving permissions')
    for k, v in loaded.items():
        try:
            v.save()
        except Exception as e:
            _ = e
            logger.exception('Failed to save namespace {}', k)
Esempio n. 28
0
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    if args:
        state["date"] = args
        logger.debug(args)
    else:
        state["date"] = "0"
        logger.debug("None")
async def luck_test(state: T_State):
    if state["test"] != "":
        test_id = state["test"]
        logger.debug("test" + ": " + test_id)
        await luck.finish(await luck_daily(user_id=int(test_id),
                                           redraw=False,
                                           group_message=group),
                          at_sender=group)
Esempio n. 30
0
async def handle_event(bot: Bot, event: Event, state: T_State):
    at_ = f"[CQ:at,qq={state['qq']}]"
    list = load_data()
    resp = choices(list, k=5)
    # logger.debug(list)
    logger.debug(resp)
    for i in resp:
        await helpmemr.send(Message(at_ + " " + i))