Exemplo n.º 1
0
async def _(session: CommandSession):
    stripped_arg_raw = session.current_arg_text.strip()  # 清除空格
    if stripped_arg_raw == "谢谢":
        session.finish("查询已结束")
    stripped_arg = re.split(r'\s+', stripped_arg_raw)  # 将输入的关键词按空格分割
    logger.debug("The keyword is splited to" + str(stripped_arg))

    if session.is_first_run:
        if stripped_arg[-1]:
            session.state['keyword'] = stripped_arg  # 将关键词赋给session
        return
    if not stripped_arg_raw:
        session.pause('请重新输入')
    try:
        if session.state['name']:
            pass
    except:
        session.state['name'] = None
    if not session.state['name']:
        session.state['keyword'] = stripped_arg
    elif len(stripped_arg) == 1 and re.match(r'\d+$', stripped_arg_raw):
        if int(stripped_arg_raw) > len(session.state['name']):
            session.pause('超出上限,请重新输入')
        session.state['final'] = session.state['name'][int(stripped_arg_raw) -
                                                       1]
    else:
        session.pause('请重新输入')
Exemplo n.º 2
0
    def store(cls, exceptionTime: float, exceptionStack: str) -> str:
        """Store a caught exception

        Parameters
        ----------
        exceptionTime : float
            Timestamp when the exception occurred
        exceptionStack : str
            Exception stack

        Returns
        -------
        str
            Unique ID used to identify the exception
        """
        stackID: str = token_hex(4).upper()
        storeDir: str = cls._getRecursivePath(f"{stackID}.json", makeDir=True)
        exceptionInfo: dict = {
            "stack_id": stackID,
            "time": exceptionTime,
            "time_format": time.strftime("%c %z",
                                         time.localtime(exceptionTime)),
            "stack": exceptionStack,
        }
        with open(storeDir, "wt", encoding="utf-8") as f:
            f.write(
                json.dumps(exceptionInfo,
                           ensure_ascii=False,
                           indent=4,
                           sort_keys=True))
        logger.debug(f"Has been saved Error Stack file {storeDir}, " +
                     f"content:{exceptionInfo}")
        return stackID
