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
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}" )
def load_config(filename): try: with open(filename, encoding='utf8') as f: config = json.load(f) return config except Exception as e: logger.exception(e) return {}
async def delete_msg(ev: MessageEvent): try: bot = get_bots().get(str(ev.self_id)) if isinstance(bot, Bot): await bot.delete_msg(message_id=ev.message_id, self_id=ev.self_id) except ActionFailed as e: logger.error(f'撤回失败 retcode={e.retcode}') except Exception as e: logger.exception(e)
async def set_unban(bot: Bot, event: Event): try: args = event.get_plaintext().strip().split() group_id, user_id = args[:2] await bot.set_group_ban(group_id=int(group_id), user_id=int(user_id), duration=0, self_id=event.self_id) await bot.send(event, '解除成功') except Exception as e: logger.exception(e) await bot.send(event, f'发生错误{e}')
async def delete_msg(ctx): try: if get_bot().config.IS_CQPRO: msg_id = ctx['message_id'] await get_bot().delete_msg(self_id=ctx['self_id'], message_id=msg_id) except ActionFailed as e: logger.error(f'撤回失败 retcode={e.retcode}') except Exception as e: logger.exception(e)
def cqcode(self) -> MessageSegment: if global_config.RES_PROTOCOL == 'http': return MessageSegment.image(self.url) elif global_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: logger.exception(e) return MessageSegment.text('[图片出错]')
async def load_json_file(filename: str) -> Dict[str, Any]: """读取json文件""" global CONFIG_PATH try: with open(os.path.join(CONFIG_PATH, filename), "r", encoding="utf-8") as f: res = json.load(f) return res except FileNotFoundError: logger.info(f"找不到文件{filename}") except Exception as e: logger.exception(e) return {}
def load_config(inbuilt_file_var): """ Just use `config = load_config(__file__)`, you can get the config.json as a dict. """ filename = os.path.join(os.path.dirname(inbuilt_file_var), 'config.json') try: with open(filename, encoding='utf8') as f: config = json.load(f) return config except Exception as e: logger.exception(e) return {}
async def silence(ev: GroupMessageEvent, ban_time: int, skip_su: bool = True): try: if skip_su and ev.user_id in global_config.superusers: return bot = get_bots().get(str(ev.self_id)) if isinstance(bot, Bot): await bot.set_group_ban(group_id=ev.group_id, user_id=ev.user_id, duration=ban_time, self_id=ev.self_id) except ActionFailed as e: logger.error(f'禁言失败 retcode={e.retcode}') except Exception as e: logger.exception(e)
async def get_single_continuation(text: str): try: result = '' for i in range(3): # 连续续写三次 nid = await get_nid(text) xid = await submit_to_ai(text, nid) logger.info(f'正在等待服务器返回第{i+1}段续写结果') continuation = await poll_for_result(nid, xid) result += text + random.choice(continuation) logger.info('续写完成') return result except Exception as e: logger.error(f'发生错误{e}') logger.exception(e) return f'发生错误{e}'
def download_icon(url: str, target: str): """从url中下载图标""" save_path = target logger.info(f'正在从{url}下载图标...') try: rsp = requests.get(url, stream=True, timeout=5) if 200 == rsp.status_code: img = Image.open(BytesIO(rsp.content)) img.save(save_path) logger.info(f'图标已保存到{save_path}') else: logger.error(f'从{url}下载失败。HTTP {rsp.status_code}') except Exception as e: logger.error(f'从{url}下载失败。{type(e)}') logger.exception(e)
def download_chara_icon(id_, star): url = f'https://redive.estertion.win/icon/unit/{id_}{star}1.webp' save_path = R.img(f'priconne/unit/icon_unit_{id_}{star}1.png').path logger.info(f'Downloading chara icon from {url}') try: rsp = requests.get(url, stream=True, timeout=5) except Exception as e: logger.error(f'Failed to download {url}. {type(e)}') logger.exception(e) if 200 == rsp.status_code: img = Image.open(BytesIO(rsp.content)) img.save(save_path) logger.info(f'Saved to {save_path}') else: logger.error(f'Failed to download {url}. HTTP {rsp.status_code}')
async def silence(ctx, ban_time, ignore_super_user=False): try: self_id = ctx['self_id'] group_id = ctx['group_id'] user_id = ctx['user_id'] bot = get_bot() if ignore_super_user or user_id not in bot.config.SUPERUSERS: await bot.set_group_ban(self_id=self_id, group_id=group_id, user_id=user_id, duration=ban_time) except ActionFailed as e: logger.error(f'禁言失败 retcode={e.retcode}') except Exception as e: logger.exception(e)
async def weibo_poller(): bot = nonebot.get_bot() for account in accounts: try: result = await poll_new_weibo(account['name'], int(account['uid']), int(account['container_id'])) if len(result) != 0: logger.info(f"成功获取@{account}的新微博") for group in push_group: try: await bot.send_group_msg(group_id=group, message=result[0]) except CQHttpError: pass else: logger.info(f"未检测到@{account}的新微博") except Exception as e: logger.exception(e) logger.error(f"获取@{account}的微博时出现异常{type(e)}")
1068, # 晶 1069, # 霸瞳 1072, # 可萝爹 1073, # 拉基拉基 1102, # 泳装大眼 } try: gadget_equip = R.img('priconne/gadget/equip.png').open() gadget_star = R.img('priconne/gadget/star.png').open() gadget_star_dis = R.img('priconne/gadget/star_disabled.png').open() gadget_star_pink = R.img('priconne/gadget/star_pink.png').open() unknown_chara_icon = R.img( f'priconne/unit/icon_unit_{UNKNOWN}31.png').open() except Exception as e: logger.exception(e) class Roster: def __init__(self): self._roster = pygtrie.CharTrie() self.update() def update(self): importlib.reload(_pcr_duel_data) self._roster.clear() for idx, names in _pcr_duel_data.CHARA_NAME.items(): for n in names: n = util.normalize_str(n) if n not in self._roster: self._roster[n] = idx