async def test_require_not_declared(app: App): import nonebot from nonebot.plugin import _managers nonebot.require("plugins.export") assert len(_managers) == 1 assert _managers[-1].plugins == {"plugins.export"}
async def test_require_not_found(app: App): import nonebot from nonebot.plugin import _managers try: nonebot.require("some_plugin_not_exist") assert False except RuntimeError: assert True
async def test_require_loaded(app: App, monkeypatch: pytest.MonkeyPatch): import nonebot def _patched_find(name: str): assert False monkeypatch.setattr("nonebot.plugin.load._find_manager_by_name", _patched_find) nonebot.load_plugin("plugins.export") nonebot.require("plugins.export")
async def execute(code: str, language: str, user_id: int): if language == "js": language = "node.js" if "sql" not in language: async with aiohttp.ClientSession() as session: data = { "code": code, "token": "4381fe197827ec87cbac9552f14ec62a", "stdin": "", "language": language_map[language], "fileext": language } async with session.post("https://tool.runoob.com/compile2.php", data=data, headers=headers) as resp: data = await resp.json() print(data) return data["output"], data["errors"] else: # super mysql if user_id not in config.superusers or not config.navicat_execute_sql: return "", "" try: export = require("nonebot_plugin_navicat") if export is None: return "", "" pool_name = language + "_pool" if pool_name in export: rows = await export[pool_name].fetch_all(code) rows = list(map(list, rows)) return json.dumps(rows, ensure_ascii=False), "" except Exception: return "", traceback.format_exc()
async def test_require_not_loaded(app: App, monkeypatch: pytest.MonkeyPatch): import nonebot from nonebot.plugin import PluginManager, _managers m = PluginManager(["plugins.export"]) _managers.append(m) origin_load = PluginManager.load_plugin def _patched_load(self: PluginManager, name: str): assert self is m return origin_load(self, name) monkeypatch.setattr(PluginManager, "load_plugin", _patched_load) nonebot.require("plugins.export") assert len(_managers) == 1
async def check_data(): global cachepath, config cachepath = os.path.join(os.getcwd(), "cache", "simdraw") try: with open(os.path.join(cachepath, "config.json"), "r", encoding="utf-8") as f: config = json.load(f) nonebot.require("nonebot_plugin_simdraw").draw = sim_draw nonebot.logger.info("simdraw init success") except: nonebot.logger.info("config.json not found")
async def shutdown(): from nonebot import require scheduler = require('nonebot_plugin_apscheduler').scheduler if scheduler.running: scheduler.shutdown() if platform.system() == "Linux": from waveshare_epd import epd1in54 epd = epd1in54.EPD() epd.init(epd.lut_full_update) epd.Clear(0xFF) img = Image.new("1", (200, 200), 0xFF) draw = ImageDraw.Draw(img) draw.rectangle((0, 0, 199, 199), outline=0x00) draw.text((33, 33), "Good\nNight", fill=0x00, font=font_50) epd.display(epd.getbuffer(img))
# -*- coding: utf-8 -*- """ @Author : yanyongyu @Date : 2020-09-20 23:59:20 @LastEditors : yanyongyu @LastEditTime : 2021-03-15 23:10:18 @Description : GitHub Main Plugin @GitHub : https://github.com/yanyongyu """ __author__ = "yanyongyu" from pathlib import Path import nonebot from redis import Redis from .config import Config # quote with double quotes to use generic typing provided by pylance redis: "Redis[bytes]" = nonebot.require("redis_provider").redis # store all github subplugins _sub_plugins = set() # load all github plugin config from global config github_config = Config(**nonebot.get_driver().config.dict()) _sub_plugins |= nonebot.load_plugins( str((Path(__file__).parent / "plugins").resolve())) from . import apis
message = MessageSegment.at('all') + message try: return await bot.call_api('send_'+send_type+'_msg', **{ 'message': message, 'user_id' if send_type == 'private' else 'group_id': type_id }) except ActionFailed as e: url = "https://haruka-bot.sk415.icu/usage/faq.html#机器人不发消息也没反应" logger.error(f"推送失败,账号可能被风控({url}),错误信息:{e.info}") except NetworkError as e: logger.error(f"推送失败,请检查网络连接,错误信息:{e.msg}") def get_type_id(event: MessageEvent): return (event.group_id if isinstance(event, GroupMessageEvent) else event.user_id) scheduler = require('nonebot_plugin_apscheduler') assert scheduler is not None scheduler = scheduler.scheduler # bot 启动时检查 src\data\haruka_bot\ 目录是否存在 if not Path(get_path()).is_dir(): Path(get_path()).mkdir(parents=True) from . import patch from .browser import get_dynamic_screenshot
from nonebot.rule import T_State from nonebot import on_command, require from nonebot.adapters.cqhttp import Bot, MessageEvent from .data_source import get_anime_res, ReplyMessage separate_trigger = require("rules").separate_trigger anime_res = on_command("资源", rule=separate_trigger, aliases={"动漫资源"}) @anime_res.handle() async def anime_res_handle(bot: Bot, event: MessageEvent, state: T_State): state["res"] = None text = event.get_plaintext() if text: state["res"], msg = await get_anime_res(anime_res, text) await anime_res.send(msg) else: await anime_res.send("请输入资源名称也可以添加关键字,注意名称与关键字空格分隔。\n例如:天气之子或天气之子 mkv") @anime_res.got("msg") async def anime_res_got(bot: Bot, event: MessageEvent, state: T_State): text = event.get_plaintext() if state["res"]: await state["res"].reply_magnet(text) else: if text: state["res"], msg = await get_anime_res(anime_res, text) await anime_res.reject(msg) await anime_res.reject("请输入资源名称!")
from nonebot import require from plugins.export import test from .export import test as test_related test_require = require("export").test assert test is test_related and test is test_require, "Export Require Error"
from aiohttp import ClientSession from bs4 import BeautifulSoup from .config import Config from datetime import datetime from nonebot import require, get_driver from typing import Optional, Union readfile = require("readfile") read_data = readfile.read_data write_data = readfile.write_data config = Config() async def get(url, headers): async with ClientSession() as session: async with session.get(url, headers=headers) as reply: return BeautifulSoup(await reply.read(), features="html.parser") class AnimeNews: def __init__(self): self.html = None def __await__(self): return self.get_html().__await__() async def get_html(self): self.html = await get(config.main_url, config.headers) return self def ranking(self):
# -*- coding = utf-8 -*- from nonebot import on_command from nonebot import require from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event import requests weather_scheduler = require('nonebot_plugin_apscheduler').scheduler weather_start = on_command("开启每日天气", rule=to_me(), priority=5) weather_stop = on_command("关闭每日天气", rule=to_me(), priority=5) #city = {} push_group_list = [] push_friend_list = [] calltime = [] @weather_start.handle() async def weather_start_puse(bot: Bot, event: Event, state: T_State): if len(calltime) == 0: calltime.append('0') weather_scheduler.add_job(weather_puse, 'cron', minute='00, 15, 30, 45', args=[bot], misfire_grace_time=600) des = event.get_event_description() des = des.split(' ')[3].split('@') msg = str(event.get_message()) if len(des) == 1:
from typing import Union from random import choice from .config import Config from nonebot import require from datetime import datetime from nonebot.adapters.cqhttp import Bot, GroupIncreaseNoticeEvent, GroupDecreaseNoticeEvent,\ Message, MessageSegment config = Config() read_config = require("readfile").read_config GroupNoticeEvent = Union[GroupDecreaseNoticeEvent, GroupIncreaseNoticeEvent] class ReplyMessage: typeof: str def __init__(self, bot: Bot, event: GroupNoticeEvent): self.bot = bot self.event = event self.config = {} async def set_config(self): self.config = await read_config(config.file_path) # 需要格式化字符 async def format_keys(self, more: dict = None) -> dict: more = more or {} return { "uid": self.event.user_id, "gid": self.event.group_id, "oid": self.event.operator_id,
import nonebot from nonebot.adapters import Bot, Event import pytz import datetime import aiohttp import asyncio from nonebot.adapters.cqhttp import Message from nonebot.log import logger from apscheduler.schedulers.asyncio import AsyncIOScheduler from awesome_bot.config.config import * from nonebot import require scheduler = require("nonebot_plugin_apscheduler").scheduler def getBot() -> Bot: print(nonebot.get_bots()) print(nonebot.get_bots().values()) print(list(nonebot.get_bots().values())) print(len(list(nonebot.get_bots().values()))) return list(nonebot.get_bots().values())[0] @scheduler.scheduled_job('cron', hour='*', minute='10') async def _(): tz = pytz.timezone('Asia/Shanghai') nowtime = datetime.datetime.now(tz).strftime("%H:%M")
import aiohttp from json import loads from nonebot import require from .config import Config from random import choice config = Config() base_url = "http://i.itpk.cn/api.php" read_data = require("readfile").read_data def get_params(msg: str): return { "question": msg, "limit": 8, "api_key": "1447d08d8e018247e2ce829e9d0380e8", "api_secret": "p782g4wij4b0" } async def get_message_reply(msg: str): async with aiohttp.ClientSession() as session: async with session.get(url=base_url, params=get_params(msg)) as resp: try: text = loads((await resp.text()).encode("utf-8")) try: return text["content"] except KeyError: return "抱歉,为对数据进行整理目前无法使用" except ValueError: return await resp.text()
def __init__(self, game_type): """Initialize the manager.""" self.scheduler = nonebot.require( 'nonebot_plugin_apscheduler').scheduler self.game_type = game_type self.invoker = {}
import re import datetime from config import bot_id, masterList from costrule import check_white_list_all, check_white_list_group, only_master from nonebot import get_bots, get_driver, on_command, require from nonebot.adapters.cqhttp import Bot, Event from nonebot.adapters.cqhttp.message import Message from nonebot.adapters.cqhttp.event import GroupIncreaseNoticeEvent, GroupMessageEvent from nonebot.plugin import on_message, on_notice global memdic memdic = {} LogPath = os.path.join(os.getcwd(), 'DataBase', 'Json', 'datalog.json') StartTime = datetime.datetime.now() scheduler = require('nonebot_plugin_apscheduler').scheduler # 定义计划任务 water = on_command("water", priority=5, rule=check_white_list_all()) # 定义water查询命令 resetLog = on_command("resetLog", priority=5, rule=only_master()) # 定义手动重置模块 writeLog = on_message(rule=check_white_list_group(), priority=5) # 定义吹氵记录增加 addLog = on_notice(priority=5) # 定义群成员变动 async def get_water_list(groupID, bot): linedic = memdic[str(groupID)] findic = reversed( sorted(linedic.items(), key=lambda kv: (kv[1], kv[0]))) a = 0 pa = "-------氵怪排行榜-------" for elem in findic: UQID = elem[0]
import uuid import re import requests import time import nonebot def pingbi(event: Event) -> bool: goup_id = event.dict().get('group_id') if goup_id: if str(goup_id) in ['389410891']: return True return False export = nonebot.require("nonebot_plugin_navicat") clien = export.redis_client # redis的 setu = on_regex("^st$|^cu$|^涩图$|^来站涩图$") @setu.handle() async def setu_rev(bot: Bot, event: Event, state: dict): if pingbi(event): return path_prefix = "/root/QQbotFiles/img/" img_list = await get_img_list(path_prefix) if not img_list: await setu.finish("色图库已经空了") else: rd.seed(time.time())
import nonebot from apscheduler.schedulers.asyncio import AsyncIOScheduler from nonebot import require from .config import Config global_config = nonebot.get_driver().config # nonebot.logger.info("global_config:{}".format(global_config)) plugin_config = Config(**global_config.dict()) # nonebot.logger.info("plugin_config:{}".format(plugin_config)) # 加载官方定时任务插件 scheduler = require( "nonebot_plugin_apscheduler").scheduler # type:AsyncIOScheduler # 发送时间 times = [{"hour": 12, "min": 30}, {"hour": 21, "min": 59}] async def send_everyday(): message1 = "阳哥看学习强国啊!" # 给qq好友发消息 for qq in plugin_config.npd_qq_friends: await nonebot.get_bot().send_private_msg(user_id=qq, message="") # 给群发消息 for qq_group in plugin_config.npd_qq_groups: await nonebot.get_bot().send_group_msg( group_id=qq_group, message="[CQ:at,qq={}]{}".format(1163113511, message1)) # 调试
sys.path.insert(0, os.path.abspath("..")) import nonebot from nonebot.log import logger, default_format # test custom log logger.add("error.log", rotation="00:00", diagnose=False, level="ERROR", format=default_format) nonebot.init(custom_config2="config on init") app = nonebot.get_asgi() # load builtin plugin nonebot.load_builtin_plugins() # load local plugins nonebot.load_plugins("test_plugins") print(nonebot.require("test_export")) # modify some config / config depends on loaded configs config = nonebot.get_driver().config config.custom_config3 = config.custom_config1 config.custom_config4 = "New custom config" if __name__ == "__main__": nonebot.run(app="bot:app")
from random import choice from nonebot import require from datetime import datetime from yaml import load, FullLoader from typing import Union from .config import Config config = Config() bot_db = require("botdb").BotDBMethods() read_config = require("readfile").read_config def get_days(__datetime: datetime, to_datetime: datetime = None) -> int: if __datetime: to_datetime = to_datetime if to_datetime else datetime.today() return (__datetime.date() - to_datetime.date()).days return 1 def is_month(__datetime: datetime, to_datetime: datetime = None) -> bool: """ 判断是否为本月 """ if __datetime: to_datetime = to_datetime if to_datetime else datetime.today() return __datetime.month == to_datetime.month return False class GetUserInfo: table = "user_info"
from nonebot import require from .send import do_send_msgs from .platform.utils import fetch_and_send from apscheduler.schedulers.asyncio import AsyncIOScheduler scheduler: AsyncIOScheduler = require('nonebot_plugin_apscheduler').scheduler @scheduler.scheduled_job('interval', seconds=10) async def weibo_check(): await fetch_and_send('weibo') @scheduler.scheduled_job('interval', seconds=10) async def bilibili_check(): await fetch_and_send('bilibili') @scheduler.scheduled_job('interval', seconds=30) async def rss_check(): await fetch_and_send('rss') @scheduler.scheduled_job('interval', seconds=1) async def _(): await do_send_msgs()
__author__ = "yanyongyu" from pathlib import Path from datetime import timedelta from typing import List, Optional import markdown from nonebot import require from src.libs import html2img from src.libs.github import Github from ... import github_config as config from src.libs.github.models import Issue from src.libs.playwright import get_new_page cache = require("redis_provider").cache async def get_issue(owner: str, repo_name: str, number: int, token: Optional[str] = None) -> Issue: if token: g = Github(token) elif config.github_client_id and config.github_client_secret: g = Github(config.github_client_id, config.github_client_secret) else: g = Github() try: repo = await g.get_repo(f"{owner}/{repo_name}", True)
policy into the memory, but not saved into the policy file on disk. """ import json import os import nonebot from nonebot.log import logger from nonebot.adapters.cqhttp import Bot, Event, GroupMessageEvent from nonebot.rule import Rule from .config import PolicyConfig global_config = nonebot.get_driver().config plugin_config = PolicyConfig(**global_config.dict()) policy_config_location = os.path.join(os.getcwd(), plugin_config.policy_config_location) scheduler = nonebot.require('nonebot_plugin_apscheduler').scheduler try: with open(policy_config_location, 'r', encoding='utf-8') as f: policy_config = json.loads(f.read()) logger.info('Policy file is loaded ...') logger.debug('Policy control data: %s' % policy_config) except Exception: policy_config = {} logger.warning('Failed to load policy file, using empty policy file ...') def valid(command_name: str) -> list: """Get all valid [bot_id, group_id] tuple for policy control.""" return [(bid, gid) for bid in policy_config.keys() for gid in policy_config[bid].keys()
async def test_require_not_found(app: App): import nonebot with pytest.raises(RuntimeError): nonebot.require("some_plugin_not_exist")