def command(self, name: Union[str, CommandName_T], *, aliases: Optional[Union[Iterable[str], str]] = None, permission: Optional[int] = None, only_to_me: Optional[bool] = None, privileged: Optional[bool] = None, shell_like: Optional[bool] = None) -> Callable: """ Decorator to register a function as a command. Its has the same usage as `on_command`. :param kwargs: keyword arguments will be passed to `on_command`. For each argument in the signature of this method here, if it is not present when calling, default value for the command group is used (e.g. `self.permission`). If that value is also not set, default value for `on_command` is used. """ sub_name = (name, ) if isinstance(name, str) else name name = self.basename + sub_name kwargs_tup = ( ('name', name), ('aliases', aliases), ('permission', permission if permission is not None else self.permission), ('only_to_me', only_to_me if only_to_me is not None else self.only_to_me), ('privileged', privileged if privileged is not None else self.privileged), ('shell_like', shell_like if shell_like is not None else self.shell_like)) kwargs = {k: v for k, v in kwargs_tup if v is not None} return on_command(**kwargs)
def command(self, name: Union[str, CommandName_T], **kwargs) -> Callable: sub_name = (name, ) if isinstance(name, str) else name name = self.basename + sub_name final_kwargs = self.base_kwargs.copy() final_kwargs.update(kwargs) return on_command(name, **final_kwargs)
def command(self, name: Union[str, CommandName_T], **kwargs) -> Callable[[CommandHandler_T], CommandHandler_T]: """ Decorator to register a function as a command. Its has the same usage as `on_command`. :param kwargs: keyword arguments will be passed to `on_command`. For each argument in the signature of this method here, if it is not present when calling, default value for the command group is used (e.g. `self.permission`). If that value is also not set, default value for `on_command` is used. """ sub_name = (name, ) if isinstance(name, str) else name name = self.basename + sub_name final_kwargs = {**self.base_kwargs, **kwargs} return on_command(name, **final_kwargs)
def on_fullmatch(self, name: str, only_to_me: bool = False, aliases: Optional[Iterable] = None, only_group: bool = True, **kwargs) -> "matcher_wrapper": if isinstance(aliases, str): aliases = set([aliases]) elif not isinstance(aliases, set): if aliases: aliases = set([aliases]) if len(aliases) == 1 and isinstance( aliases, tuple) else set(aliases) else: aliases = set() kwargs['aliases'] = aliases rule = self.check_service(only_to_me, only_group) kwargs['rule'] = rule priority = kwargs.get('priority', 1) mw = matcher_wrapper(self, 'Message.command', priority, command=name, only_group=only_group) matcher = on_command(name, **kwargs) mw.load_matcher(matcher) self.matchers.append(str(mw)) _loaded_matchers[mw.matcher] = mw return mw
from nonebot.plugin import on_command import salmon from salmon import Bot, priv from salmon.service import parse_gid from salmon.typing import CQEvent, T_State, PrivateMessageEvent, GroupMessageEvent from salmon.modules.authMS import util from salmon.modules.authMS.group import check_auth from salmon.modules.authMS.constant import config quick_check = on_command('快速检查') admin_help = on_command('管理员帮助') query_time = on_command('查询授权') @quick_check.handle() async def quick_check_chat(bot: Bot, event: CQEvent): ''' 立即执行一次检查, 内容与定时任务一样 ''' if event.user_id not in salmon.configs.SUPERUSERS: return await check_auth() await quick_check.finish('检查完成') @admin_help.handle() async def master_help_chat(bot: Bot, event: CQEvent): if isinstance(event, PrivateMessageEvent): if event.user_id not in salmon.configs.SUPERUSERS: await admin_help.finish('权限不足') await admin_help.finish(config.ADMIN_HELP)
from functools import reduce from nonebot.rule import to_me from nonebot.plugin import on_command from nonebot.permission import SUPERUSER from nonebot.typing import Bot, Event, MessageSegment say = on_command("say", to_me(), permission=SUPERUSER) @say.handle() async def say_unescape(bot: Bot, event: Event, state: dict): Message = event.message.__class__ def _unescape(message: Message, segment: MessageSegment): if segment.type == "text": return message.append(str(segment)) return message.append(segment) message = reduce(_unescape, event.message, Message()) # type: ignore await bot.send(message=message, event=event) echo = on_command("echo", to_me()) @echo.handle() async def echo_escape(bot: Bot, event: Event, state: dict): # Message = event.message.__class__ # MessageSegment = event.message[0].__class__
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"] super_ = on_command("bash") @super_.handle() async def handle_super_(bot: Bot, event: Event, state: dict): language, code = str(event.message).split("\n", 1) language: str = language.strip() if code: # print(code) stdout, stderr = await execute(code, language) if temp := stdout.strip(): await bot.send(event, temp) if temp := stderr.strip(): await bot.send(event, temp)
Author : DiheChen Date : 2021-01-05 01:35:52 LastEditors : DiheChen LastEditTime : 2021-01-05 02:42:20 Description : None GitHub : https://github.com/Chendihe4975 ''' from nonebot.plugin import on_command from nonebot.typing import T_State from loguru import logger from nonebot.adapters.cqhttp.message import Message from nonebot.exception import ActionFailed from nonebot.adapters import Bot, Event from yuudi.util import FreqLimiter, DailyNumberLimiter setu = on_command( "setu", aliases={"色图", "涩图", "来点色图", "来点涩图", "看过了", "不够色", "就这", "铜"}) setudlmt = DailyNumberLimiter(30) setuflmt = FreqLimiter(15) def get_setu(): return f"[CQ:image,cache=0,file=https://michikawachin.art/]" @setu.handle() async def push_setu(bot: Bot, event: Event, state: T_State): user_id = event.user_id if not setudlmt.check(user_id): await setu.send("您今天已经冲了10次了, 雨滴很担心你, 还是明天再冲吧。") if not setuflmt.check(user_id):
rec.repeat_count += 1 if rec.repeat_count == 2: if msg not in repeat_data: repeat_data[msg] = 1 else: repeat_data[msg] += 1 with open(RECORD, 'w') as file: ujson.dump(repeat_data, file) delay = randint(5, 20) / 10 await asyncio.sleep(delay) await repeater.finish(msg) repeater_rank = on_command("frank", aliases={"复读榜"}) @repeater_rank.handle() async def _(bot: Bot, event: Event, state: dict): rank = sorted(repeat_data.items(), key=lambda kv: (kv[1], kv[0]), reverse=True) msg = "------+++复读榜+++------\n" size = 3 if len(rank) > 3 else len(rank) for i in range(size): if i != size - 1: msg += str(i) + ". " + rank[i][0] + " 被复读了足足 " + str( rank[i][1]) + " 次!\n" else: msg += str(i) + ". " + rank[i][0] + " 被复读了足足 " + str(
import copy from nonebot.plugin import on_command from nonebot.adapters.cqhttp import Bot, Event from nonebot.plugin import require from fuzzywuzzy import fuzz import requests from bs4 import BeautifulSoup export = require("tools") WF_Dict = export.dict WF_Riven = export.riven rm = on_command("rm", aliases={"RM"}) @rm.handle() async def _(bot: Bot, event: Event): try: item = event.get_message().__str__().strip() if item == "": await rm.send("参数不能为空!") return #相似度匹配 index = 0 similar = 0 for i in range(len(WF_Dict)): flag = True for j in WF_Riven: if WF_Dict[i]["en"] == j["name"]: flag = False
from nonebot.plugin import on_command, 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 voidtrader = on_command("奸商") @voidtrader.handle() async def _(bot: Bot, event: Event): # try: response = requests.get(url="https://api.warframestat.us/pc/voidTrader") data = json.loads(response.text) if not data["active"]: content = "距离 " + data["character"] + " 到达 " + Translate( data["location"], "dict") + " 中继站还有 " utcTime = datetime.strptime(data["activation"], "%Y-%m-%dT%H:%M:%S.%fZ") timeLeft = utcTime + timedelta(hours=8) - datetime.now() content += DeltaStr(timeLeft) await voidtrader.send(content) else: nodes = [] node = {
# @Time : 2020/12/8 20:03 # @Author : QingWen # @E-mail : [email protected] from random import choice from nonebot.adapters.cqhttp import Bot, Event from nonebot.plugin import on_command from nonebot.log import logger from src.utils.rules import is_banned from .location_parser import location_parse from .report_getter import location_get, report_get from . import expression as e weather = on_command("weather", aliases={"天气"}, rule=is_banned(), block=True) @weather.handle() async def _(bot: Bot, event: Event, state: dict): args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 if args: state["location"] = args @weather.got("location", prompt=choice(e.WHERE)) async def _(bot: Bot, event: Event, state: dict): location = await location_parse(state["location"]) location_found = await location_get(location) if location_found: state["location"] = location_found
from datetime import datetime from nonebot.adapters.cqhttp import Bot, Event from nonebot.plugin import on_command, on_metaevent from nonebot.permission import SUPERUSER from nonebot.log import logger from nonebot import require from nonebot.message import run_preprocessor from src.utils.scheduler_job.throughput_counter import ThroughPut from src.utils.scheduler_job.epd_drawer import epd_updater, epd_start_screen counter = 0 boot_time = datetime(1970, 1, 1) status = on_command("status", permission=SUPERUSER, block=True) @status.handle() async def _(bot: Bot, event: Event, state: dict): try: py_info = platform.python_version() pla = platform.platform() cpu = psutil.cpu_percent() memory = psutil.virtual_memory().percent memory = round(memory, 2) except Exception: # ignore await status.finish("获取状态失败!") return msg = r""" __ _ _
import random import os import re import datetime import aiohttp from config import lolicon_api, masterList, setu_path from httpx import AsyncClient from nonebot import get_driver from nonebot.adapters.cqhttp import Bot from nonebot.adapters.cqhttp.event import (Event, GroupMessageEvent, PrivateMessageEvent) from nonebot.adapters.cqhttp.message import Message from nonebot.plugin import on_command, on_regex global last_time_command, last_time_Rrandom, resetTime command_setu = on_command("setu", priority=5, rule=check_white_list_all()) regex_setu_random = on_regex( pattern=r'^[来整]点[涩色活好康][的图儿]$|^[色涩]图来$|^冲[亿1一]发$|^冲$|^[色涩黄]图$') regex_setu_search = on_regex( pattern=r'^[来整]点.\S*[色涩黄]图$|^[来整][几.\S*][张份个]\S*[色涩黄]图$') last_time_command, last_time_Rrandom, resetTime = '', '', True download_urls = [] word_to_int = { "一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5, "六": 6,
import nonebot.adapters.cqhttp.permission as cpermission from nonebot.plugin import on_command from .config import Config from .constants import InteractionMessage, DBStatusCode from . import BossDB global_config = nonebot.get_driver().config plugin_config = Config(**global_config.dict()) boss_database = BossDB.BossDB(Path().cwd().joinpath( plugin_config.company_storage).joinpath( plugin_config.company_record).joinpath('CompanyRevue.db')) helper = on_command(cmd='help_boss', aliases={'boss管理'}, priority=10) add_boss = on_command(cmd='add_boss', aliases={'添加boss', 'ab'}, permission=permission.SUPERUSER | cpermission.GROUP_OWNER | cpermission.GROUP_ADMIN, priority=1) add_boss_range = on_command(cmd='add_boss_range', aliases={'添加boss组', 'abr'}, permission=permission.SUPERUSER | cpermission.GROUP_OWNER | cpermission.GROUP_ADMIN, priority=1) remove_boss = on_command(cmd='remove_boss',
from nonebot.plugin import on_command from nonebot.typing import T_State from nonebot.adapters.feishu import Bot as FeishuBot, MessageEvent helper = on_command("say") @helper.handle() async def feishu_helper(bot: FeishuBot, event: MessageEvent, state: T_State): message = event.get_message() await helper.finish(message, at_sender=True)
data = { "code": code, "token": "4381fe197827ec87cbac9552f14ec62a", "stdin": "", "language": 17, "fileext": "lua" } 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"] super_lua = on_command("super lua") @super_lua.handle() async def handle_lua(bot: Bot, event: Event, state: dict): # print(type(asyncio.get_running_loop())) # assert isinstance(asyncio.get_running_loop(), asyncio.ProactorEventLoop) if code := str(event.message): stdout, stderr = await execute_lua(code) if temp := stdout.strip(): await bot.send(event, temp) if temp := stderr.strip(): await bot.send(event, temp) if __name__ == "__main__":
from .constants import InteractionMessage from . import data_source from . import MemberManager, BossManager, RecordManager, TeamManager from nonebot.plugin import on_command bot_driver = nonebot.get_driver() bot_driver.on_startup(lambda: data_source.init_database( str(Path.cwd().joinpath('Data/Company').joinpath('ORMTest').joinpath( 'Revue.db')))) # test_message_helper = on_command('test_message', aliases={'tm'}, priority=10) overall_helper = on_command(cmd='help', aliases={'帮助'}, priority=10) clear_db = on_command(cmd='EMPTY', permission=permission.SUPERUSER, priority=1) @overall_helper.handle() async def helper_handler(bot: cqhttp.Bot, event: cqhttp.Event, state: typing.T_State): await overall_helper.finish(InteractionMessage.OVERALL_HELPER) @clear_db.handle() async def clearance(bot: cqhttp.Bot, event: cqhttp.Event, state: typing.T_State): db_file = Path.cwd().joinpath('Data/Company').joinpath('ORMTest').joinpath( 'Revue.db')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from nonebot.rule import to_me from nonebot.typing import Event from nonebot.plugin import on_command from nonebot.adapters.cqhttp import Bot test_command = on_command("帮助", to_me()) @test_command.handle() async def test_handler(bot: Bot, event: Event, state: dict): print("[!] Command:", state["_prefix"]) args = str(event.message)[len(state["_prefix"]):].strip() if args: state["help"] = args else: await bot.send_private_msg(message="命令:\n1. test1\n2. test2", user_id=event.user_id) @test_command.got("help", prompt="你要帮助的命令是?") async def test_handler(bot: Bot, event: Event, state: dict): print("[!] Command 帮助:", state["help"]) if state["help"] not in ["test1", "test2"]: await bot.send_private_msg(message=f"{state['help']} 不支持,请重新输入!") test_command.reject() await bot.send_private_msg(message=f"{state['help']} 帮助:\n...")
"ext": "rs" }, "scala": { "ext": "scala" }, "swift": { "ext": "swift" }, "typescript": { "ext": "ts" }, } api_token = global_config.glot_key coderunner = on_command("code_runner", aliases={"run", "运行代码", "运行", "执行代码"}, priority=5) @coderunner.handle() async def _(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() if args: state['args'] = args language, *remains = state['args'].split("\n", maxsplit=1) language = language.strip() if language not in SUPPORTED_LANGUAGES: await coderunner.finish("暂时不支持运行你输入的编程语言") state["language"] = language
import nonebot from nonebot.plugin import on_message, on_command from nonebot.rule import to_me, Rule from nonebot.typing import T_State from nonebot.adapters.mirai import Bot, Event, MessageSegment from .config import Config global_config = nonebot.get_driver().config plugin_config = Config(**global_config.dict()) manual = on_message(rule=to_me(), priority=99) help = on_command('help', priority=98) @manual.handle() async def manual_handle(bot: Bot, event: Event, state: T_State): await manual.finish(plugin_config.about) @help.handle() async def help_handle(bot: Bot, event: Event, state: T_State): args = str(event.get_message()).strip() if args == "r": await help.finish(plugin_config.help_r) elif args == "check": await help.finish(plugin_config.help_check) elif args == "choose": await help.finish(plugin_config.help_choose) elif args == "daily": await help.finish(plugin_config.help_daily)
from nonebot.rule import to_me from nonebot.plugin import on_command from nonebot.typing import Bot, Event say = on_command("say", to_me()) @say.handle() async def repeat(bot: Bot, event: Event, state: dict): await bot.send(message=event.message, event=event)
from nonebot.plugin import on_command, 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 alerts = on_command("警报") @alerts.handle() async def _(bot: Bot, event: Event): try: response = requests.get(url="https://api.warframestat.us/pc/alerts") data = json.loads(response.text) if not len(data): await alerts.send("目前无警报") return nodes = [] node = { "type": "node", "data": { "uin": f"{bot.self_id}", "name": "ZANUKA" } }
with open(LV, 'w') as file: ujson.dump(data, file) await notice_handler.finish(msg) elif event.sub_type == "talkative": img_path = Path("./images/long_wang.jpg").resolve() msg = { "type": "image", "data": { "file": f"file:///{str(img_path)}" } } await notice_handler.finish(msg) nmsl = on_command("嘴臭", aliases={"口臭", "开骂"}, rule=to_me(), block=True) count_list_n = [] @nmsl.handle() async def _(bot: Bot, event: Event, state: dict): user = str(event.user_id) count = counter(count_list_n, user) if 6 > count > 3: await bot.send(event, "还,还要吗?!") api = config["shadiao"]["zui_chou"] if count < 7: count_list_n.append(user) async with httpx.AsyncClient() as client: response = await client.get(api)
# @File : __init__.py.py # @Time : 2020/12/10 9:49 # @Author : QingWen # @E-mail : [email protected] import ujson from pathlib import Path from nonebot.adapters.cqhttp import Bot, Event from nonebot.log import logger from nonebot.plugin import on_command from nonebot.permission import SUPERUSER from src.utils.func_switch import func_switcher switch = on_command("switch", permission=SUPERUSER) @switch.handle() async def _(bot: Bot, event: Event, state: dict): group = str(event.group_id) args = str(event.message).strip() if not args: msg = """--+Welcome Contro1-C+-- Type in switch {func_name} on/off to switch func for group switch {func-name} all-on/off to swtich func for all""" await switch.finish(msg)
from nonebot.plugin import on_keyword, on_command from nonebot.rule import to_me from nonebot.adapters.mirai import Bot, MessageEvent message_test = on_keyword({'reply'}, rule=to_me()) @message_test.handle() async def _message(bot: Bot, event: MessageEvent): text = event.get_plaintext() await bot.send(event, text, at_sender=True) command_test = on_command('miecho') @command_test.handle() async def _echo(bot: Bot, event: MessageEvent): text = event.get_plaintext() await bot.send(event, text, at_sender=True)
import json import re from pathlib import Path from nonebot import get_driver from nonebot.adapters.cqhttp import GROUP_ADMIN, GROUP_OWNER, Bot, GroupMessageEvent from nonebot.permission import SUPERUSER from nonebot.plugin import on_command from alisabot.utils.rule import plugin_control global_config = get_driver().config superusers = global_config.superusers switch = on_command('/switch', permission=(SUPERUSER | GROUP_OWNER | GROUP_ADMIN)) @switch.handle() async def _(bot: Bot, event: GroupMessageEvent) -> None: user = str(event.user_id) group = str(event.group_id) func = str(event.message).strip() switch_path = Path('.') / 'alisabot' / 'data' / 'switch.json' with open(switch_path, 'r') as f: data = json.load(f) funclist = [] for i in data: funclist.append(i) if not func: msg = "现在注册控制的功能有:"
from loguru import logger from nonebot import get_driver from nonebot.adapters import Event, Message, MessageTemplate from nonebot.adapters.onebot.v11 import MessageEvent as OneBot_V11_MessageEvent from nonebot.exception import ActionFailed from nonebot.params import CommandArg from nonebot.permission import Permission from nonebot.plugin import on_command from nonebot.typing import T_State from ujson import loads as loadJsonS from ._permission import onFocus config = get_driver().config translate = on_command("翻译", aliases={"机翻"}) @translate.permission_updater async def _(event: Event) -> Permission: return await onFocus(event) async def getReqSign(params: dict) -> str: common = { "Action": "TextTranslate", "Region": f"{getattr(config, 'tencentcloud_common_region', 'ap-shanghai')}", "Timestamp": int(time()), "Nonce": randint(1, maxsize), "SecretId": f"{getattr(config, 'tencentcloud_common_secretid', '')}", "Version": "2018-03-21",
text, at_sender=True, ) except: try: await setu.send("呀,发送色图详情失败辣,。,") except: pass try: if pic != None: await setu.send(pic) except: await setu.send("呀,发送失败辣,。,") act = on_command("act", priority=1) @act.handle() async def firsthandle(bot: Bot, event: Event, state: dict): await act.finish(unescape(cq.image("activity.jpg"))) stCome = on_message(rule=ckimg("b407f708a2c6a506342098df7cac4a57.image")) @stCome.handle() async def pre(bot: Bot, event: Event, state: dict): if event.detail_type == "group": safe = await cksafe(event.group_id) else:
# config = Config(**global_config.dict()) push_list = [] start_time = [] bot_list = [] # @start.on_bot_connect() # async def connect(bot: Bot): # if len(bot_list) != 0: # bot_list.pop() # bot_list.append(bot) # # await bot.send_msg(user_id=2902993382, mssage='connect') push_schedule = AsyncIOScheduler() push_start_event = plugin.on_command('开启天气预报', rule=to_me(), priority=19) push_stop_event = plugin.on_command('关闭天气预报', rule=to_me(), priority=19) @push_start_event.handle() async def push_start(bot: Bot, event: Event, state: T_State): push_infor = Push_information() state['push_infor'] = push_infor des = event.get_event_description() des = des.split(' ')[3].split('@') args = str(event.get_message()).strip() # msg = str(event.get_message()) if len(des) == 1: for i in push_list: