def deco(func) -> Callable: @wraps(func) async def wrapper(session): if session.ctx['message_type'] != 'group': return if not self.check_enabled(session.ctx['group_id']): self.logger.debug( f'Message {session.ctx["message_id"]} is command of a disabled service, ignored.' ) if deny_tip: session.finish(deny_tip, at_sender=True) return if self._check_all(session.ctx): try: ret = await func(session) self.logger.info( f'Message {session.ctx["message_id"]} is handled as command by {func.__name__}.' ) return ret except CanceledException: raise _FinishException except (_PauseException, _FinishException, SwitchException) as e: raise e except Exception as e: self.logger.error( f'{type(e)} occured when {func.__name__} handling message {session.ctx["message_id"]}.' ) self.logger.exception(e) return nonebot.on_command(name, **kwargs)(wrapper)
def deco(func): @wraps(func) async def wrapper(session: nonebot.CommandSession): if await self.check_permission(session.ctx): try: await func(session) self.logger.info( f'Message {session.ctx["message_id"]} is handled as command by {func.__name__}.' ) except (_PauseException, _FinishException, SwitchException) as e: raise e except Exception as e: self.logger.exception(e) self.logger.error( f'{type(e)} occured when {func.__name__} handling message {session.ctx["message_id"]}.' ) return elif deny_tip: await session.send(deny_tip, at_sender=True) self.logger.info( f'Message {session.ctx["message_id"]} is a command of {func.__name__}. Permission denied.' ) return nonebot.on_command(name, **kwargs)(wrapper)
def decorator(func: Callable): matcher = on_command(cmd, **kwargs) @wraps(func) @self._pre_check(only_to_me=only_to_me) async def wrapper(bot: Bot, event: Event, state: T_State): await func(bot, event) logger.info( f'消息{event.get_session_id()}已被on_command处理器{func.__name__}处理。' ) await matcher.finish() return matcher.handle()(wrapper)
def create_matchers(): def create_handler(type: str) -> T_Handler: async def handler(msg: Message = CommandArg()): text = msg.extract_plain_text().strip() await handle(matcher, type, text) return handler for type, params in commands.items(): matcher = on_command(type, aliases=params["aliases"], block=True, priority=13) matcher.append_handler(create_handler(type))
def deco(func) -> Callable: @wraps(func) async def wrapper(session: CommandSession): if session.event.user_id not in hoshino.config.SUPERUSERS: return if force_private and session.event.detail_type != 'private': await session.send('> This command should only be used in a private session.') return try: return await func(session) except (_PauseException, _FinishException, SwitchException): raise except Exception as e: sulogger.error(f'{type(e)} occured when {func.__name__} handling message {session.event.message_id}.') sulogger.exception(e) return nonebot.on_command(name, **kwargs)(wrapper)
def deco(func: MethodCommand_T) -> Callable: @wraps(func) async def wrapped_function(session: CommandSession): from config import BOT_SWITCH, NICKNAME logger.info(need_bot_open) logger.info(BOT_SWITCH) if need_bot_open and not BOT_SWITCH: await session.send(NICKNAME[0] + '没有打开') return cls = get_class_that_defined_method(func) if not cls: raise Exception('cannot resolve class from method') return await func(cls(session)) wrapped_function.is_command = True return on_command(name, aliases=aliases, permission=permission, only_to_me=only_to_me, privileged=privileged, shell_like=shell_like)(wrapped_function)
from nonebot import on_command from nonebot.log import logger from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event from nonebot.adapters.cqhttp import Message from .data_source import get_hand_painting hand_painting = on_command("手绘", rule=to_me(), priority=1) @hand_painting.handle() async def handle(bot: Bot, event: Event, state: T_State): logger.success(f'hand_painting: {event}\n') @hand_painting.got("img", prompt="请发送一张图片") async def handle_hand_painting_got(bot: Bot, event: Event, state: T_State): img = Message(state["img"]) try: if img[0].type == "image": await hand_painting.send("转化中") img_url = await get_hand_painting(img[0].data["url"]) if img_url is None: await hand_painting.send("出错了,请重新开始") else: await hand_painting.send(Message(f'[CQ:image,file={img_url}]')) else: await hand_painting.send("这是啥?") except:
from nonebot import on_keyword, on_command from nonebot.typing import T_State from nonebot.adapters.cqhttp import Message, Bot, Event # 这两个没用的别删 from nonebot.adapters.cqhttp.message import MessageSegment import requests from nonebot.permission import * from nonebot.rule import to_me # matcher = on_keyword({"主人"}) matcher = on_command('主人', rule=to_me(), priority=5) @matcher.handle() async def _(bot: Bot, event: Event, state: T_State): await matcher.send('我主人是川川大帅哥') test = on_keyword({"test"}) @test.handle() 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=8]"#礼物使用 await test.send(MessageSegment.at(id) + '你好帅哥') test = on_keyword({"礼物", '我要礼物', '我也要礼物'}) # test=on_command('礼物',rule=to_me(),priority=5)
花价 api:jx3box """ import httpx import nonebot from nonebot import on_command from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event import asyncio import time import json flower_price = on_command("花价", rule=to_me(), priority=5) @flower_price.handle() async def handle_first_receive(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() if args: if " " in args: # 首先判断文本中间有没有空格 arg_list = args.split(' ') if len(arg_list) == 2: # 当参数为两个时,直接执行 state["server"] = arg_list[0] state["flower"] = arg_list[1] else: await flower_price.finish("参数错误!") else: # 没有空格的话就直接赋值给参数server state["server"] = args
elif mode == "trace": async for msg in get_des_trace(url): yield msg elif mode == "yandex": async for msg in get_des_yandex(url): yield msg elif mode.startswith("asc"): async for msg in get_des_asc(url): yield msg else: async for msg in get_des_sau(url): yield msg setu = on_command("搜图", aliases={"search"}, rule=sv_sw('搜图', plugin_usage), priority=2) @setu.handle() async def handle_first_receive(bot: Bot, event: MessageEvent, state: T_State): msg = event.message if msg: state["setu"] = msg @setu.got("setu", prompt="图呢?") async def get_setu(bot: Bot, event: MessageEvent, state: T_State): msg: Message = Message(state["setu"]) try: for seg in msg:
from nonebot import on_command from nonebot.adapters.cqhttp import Bot from nonebot.adapters.cqhttp.event import MessageEvent from nonebot.typing import T_State from ...database import DB from ...utils import get_type_id, permission_check, to_me sub_list = on_command('关注列表', aliases={ '主播列表', }, rule=to_me(), priority=5) sub_list.__doc__ = """关注列表""" sub_list.handle()(permission_check) @sub_list.handle() async def _(bot: Bot, event: MessageEvent, state: T_State): """发送当前位置的订阅列表""" message = "关注列表(所有群/好友都是分开的)\n\n" async with DB() as db: subs = await db.get_sub_list(event.message_type, get_type_id(event)) for sub in subs: user = await db.get_user(sub.uid) assert user is not None message += (f"{user.name}({user.uid})" f"直播:{'开' if sub.live else '关'}," f"动态:{'开' if sub.dynamic else '关'}," f"全体:{'开' if sub.at else '关'}\n") await sub_list.finish(message)
import re from .config import Config from nonebot import on_command,on_regex,on_notice from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event from nonebot.adapters.cqhttp import Message,MessageSegment,GroupIncreaseNoticeEvent from .data_source import get_words,IsAdded,IsDel # 默认配置 global_config = nonebot.get_driver().config plugin_config = Config(**global_config.dict()) # 响应命令 BDwords = on_command("BDwords", aliases=set(['*/爆点语录','*/BD语录','*/bd语录']), priority=2) Addwords = on_regex("\*/add\n([\s\S]*)\n\*/end") Delwords = on_command("*/del",priority=2) welcom = on_notice() @BDwords.handle() async def handle_first_receive(bot: Bot, event: Event, state: T_State): words = await get_words() await BDwords.finish(Message(words)) @Addwords.handle() async def handle_first_receive(bot: Bot,event: Event, state: T_State): words = re.findall("\*/add\n([\s\S]*)\n\*/end",str(event.get_message())) if IsAdded(words): await Addwords.finish(Message("语录追加成功,爆点世界重构中……"))
from nonebot import on_command from nonebot.matcher import Matcher from nonebot.permission import SUPERUSER from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event from nonebot.adapters.cqhttp import Bot, unescape, MessageEvent, Message, MessageSegment from nonebot.log import logger from .prompt import * from .utils import * from .alioss import * from awesome_bot.config.utils import exception_log # Add To MySQL add = on_command("add", rule=to_me(), priority=1, permission=SUPERUSER) @add.handle() async def handle(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() if args: state["args"] = args @add.got("args", prompt=ADD_ARGS_PROMPT) 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()
from nonebot.adapters.cqhttp import GROUP_ADMIN, GROUP_OWNER from nonebot.adapters.cqhttp import GroupMessageEvent def cpu_status() -> float: return psutil.cpu_percent(interval=1) # type: ignore def per_cpu_status() -> List[float]: return psutil.cpu_percent(interval=1, percpu=True) # type: ignore def memory_status() -> float: return psutil.virtual_memory().percent status = on_command("系统状态", aliases={'status'}, priority=2) @status.handle() async def status_(bot: Bot, event: Event, state: dict): if event.get_user_id != str(event.self_id): mess = 'CPU占用率: ' + str(cpu_status()) + '%\n' + '内存占用率: ' + str( memory_status()) if await GROUP_ADMIN(bot, event): await bot.send(event=event, message='尊贵的管理员:\n' + mess) elif await GROUP_OWNER(bot, event): await bot.send(event=event, message='尊贵的群主:\n' + mess) else: await bot.send(event=event, message='底层群员没有查看权限!一边凉快呆着吧\n')
[{t4}]""" """ 俄罗斯转盘 判断会话状态是否为active 是,则读取子弹数量,开枪次数,命中数。 否,则初始化数据,初始化 子弹数量,开枪次数,命中数。 开始会话 每个人触发几率为子弹数/6-开枪次数 触发命中后,子弹数量-1,开枪次数+1,命中+1,返回命中讯息 触发miss后,子弹数量不变,开枪次数+1,命中不变,返回miss讯息 当命中数=子弹数时,总会话终止,设置会话状态false """ shoot = on_command("开枪", rule=None, priority=2) @shoot.handle() async def _(bot: Bot, event: Event, state: T_State): message_type = str(event.dict()["message_type"]) # 来源判断 if message_type == "group": id = str(event.dict()["group_id"]) elif message_type == "private": id = event.get_user_id() # strmsg = [0, 0, 0, 0] # ru_status = strmsg[0] # bullets_num = strmsg[1] # shoot_times = strmsg[2] # hit_times = strmsg[3]
from .config import Config from nonebot import (on_command, on_message, logger) from nonebot.rule import to_me, startswith from nonebot.adapters import Bot from nonebot.adapters.cqhttp import MessageEvent, Message from nonebot.adapters.cqhttp.message import MessageSegment from .data_source import redis_client add = on_command("add", rule=startswith("add"), priority=5) @add.handle() 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}") del_event = on_command("del", rule=to_me(), priority=5)
from nonebot import on_command from nonebot.adapters.cqhttp import Bot, Event from .run import run runcode = on_command('super', aliases={'run'}) @runcode.handle() async def _(bot: Bot, event: Event): code = str(event.get_message()).strip() res = await run(code) await runcode.send(message='\n' + res, at_sender=True)
import sys import os path = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) sys.path.append(path) from shared import spider from nonebot import on_command from nonebot.matcher import Matcher from nonebot.adapters.onebot.v11 import Message, MessageSegment from nonebot.params import CommandArg matcher = on_command("翻译", aliases={"trans"}, priority=2) @matcher.handle() async def PushAnswer(matcher: Matcher, msg: Message = CommandArg()): matcher.stop_propagation() if (str(msg) == ""): await matcher.finish(Message("? 翻译啥呢")) page_text = await spider.GetPage( "https://www.youdao.com/w/" + str(msg) + r"/", "get") answers = [] l1 = await spider.ParsePage( page_text, "/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[1]/div/p/text()") l2 = await spider.ParsePage( page_text, "/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[1]/div[2]/ul/li/text()"
url_msg = '订阅用户%s开播了~\n' % status['name'] share_msg = '[CQ:share,url=%s,title=订阅用户%s开播了~,content=%s]' % ( status['live_room_url'], status['name'], status['live_title']) message = url_msg + share_msg # post the subscribe message await bot.send_group_msg(group_id=group_id, message=message) subscribed_list.pop(uid) # pop the first item in the subscribed list subscribed_list[uid] = status[ 'live_status'] # update the live status and move the item to the end save(universal_id, 'subscribed_list', subscribed_list) save('0', 'global_subscribed_list', global_subscribed_list) subscriber = on_command(cmd='subscribe ', aliases={'订阅用户 '}, rule=check('bilipush')) @subscriber.handle() async def subscriber_update(bot: Bot, event: Event, state: dict): """Handle the subscribe command.""" universal_id = str(event.self_id) + str(event.group_id) subscribed_list = load(universal_id, 'subscribed_list') if not subscribed_list: subscribed_list = {} save(universal_id, 'subscribed_list', subscribed_list) operation = { '+': lambda x: subscribed_list.setdefault(x, False), '-': lambda x: subscribed_list.pop(x),
# Author: BeiYu # Github: https://github.com/beiyuouo # Date : 2021/1/14 21:01 # Description: import httpx from nonebot import on_command from nonebot.adapters.cqhttp import Message from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event from nonebot.log import logger setu = on_command("setu", aliases=set(['瑟图', '色图', '来张色图', '来张瑟图']), rule=to_me(), priority=1) @setu.handle() async def handle(bot: Bot, event: Event, state: T_State): at_ = "[CQ:at,qq={}]".format(event.get_user_id()) 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(Message(at_ + cqimg))
from nonebot import on_command from nonebot.adapters.cqhttp import Bot, Message, GroupMessageEvent, PrivateMessageEvent from .getPic import get_almanac_base64_str almanac = on_command('黄历', aliases={'原神黄历'}) @almanac.handle() async def _(bot: Bot, event: GroupMessageEvent): ba = get_almanac_base64_str() await almanac.send(Message(f'[CQ:image,file={ba}]')) @almanac.handle() async def _(bot: Bot, event: PrivateMessageEvent): ba = get_almanac_base64_str() await almanac.send(Message(f'[CQ:image,file={ba}]'))
rank_file_list = ['tf.png', 'tm.png', 'tb.png'] @scheduler.scheduled_job('cron', hour=15) async def _(): layout = await query_rank_sheet_from_yuni('台前中后rank') if len(layout) < 3: return for i, data in enumerate(layout): file_content = data['data']['file'].replace('base64://', '') image = Image.open(BytesIO(base64.b64decode(file_content))) image.save(path.join(path.dirname(__file__), rank_file_list[i])) def get_rank_def(filename: str): async def temp_func(session: CommandSession): filepath = path.join(path.dirname(__file__), filename) if path.exists(filepath): await session.finish(f'[CQ:image,file=file:///{filepath}]') else: await session.finish(f'{filename} not found') return temp_func command_list = ['前卫rank', '中卫rank', '后卫rank'] for i, command in enumerate(command_list): on_command(command, only_to_me=False)(get_rank_def(rank_file_list[i]))
import sys import os path=os.path.dirname(os.path.dirname(os.path.dirname(__file__))) sys.path.append(path) from shared import spider from nonebot import on_command from nonebot.matcher import Matcher from nonebot.adapters.onebot.v11 import Message matcher=on_command("热搜",aliases={"hot"},priority=2) @matcher.handle() async def PushAnswer(matcher: Matcher): matcher.stop_propagation() page_text =await spider.GetPage("https://top.baidu.com/board?tab=realtime","get") titles= await spider.ParsePage(page_text,'/html/body/div/div/main/div[2]/div/div[2]/div/div[2]/a/div[1]/text()') await matcher.send("====百度热搜榜Top30====") res="" for i in range(30): res+=Message(f"{i+1}. {titles[i]}\n") await matcher.finish(res)
from nonebot import on_command from nonebot.typing import T_State from nonebot.adapters import Bot, Event from nonebot.permission import Permission import re import httpx character = on_command("人物", rule=None, permission=Permission(), priority=5) @character.handle() async def _(bot: Bot, event: Event, state: T_State): stripped_arg = str(event.get_message()).strip() # 去掉消息首尾的空白符 if stripped_arg: state["character"] = stripped_arg print("character") @character.got("character", prompt='123') async def receive(bot: Bot, event: Event, state: T_State): char = state["character"] char_id = await get_character_id(char) info = await call_eve_esi(char_id) corporation_name, alliance_name, char, security = await esi_info_convert( info) char_info = await data_process(corporation_name, alliance_name, char, security) await character.send(char_info)
import json from nonebot import on_command from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters.cqhttp import Bot, Event from nonebot.adapters import Event jj_cx = on_command("cx", rule=to_me(), priority=1) @jj_cx.handle() async def handle1(bot: Bot, event: Event, state: T_State): userid = str(event.get_user_id()) jjcx = await read_data(userid) await jj_cx.finish(jjcx) async def read_data(userid): data_file = "/root/testbot/testbot/plugins/jjconfig/" data_file = data_file + userid + '/data.json' with open(data_file, encoding='utf-8') as f: data = json.load(f) return data
from nonebot import on_command from nonebot.log import logger from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event from .data_source import get_yourls yourls = on_command("yourls", aliases={"短链接"}, rule=to_me(), priority=1) @yourls.handle() async def handle(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() logger.success(f'yourls: {event}\n') if args: state["yourls"] = args @yourls.got("yourls", prompt="请输入链接") async def handle_weather_got(bot: Bot, event: Event, state: T_State): url = await get_yourls(state['yourls']) if url: await yourls.send(url) # await yourls.send(Message( # f'[CQ:share,url={data["url"]},title={data["title"]},content={data["content"]},image={data["image"]}]')) else: await yourls.send("转换短链接失败")
from nonebot import on_command from nonebot.plugin import require from nonebot.adapters.cqhttp import Bot, Event from datetime import datetime, timedelta import requests import json import re import copy export = require("tools") Translate = export.translate DeltaStr = export.deltastr nightwave = on_command("电波") @nightwave.handle() async def _(bot: Bot, event: Event): try: response = requests.get(url="https://api.warframestat.us/pc/nightwave") data = json.loads(response.text) nodes = [] node = { "type": "node", "data": { "uin": f"{bot.self_id}", "name": "ZANUKA" } } for i in data["activeChallenges"]: content = "——————————"
from nonebot import on_command from nonebot.rule import to_me from nonebot.adapters.cqhttp import Bot, Event, MessageSegment import random import requests import lxml from bs4 import BeautifulSoup import json import os import platform from christinaqqbot.utils.rule import _gruop_white_list waifu = on_command('waifu', rule=to_me() & _gruop_white_list) def save_pic(pic_url): pic_name = pic_url.split('/')[-1] try: r = requests.get(url=pic_url) except Exception: raise Exception with open('./pic/' + pic_name, 'wb') as f: f.write(r.content) f.close() return pic_name @waifu.handle() async def _(bot: Bot, event: Event, state: dict) -> None:
from nonebot import on_command from nonebot.adapters.cqhttp import Bot from nonebot.adapters.cqhttp.event import MessageEvent from nonebot.typing import T_State from ...database import DB from ...utils import get_type_id, permission_check, to_me, handle_uid dynamic_off = on_command('关闭动态', rule=to_me(), priority=5) dynamic_off.__doc__ = """关闭动态 UID""" dynamic_off.handle()(permission_check) dynamic_off.handle()(handle_uid) @dynamic_off.got('uid', prompt='请输入要关闭动态的UID') async def _(bot: Bot, event: MessageEvent, state: T_State): """根据 UID 关闭动态""" async with DB() as db: if await db.set_sub('dynamic', False, uid=state['uid'], type_=event.message_type, type_id=get_type_id(event)): user = await db.get_user(state['uid']) assert user is not None await dynamic_off.finish(f"已关闭 {user.name}({user.uid})的动态推送") await dynamic_off.finish(f"UID({state['uid']})未关注,请先关注后再操作")
from nonebot import on_command from nonebot.adapters.cqhttp import Bot from nonebot.adapters.cqhttp.event import MessageEvent from nonebot.typing import T_State from ...database import DB from ...utils import permission_check, to_me, get_type_id from ...libs.bilireq import BiliReq, RequestError add_sub = on_command('关注', aliases={ '添加主播', }, rule=to_me(), priority=5) add_sub.__doc__ = """关注 UID""" add_sub.handle()(permission_check) @add_sub.handle() async def get_args(bot: Bot, event: MessageEvent, state: T_State): args = str(event.message).strip() if args: state['uid'] = args @add_sub.got('uid', prompt='请输入要关注的UID') async def _(bot: Bot, event: MessageEvent, state: T_State): """根据 UID 订阅 UP 主""" uid = state['uid'] async with DB() as db: user = await db.get_user(uid)