Exemplo n.º 3
0
async def get_name_of_data(keywords: list):
    '''
    输入参数为数组,内容为搜索关键词。
    '''
    connection = pymysql.connect(host='127.0.0.1',
                                 user='******',
                                 password='******',
                                 db='pathfinder',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    logger.debug(keywords)
    try:
        sql = ''
        with connection.cursor() as cursor:
            for i, subtitle in enumerate(keywords):
                args = '%' + subtitle + '%'
                if i == 0:
                    sql += "select * from data where name like '%s'" % args
                else:
                    sql += "and name like '%s'" % args
            cursor.execute(sql)
            result = cursor.fetchall()
            logger.debug(len(result))
        connection.commit()
    finally:
        connection.close()
        return result
Exemplo n.º 4
0
    def render_image(self, view='', bg=False, width=500, **kwargs):
        from config import TEMPLATES_ROOT, DATA_ROOT, DATA_URL
        # files and url
        tpl_file = path.join(TEMPLATES_ROOT, f'{view}.mako')
        img_file = path.join(DATA_ROOT, f'{view}.jpg')
        css_file = path.join(TEMPLATES_ROOT, 'css/bootstrap.min.css')
        img_url = DATA_URL + f'/{view}.jpg'
        # render template
        view = Template(filename=tpl_file,
                        input_encoding='utf-8',
                        output_encoding='utf-8',
                        lookup=self.template_lookup)
        kwargs.update({'data_url': DATA_URL, 'cover': bg})
        html_str = view.render(**kwargs).decode('utf-8')
        logger.debug(f"image_available: {self.image_available}")
        if self.image_available:
            # output

            config = imgkit.config(
                wkhtmltoimage=file_config.wkhtmltoimage_path)
            # imgkit.from_string(html_string, output_file, config=config)
            imgkit.from_string(html_str,
                               output_path=img_file,
                               css=css_file,
                               options={'crop-w': width},
                               config=config)
            # return cq code
            return f'[CQ:image,cache=0,file={img_url}]'
        else:
            soup = BeautifulSoup(html_str, 'html5lib')
            msg = re.sub(r'\n+', '\n', soup.body.text.strip().replace(' ', ''))
            return msg
Exemplo n.º 5
0
async def _(session: NLPSession):
    # 去掉消息首尾的空白符
    await check_group(session)
    stripped_msg = session.msg_text.strip()
    logger.debug(stripped_msg)
    if stripped_msg[:2] == '押马':
        return IntentCommand(90.0, 'bet', current_arg=stripped_msg[2:])
Exemplo n.º 6
0
 def __init__(self, user_id):
     logger.debug(f'NUser({user_id}) init')
     self.session = Session()
     # 是 coolq 的 user_id ,实际上是 qq 号
     self.user_id = user_id
     self._user: User = User.first(qq=self.user_id, session=self.session)
     self.nuid = self._user.id if self._user else None
Exemplo n.º 7
0
async def _(session: NLPSession):

    # 检查用户是否在黑名单
    get_blacklist_SQL = '''SELECT * from blacklist'''
    cursor.execute(get_blacklist_SQL)
    blacklist = []
    fetch_result = cursor.fetchall()

    # 唉,这写的什么玩意
    for record in fetch_result:
        blacklist.append(record[0])

    if int(session.ctx['user_id']) in blacklist:
        logger.debug('用户在黑名单中,忽略')
        return

    cursor.execute('''SELECT * FROM rules''')
    rules = cursor.fetchall()
    message = session.msg_text
    if not message:
        return
    reply_list = []

    for rule in rules:
        pattern = rule[1]
        reply = rule[2]
        if re.match(message, pattern) or pattern in message:
            reply_list.append(reply)
        pass

    if reply_list:
        await session.send(choice(reply_list))
    else:
        logger.debug('没有匹配的规则,忽略')
Exemplo n.º 8
0
async def setu(bot: Bot, event: Event):
    """随机叫一份涩图,对每个用户有冷却时间"""
    uid = event.get_user_id()
    if not _nlmt.check(uid):
        await bot.send(event, EXCEED_NOTICE, at_sender=True)
        return
    if not _flmt.check(uid):
        await bot.send(event, '您冲得太快了,请稍候再冲', at_sender=True)
        return
    _flmt.start_cd(uid)
    _nlmt.increase(uid)

    # conditions all ok, send a setu.
    try:
        logger.debug('开始从网络爬取图片。')
        pic = await get_web_img()
    except Exception as e:
        logger.error(f"爬取网络图片失败,将从本地选择。({e})")
        pic = get_local_setu()

    try:
        if pic:
            await bot.send(event, pic.cqcode)
    except Exception as e:
        logger.error(f"发送图片{pic.path}失败")
        logger.exception(e)
        try:
            await bot.send(event, '涩图太涩,发不出去勒...')
        except:
            pass
Exemplo n.º 9
0
def batchSend():
    global _IMAGE_LIST_CACHE
    _IMAGE_LIST_CACHE = None
    logger.debug("Begin to start daily greeting")
    groupsList = [i["group_id"] for i in callModuleAPI("get_group_list")]
    successSend = 0
    for groupID in groupsList:

        enabled = PluginManager._getSettings(__plugin_name__,
                                             type="group",
                                             id=groupID).status
        if not enabled:
            continue
        try:
            callModuleAPI(
                "send_msg",
                params={
                    "group_id": groupID,
                    "message": timeTelling()
                },
            )
        except Exception:
            eid = ExceptionProcess.catch()
            logger.exception(
                f"Failed to greeting in group {groupID},traceback id:{eid}")
        else:
            successSend += 1
    logger.info(
        f"Daily greeting finished,total send:{len(groupsList)},success:{successSend}"
    )
Exemplo n.º 10
0
async def user_check(session: CommandSession):
    qq = session.ctx['user_id']
    group_id = session.ctx['group_id']
    id = 0
    money = 0
    help_cnt = 10

    mysql_operate = MysqlOp()
    await mysql_operate.init_mysql()
    user_row = await mysql_operate.select_one(
        "select * from user "
        "where qq = %s and qq_group_id = %s",
        (qq, group_id)
    )

    logger.debug(user_row)

    if user_row is None:
        await mysql_operate.op_sql(
            "insert into user(qq, qq_group_id) "
            "values (%s, %s)",
            (qq, group_id)
        )
        id = mysql_operate.cur.lastrowid
    else:
        id = user_row['id']
        money = user_row['money']
        help_cnt = user_row['help_count']

    return id, money, qq, help_cnt
Exemplo n.º 11
0
async def live_db_upgrade():
    logger.debug('live_db_upgrade: started upgrade subscription info')
    t = DBTable(table_name='Subscription')
    for item in t.list_col_with_condition('sub_id', 'sub_type', 1).result:
        sub_id = int(item[0])
        sub = DBSubscription(sub_type=1, sub_id=sub_id)
        _res = await get_live_info(room_id=sub_id)
        if not _res.success():
            logger.error(
                f'live_db_upgrade: 获取直播间信息失败, room_id: {sub_id}, error: {_res.info}'
            )
            continue
        up_uid = _res.result.get('uid')
        _res = await get_user_info(user_uid=up_uid)
        if not _res.success():
            logger.error(
                f'live_db_upgrade: 获取直播间UP用户信息失败, room_id: {sub_id}, error: {_res.info}'
            )
            continue
        up_name = _res.result.get('name')
        _res = sub.add(up_name=up_name)
        if not _res.success():
            logger.error(
                f'live_db_upgrade: 更新直播间信息失败, room_id: {sub_id}, error: {_res.info}'
            )
            continue
    logger.debug('live_db_upgrade: upgrade subscription info completed')
Exemplo n.º 12
0
 def wrapper(*args, **kwargs):
     global _MODIFED, _CACHE
     if _MODIFED:
         if _CACHE:
             _SettingsIO.write(_CACHE)
         _CACHE = _SettingsIO.read()
         logger.debug(f"Plugin configuration has been updated:{_CACHE}")
         _MODIFED = False
     return function(*args, **kwargs)
Exemplo n.º 13
0
def _(session: NLPSession):
    message = htmlUnescape(str(session.event.message))
    searchResult = MATCH_RICH_TEXT.search(message)
    if not searchResult:
        return
    logger.debug(f"Catch miniprogram {searchResult}")
    return IntentCommand(100,
                         name="miniprogram_extract",
                         args={"data": searchResult.group(1)})
Exemplo n.º 14
0
 def wrapper(*args, **kwargs):
     functionName = _getFunctionName(function)
     startTime = time() * 1000
     try:
         return function(*args, **kwargs)
     finally:
         runningCost = (time() * 1000) - startTime
         logger.debug(
             f"Function {functionName} cost {runningCost:.3f}ms." +
             f"args={str(args):.100s}...,kwargs={str(kwargs):.100s}...")
Exemplo n.º 15
0
async def fflogs_cache():
    """ 定时缓存数据
    """
    bosses = get_bosses_info()
    jobs = get_jobs_info()
    for boss in bosses:
        for job in jobs:
            await API.dps(boss.name, job.name)
            logger.debug(f'{boss.name} {job.name}的数据缓存完成。')
            await asyncio.sleep(30)
Exemplo n.º 16
0
async def update(record: Record, group_id: str):
    logger.debug(group_id)
    mysql_operate = MysqlOp()
    await mysql_operate.init_mysql()
    for k, v in record.user_list.items():
        await mysql_operate.op_sql(
            "update user set money = money + %s "
            "where qq = %s and qq_group_id = %s",
            (v[2], k, group_id)
        )
Exemplo n.º 17
0
 def wrapper(*args, **kwargs):
     for _ in range(retries if retries else 1):
         try:
             return function(*args, **kwargs)
         except RequestException as error:
             traceID = ExceptionProcess.catch()
             logger.debug(f"Function {functionName} encountered" +
                          f'a network request error: "{error}"')
             if isinstance(error, HTTPError):
                 break
     raise BotRequestError(prompt, traceID)
Exemplo n.º 18
0
def check(bot: Bot, event: Event, perm: str) -> bool:
    if c.flexperm_debug_check:
        logger.debug('Checking {}', perm)
    for group in iterate_groups(bot, event):
        r = group.check(perm)
        if c.flexperm_debug_check:
            logger.debug('Got {} from {}', r, group)
        if r is not None:
            return r == CheckResult.ALLOW

    return False
Exemplo n.º 19
0
def _(session: NLPSession):
    groupRate = PluginManager.settings(__plugin_name__,
                                       ctx=session.ctx).settings["rate"]
    randomNum, msgID = randint(0, groupRate - 1), session.ctx["message_id"]
    groupID = session.ctx.get("group_id")
    if not groupID:
        return
    logger.debug(
        f"Chat {groupID} has a repeat probability of {1/groupRate:.3%}." +
        f"The random number of the current session {msgID} is {randomNum}.")
    if not randomNum:
        return session.msg, False
Exemplo n.º 20
0
async def _(bot: Bot, event: MessageEvent):
    stripped_arg = event.raw_message.split()[1:]
    logger.debug(f"{stripped_arg}, {len(stripped_arg)}")
    if len(stripped_arg) < 2:
        await add.finish("输入错误")
        return
    key, word = stripped_arg[0], stripped_arg[-1]
    res = await redis_client.srem(key, word)
    if res == 1:
        await del_event.finish("如果你不想听我就不说了")
    else:
        await del_event.finish("我可不想忘记[CQ:face,id=14]")
Exemplo n.º 21
0
async def nuannuan(session: CommandSession):
    url = "http://nuannuan.yorushika.co:5000/"
    r = await aiorequests.get(url=url, timeout=5)
    data = await r.json()
    logger.debug(data)
    if data["success"]:
        msg = data.get("content", "default content")
        msg += "\nPowered by 露儿[Yorushika]"
    else:
        msg = "Error"

    await session.send(msg)
Exemplo n.º 22
0
async def random_repeater(context):
    msg = str(context['message'])
    logger.debug(msg)
    if "晚安" in msg:
        random_num = 1000 + random.randint(1, 126)

        img_path = path.join(path.dirname(path.dirname(__file__)), 'res',
                             'meat',
                             str(random_num) + '.gif')

        msg = "[CQ:image,file=file:///{}]\n".format(img_path)
        msg = msg.strip()
        await bot.send(context, msg)
Exemplo n.º 23
0
async def blacklist(session: CommandSession):
    logger.debug('执行添加黑名单指令')
    args = session.args['argv']

    try:
        assert len(args) == 1
        id = int(args[0])
    except (AssertionError, ValueError):
        await session.send('参数错误')
        return

    add_blacklist(id)
    await session.send('黑名单已添加' + ' ' + str(id))
Exemplo n.º 24
0
async def start():
    try:
        rss = rss_class.Rss('', '', '-1', '-1')
        rss_list = rss.read_rss()  # 读取list
        if not rss_list:
            raise Exception('第一次启动,你还没有订阅,记得添加哟!')
        for rss_tmp in rss_list:
            if not rss_tmp.stop:
                await tr.add_job(rss_tmp)  # 创建检查更新任务
        logger.info('ELF_RSS 订阅器启动成功!')
        # hash_clear()
    except Exception as e:
        logger.info('第一次启动,你还没有订阅,记得添加哟!')
        logger.debug(e)
Exemplo n.º 25
0
async def _(bot: Bot, event: MessageEvent):
    stripped_arg = event.raw_message.split()[1:]
    logger.debug(f"{stripped_arg}, {len(stripped_arg)}")
    if len(list(stripped_arg)) < 2:
        await add.finish("输入错误")
        return
    elif stripped_arg[-1] == '帅':
        await add.finish('咕咕鸟从来不骗人, 不能说这句')
        return
    else:
        keyword, sentence = stripped_arg[0], ''.join(
            str(i) for i in stripped_arg[1:])
        await redis_client.sadd(keyword, sentence)
        await add.finish(f"你说: {keyword}, 我说: {sentence}")
Exemplo n.º 26
0
async def dynamic_db_upgrade():
    logger.debug('dynamic_db_upgrade: started upgrade subscription info')
    t = DBTable(table_name='Subscription')
    for item in t.list_col_with_condition('sub_id', 'sub_type', 2).result:
        sub_id = int(item[0])
        sub = DBSubscription(sub_type=2, sub_id=sub_id)
        _res = await get_user_info(user_uid=sub_id)
        if not _res.success():
            logger.error(f'获取用户信息失败, uid: {sub_id}, error: {_res.info}')
        up_name = _res.result.get('name')
        _res = sub.add(up_name=up_name)
        if not _res.success():
            logger.error(f'dynamic_db_upgrade: 更新用户信息失败, uid: {sub_id}, error: {_res.info}')
            continue
    logger.debug('dynamic_db_upgrade: upgrade subscription info completed')
Exemplo n.º 27
0
async def game_check(session: CommandSession) -> bool:
    group_id = session.ctx['group_id']
    record = records.get(group_id)  # 查找是否有原来的游戏信息

    logger.debug(record)

    # 如果没有就说明比赛还没开始
    if record is None:
        return False, None
    # 再寻找比赛信息
    if record.is_start:
        await anonymous_check(session)
        return True, record
    else:
        return False, record
Exemplo n.º 28
0
async def blacklist(session: CommandSession):
    logger.debug('执行添加黑名单指令')
    args = session.args['argv']

    try:
        assert len(args) == 1
        id = int(args[0])
    except (AssertionError, ValueError):
        await session.send('参数错了呢~')
        return
    try:
        add_blacklist(id)
    except sqlite3.IntegrityError:
        session.send('是这个人吗? ' + str(id) + ' 之前说过啦')
        return
    await session.send('原来 ' + str(id) + ' 是坏人吗,不听ta说话了')
Exemplo n.º 29
0
async def talk_del(session: CommandSession):
    logger.debug('执行删除命令')
    args = session.args['argv']
    try:
        assert len(args) == 2
        pattern = args[0]
        reply = args[1]
    except AssertionError:
        session.send('参数错了呢~')

    try:
        del_rule(pattern, reply=reply)
    except Exception:
        await session.send('你说的这个我没有听说过呢')
        return
    await session.send('好吧好吧,删除这一条' + ' ' + pattern + ' ' + reply)
Exemplo n.º 30
0
async def end_game(session: CommandSession, record: Record):
    """
    比赛结束后的结算函数
    :param session:
    :param record:
    :return:
    """
    logger.debug('游戏结束')
    res = '本场赛马已结束!\n'
    res += '\n'.join(f'第{v}名:{k + 1}号马!' for k, v in record.rank.items())
    res += '\n现在开始结算...'
    await session.send(res)
    # 下面是清算相关函数
    await calcu(record)
    await update(record, session.ctx['group_id'])
    await session.send('已结算!')
    records.pop(session.ctx['group_id'])