コード例 #1
0
ファイル: utils.py プロジェクト: nightingu/damebot
    def build_help(self, *help_prefixes, priority_delta=0, recursive=True, **help_args):
        logger.info(f"building help for '{self.cmd}' using '{self.help_short_async_factory.__name__}:{self.help_short}' and '{self.help_long_async_factory.__name__}:{self.help_long}'")
        priority = self.help_priority + priority_delta
        if len(help_prefixes) == 0:
            help_prefixes = ["help"]
        all_commands_combined = [help_name + ("" if self.cmd is None else f" {self_name}") for self_name in self.cmd_in_dice for help_name in help_prefixes]
        main_command, *aliases = all_commands_combined
        aliases = set(aliases)
        sub_matchers = None
        if recursive:
            sub_matchers = [child_cmd.build_help(*help_prefixes, priority_delta=priority_delta-1, recursive=recursive, **help_args) for child_cmd in self.sub_commands]        
        config = nonebot.get_driver().config
        command_start = config.command_start
        regex = f"^({'|'.join(command_start)})({'|'.join(all_commands_combined)})(.*)$"
        logger.info(f"building command help matcher with {regex}, prior={priority}, kwargs={help_args}")
        matcher = on_regex(regex, flags=re.MULTILINE, block=True, priority=priority, **help_args)
        @matcher.handle()
        async def help(bot: Bot, event: Event, state: T_State, matcher: Matcher):
            # get real command content
            logger.debug(f"event: {event}")
            logger.debug(f"state: {state}")
            msg = event.get_message().extract_plain_text()
            logger.debug(f"got message '{msg}'")
            _, origin_command, command_text = re.match(regex, msg, flags=re.MULTILINE).groups()
            logger.debug(f"got command text '{command_text}'")
            extra_prompt = ""
            if not command_text.startswith(" ") and command_text != "":
                extra_prompt += f"treat '{origin_command + command_text}' as '{origin_command}'\n"
                logger.warning(extra_prompt)
                command_text = ""
            else:
                command_text = command_text.strip()
            command_without_help = origin_command.split()[-1]
            logger.debug(f"{command_without_help} => {self.cmd}")
            logger.debug(f"planning to call with '{self.cmd}', '{command_text}', '{self.help_long}'")
            help_long_text = await self.help_long_async_factory(self.cmd, command_text, self.help_long)
            
            sub_commands_texts = await asyncio.gather(*[command.help_short_async_factory(command.cmd, command_text, command.help_short) for command in self.sub_commands])
            newline = '\n'
            output = \
f"""
{extra_prompt}{help_long_text.strip()}

sub-commands:
{newline.join(f'{k}[{u}]:{v.strip()}' for k,u,v in zip(
    ('|'.join(comm.cmd_in_dice) for comm in self.sub_commands), 
    (f'{comm.run_as}' for comm in self.sub_commands), 
    sub_commands_texts
    )
).strip()}
""".strip()
            await matcher.finish(output)
        logger.info(f"builded help")
        return (matcher, sub_matchers) if sub_matchers else matcher     
コード例 #2
0
ファイル: __init__.py プロジェクト: MeetWq/mybot
def create_emoji_matchers():
    def create_handler(dirname: str) -> T_Handler:
        async def handler(filename: str = EventPlainText()):
            filename = filename.strip().strip("[").strip("]")
            await handle_emoji(matcher, dirname, filename)

        return handler

    for _, params in emoji_list.items():
        matcher = on_regex(params["pattern"], block=True, priority=14)
        matcher.append_handler(create_handler(params["dirname"]))
コード例 #3
0
        def decorator(func: Callable):
            matcher = on_regex(pattern, **kwargs)

            @wraps(func)
            @self._pre_check(only_to_me=only_to_me)
            async def wrapper(bot: Bot, event: Event, state: T_State):
                match_group = state['_matched_groups']
                setattr(event, 'match', match_group)
                await func(bot, event)
                logger.info(
                    f'消息{event.get_session_id()}已被on_regex处理器{func.__name__}处理。'
                )
                await matcher.finish()

            return matcher.handle()(wrapper)
コード例 #4
0
ファイル: utils.py プロジェクト: nightingu/damebot
 def build(self, build_sub=True, recursive=False) -> Matcher:
     self.init_fn()
     logger.info(f"building '{self.cmd}'")
     if recursive:
         build_sub = True
     matcher = None
     if self.cmd is not None:
         config = nonebot.get_driver().config
         command_start = config.command_start
         regex = f"^({'|'.join(command_start)})({'|'.join(self.cmd_in_dice)})(.*)$"
         self.regex_ = regex
         matcher = on_regex(regex, flags=re.MULTILINE, block=True, priority=self.priority, **self.extra_kwargs)
         logger.info(f"building command matcher with '{regex}', prior={self.priority}, kwargs={self.extra_kwargs}")
         @matcher.handle()
         async def my_cmd_handler(bot: Bot, event: Event, state: T_State, matcher: Matcher):
             result = await self.cmd_handler(bot=bot, event=event, state=state, matcher=matcher)
             return result
         matcher.command_builder = self
     matcher_subs = [x.build(build_sub=recursive, recursive=recursive) for x in self.sub_commands] if build_sub else None
     logger.info(f"builded '{self.cmd}'")
     for item in [matcher, matcher_subs]:
         if item is not None:
             return item
コード例 #5
0
ファイル: __init__.py プロジェクト: LuneZ99/Meteora
import nonebot

from nonebot import on_regex
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.permission import Permission, SUPERUSER

from .config import Config

cfg = Config()
print(cfg.regex)
aha = on_regex(cfg.regex)


@aha.handle()
async def hai(bot: Bot, event: Event, state: T_State):
    await aha.send(event.get_message())


コード例 #6
0
ファイル: __init__.py プロジェクト: SlieFamily/bdg-bot
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("\+%([\s\S]+)%")
Delwords = on_command("-del", priority=2)
welcom = on_notice()
suanle = on_regex("算了|bdg|爆点哥|BDG")


@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("\+%([\s\S]*)%", str(event.get_message()))
    if IsAdded(words):
コード例 #7
0
ファイル: maimaidx.py プロジェクト: Diving-Fish/Chiyuki-Bot
        await inner_level.finish("命令格式为\n定数查歌 <定数>\n定数查歌 <定数下限> <定数上限>")
        return
    if len(argv) == 1:
        result_set = inner_level_q(float(argv[0]))
    else:
        result_set = inner_level_q(float(argv[0]), float(argv[1]))
    if len(result_set) > 50:
        await inner_level.finish("数据超出 50 条,请尝试缩小查询范围")
        return
    s = ""
    for elem in result_set:
        s += f"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\n"
    await inner_level.finish(s.strip())


spec_rand = on_regex(r"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\+?")


@spec_rand.handle()
async def _(bot: Bot, event: Event, state: T_State):
    level_labels = ['绿', '黄', '红', '紫', '白']
    regex = "随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\+?)"
    res = re.match(regex, str(event.get_message()).lower())
    try:
        if res.groups()[0] == "dx":
            tp = ["DX"]
        elif res.groups()[0] == "sd" or res.groups()[0] == "标准":
            tp = ["SD"]
        else:
            tp = ["SD", "DX"]
        level = res.groups()[2]
コード例 #8
0
ファイル: __init__.py プロジェクト: SlieFamily/bdg-bot
import re
from .config import Config
from nonebot import on_command, on_regex
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

from .data_source import get_image, update_img

# 默认配置
global_config = nonebot.get_driver().config
plugin_config = Config(**global_config.dict())

# 响应命令
group_bqb = on_regex("([\S]+).jpg")
add_img = on_regex("\+ img ([\S]+):%\[[\S]+url=([\S]+)\]%")


@group_bqb.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
    key = re.findall("([\S]+).jpg", str(event.get_message()))[0]
    print(key)
    key_image_url = await get_image(key)
    if key_image_url:
        await group_bqb.finish(MessageSegment.image(key_image_url))


@add_img.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
    dats = re.findall("\+ img ([\S]+):%\[[\S]+url=([\S]+)\]%",
コード例 #9
0
ファイル: __init__.py プロジェクト: ShawnQiang1/nonebot_tools
import httpx
from loguru import logger
from nonebot import on_command, on_message
from nonebot import on_regex
from nonebot.adapters.cqhttp import Bot, Event, Message, MessageSegment

from .data_source import Setu, hso_config
from .model import Power

# -----------
# 事件响应
# -----------

# -----------------------------------------------------------------
setu = on_regex(pattern="来(.*?)[点丶份张幅](.*?)的?(|r18)[色瑟涩🐍][图圖🤮]", priority=1)
db = on_command("hso", priority=2)
reply = on_message(priority=3)
pic = on_command("查看")
asyncio.run(Power().update_all())


@setu.receive()
async def message_receive(bot: Bot, event: Event, state: dict):  # 涩图调用
    # logger.info(bot.__dict__)
    # logger.info(event.dict())
    # logger.info(state)
    await Setu(bot, event, state).main()


# -----------------------------------------------------------------
コード例 #10
0
ファイル: __init__.py プロジェクト: 138436724/coup
from .player import Player

# 游戏是否开始
game_flag = False
# 玩家数据
players = {}
# 身份牌
identities = ['公爵 ', '队长 ', '夫人 ', '刺客 ', '大使 '] * 4
# 身份牌墓地
card_graveyard = []

help_documentation = on_command("帮助", rule=to_me(), priority=0)

start_game = on_command("开始", rule=to_me(), priority=1)
draw_cards = on_endswith("人", rule=to_me(), priority=1)
give_cards = on_regex("^[1-7一二三四五六七两俩]", rule=to_me(), priority=2)
change_cards = on_startswith("换牌", rule=to_me(), priority=2)
die_cards = on_startswith("死亡", rule=to_me(), priority=2)
end_game = on_command("结束", rule=to_me(), priority=1)


@help_documentation.handle()
async def _(bot: Bot, event: Event):
    text = '请先呼我名\n' \
           '创建房间命令是”开始“\n' \
           '选择人数命令是“n人”\n' \
           '加入房间的命令是“n“\n' \
           '换牌命令是”换牌第n张“\n' \
           '死亡命令是”死亡第n张“\n' \
           '支持命令”结束“快速结束\n' \
           '详情规则参考http://www.yihubg.com/rule-details/7f81295f-7160-4261-b436-d385395b9b22'
コード例 #11
0
ファイル: __init__.py プロジェクト: Zhao-FlorenCE/CSC_Code
import base64
import re
from io import BytesIO

from nonebot import on_regex
from nonebot.adapters.cqhttp import Bot, Message, MessageEvent, MessageSegment

from .convrt_pic import *
from .get_weather import *

weather = on_regex(r".*?(.*)天气.*?", priority=1)


def img_to_b64(pic: Image.Image) -> str:
    buf = BytesIO()
    pic.save(buf, format="PNG")
    base64_str = base64.b64encode(buf.getbuffer()).decode()
    return "base64://" + base64_str


def get_msg(msg) -> str:
    msg1 = re.search(r".*?(.*)天气.*?", msg)
    msg2 = re.search(r".*?天气(.*).*?", msg)
    msg1 = msg1.group(1).replace(" ", "")
    msg2 = msg2.group(1).replace(" ", "")
    msg = msg1 if msg1 else msg2

    return msg


@weather.handle()
コード例 #12
0
from src.common.levelsystem import cd_step, UserLevel, FuncLimiter
from .lolicon import get_lolicon, get_1200
from .setu_lib import get_setu, increase_setu
from .others import get_sjbz, get_asmdh, get_nmb, get_pw


plugin_name = '色图'
plugin_usage = """别TM搜什么孙笑川色图,兄贵色图了,淦
———————
设置sl只最大最小是否5级才对这个有用,以下等级可以忽略
""".strip()


setu = on_regex(
    r'^ *再?[来來发發给給](?:(?P<num>[\d一二两三四五六七八九十]*)[张張个個幅点點份])?(?P<r18_call>[非(?:不是)]?R18)?(?P<kwd>.{0,10}?[^的])?的?(?P<r18_call2>[非(?:不是)]?R18)?的?[色瑟涩][图圖](?:(?P<num2>[\d一二两三四五六七八九十]*)[张張个個幅点點份])? *$',
    flags=re.I,
    rule=sv_sw(plugin_name, plugin_usage),
    priority=2
    )


kwdrex = re.compile(r'[,,]')  # 分离逗号做交集搜索


@setu.handle()
async def send_lolicon(bot: Bot, event: MessageEvent, state: T_State):

    gid = event.group_id if event.message_type=='group' else 0
    if gid:
        if str(gid) not in sl_settings:
            await setu.finish('''先设置本群sl再使用此功能吧
[设置sl 最小sl-最大sl]
コード例 #13
0
from .bilibili_video import b23_extract, bili_keyword
from nonebot import on_regex
from nonebot.adapters import Bot, Event

analysis_bili = on_regex(
    r"(b23.tv)|(www.bilibili.com/video)|(www.bilibili.com/bangumi)|(^(BV|bv)([0-9A-Za-z]{10}))|"
    r"(^(av|AV)([0-9]+)(/.*|\\?.*|)$)|(\[\[QQ小程序\]哔哩哔哩\])|(QQ小程序&amp;#93;哔哩哔哩)|"
    r"(QQ小程序&#93;哔哩哔哩)",
    priority=10,
    block=False)


@analysis_bili.handle()
async def analysis_main(bot: Bot, event: Event, state: dict):
    text = str(event.get_message()).strip()

    if "b23.tv" in text:
        # 提前处理短链接,避免解析到其他的
        text = await b23_extract(text)

    msg = await bili_keyword(text)
    if msg:
        await analysis_bili.send(msg)
        # try:
        #     await analysis_bili.send(msg)
        # except Exception as e:
        #     await analysis_bili.send(str(e)+"此次解析可能被风控,尝试去除简介后发送!")
        #     msg = re.sub(r"简介.*", "", msg)
        #     await analysis_bili.send(msg)
コード例 #14
0
ファイル: __init__.py プロジェクト: Melodyknit/QQ-GitHub-Bot
from ...utils import send_github_message

# allow using api without token
try:
    from ...libs.auth import get_user_token
except ImportError:
    get_user_token = None

ISSUE_REGEX = r"^#(?P<number>\d+)$"
REPO_REGEX: str = (r"^(?P<owner>[a-zA-Z0-9][a-zA-Z0-9\-]*)/"
                   r"(?P<repo>[a-zA-Z0-9_\-]+)$")
GITHUB_LINK_REGEX = (r"github\.com/"
                     r"(?P<owner>[a-zA-Z0-9][a-zA-Z0-9\-]*)/"
                     r"(?P<repo>[a-zA-Z0-9_\-]+)")

issue = on_regex(REPO_REGEX, priority=config.github_command_priority)
issue.__doc__ = """
^owner/repo$
获取指定仓库封面
"""
# lower priority than issue link
link = on_regex(GITHUB_LINK_REGEX, priority=config.github_command_priority + 1)
link.__doc__ = """
github.com/owner/repo
识别链接获取仓库封面
"""


@issue.handle()
@link.handle()
async def handle(bot: Bot, event: MessageEvent, state: T_State):
コード例 #15
0
            await c.execute(
                f'update group_poke_table set disabled=1 where group_id={event.group_id}'
            )
        else:
            raise ValueError
        await poke_setting.send("设置成功")
        await db.commit()
    except (IndexError, ValueError):
        await poke_setting.finish(
            "命令格式:\n戳一戳设置 默认   将启用默认的戳一戳设定\n戳一戳设置 限制 <秒>   在戳完一次bot的指定时间内,调用戳一戳只会让bot反过来戳你\n戳一戳设置 禁用   将禁用戳一戳的相关功能"
        )
    pass


#按性别随机群友
random_person = on_regex("^/随个([男女]?)人")


@random_person.handle()
async def _(bot: Bot, event: Event, state: T_State):
    try:
        gid = event.group_id
        glst = await bot.get_group_member_list(group_id=gid,
                                               self_id=int(bot.self_id))
        v = re.match("/随个([男女]?)人", str(event.get_message())).group(1)
        if v == '男':
            for member in glst[:]:
                if member['sex'] != 'male':
                    glst.remove(member)
        elif v == '女':
            for member in glst[:]:
コード例 #16
0
ファイル: public.py プロジェクト: Diving-Fish/Chiyuki-Bot
@repeat.handle()
async def _(bot: Bot, event: Event, state: T_State):
    r = random.random()
    if r <= 0.0114514:
        await repeat.finish(event.get_message())
'''

taro_lst = []

with open('src/static/taro.txt', encoding='utf-8') as f:
    for line in f:
        elem = line.strip().split('\t')
        taro_lst.append(elem)

taro = on_regex("溜冰塔罗牌")


@taro.handle()
async def _(bot: Bot, event: Event):
    group_id = event.group_id
    nickname = event.sender.nickname
    if str(group_id) != "702156482":
        return
    c = randint(0, 10)
    a = randint(0, 1)
    s1 = "正位" if a == 0 else "逆位"
    s2 = taro_lst[c][3 + a]
    await taro.finish(
        f"来看看{ nickname }抽到了什么:\n{taro_lst[c][0]}({taro_lst[c][1]},{taro_lst[c][2]}){s1}:\n{s2}"
    )
コード例 #17
0
import re
from .analysis_bilibili import b23_extract, bili_keyword
from nonebot import on_regex
from nonebot.adapters import Bot, Event

analysis_bili = on_regex(
    "(b23.tv)|(bilibili.com/video)|(bilibili.com/bangumi)|(^(BV|bv)([0-9A-Za-z]{10}))|(^(av|AV)([0-9]+)(/.*|\\?.*|)$)|(\[\[QQ小程序\]哔哩哔哩\])|(QQ小程序&amp;#93;哔哩哔哩)|(QQ小程序&#93;哔哩哔哩)"
)


@analysis_bili.handle()
async def analysis_main(bot: Bot, event: Event, state: dict):
    text = str(event.message).strip()
    if "b23.tv" in text:
        # 提前处理短链接,避免解析到其他的
        text = await b23_extract(text)
    try:
        group_id = event.group_id
    except:
        group_id = "1"
    msg = await bili_keyword(group_id, text)
    if msg:
        try:
            await analysis_bili.send(msg)
        except:
            await analysis_bili.send("此次解析可能被风控,尝试去除简介后发送!")
            msg = re.sub(r"简介.*", "", msg)
            await analysis_bili.send(msg)
コード例 #18
0
# import nonebot
from nonebot import get_driver, on_regex

from .config import Config
from nonebot.typing import T_State
from pathlib import Path
from nonebot.adapters.onebot.v11 import Bot, Event,Message
from nonebot.params import T_State,State

global_config = get_driver().config
config = Config(**global_config.dict())

from .data_source import get_av_data
import re
# Export something for other plugin
# export = nonebot.export()
# export.foo = "bar"

# @export.xxx
# def some_function():
#     pass
biliav = on_regex("av(\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})")
@biliav.handle()
async def handle(bot:Bot,event:Event,state:T_State=State()):
    avcode = re.search('av(\d{1,12})|BV(1[A-Za-z0-9]{2}4.1.7[A-Za-z0-9]{2})', str(event.get_message()))
    if avcode==None:
        return
    rj = await get_av_data(avcode[0])
    await bot.send(event=event,message=rj)
コード例 #19
0
from src.libraries.image import *
from src.libraries.gosen_choyen import generate
from nonebot import on_command, on_message, on_notice, on_regex
from nonebot.typing import T_State
from nonebot.adapters import Event, Bot
from nonebot.adapters.cqhttp import Message

#修改regex匹配
high_eq = on_regex('/低情商.+高情商.+')


@high_eq.handle()
async def _(bot: Bot, event: Event, state: T_State):
    regex = '/低情商(.+)高情商(.+)'
    groups = re.match(regex, str(event.get_message())).groups()
    left = groups[0].strip()
    right = groups[1].strip()
    if len(left) > 15 or len(right) > 15:
        await high_eq.send("为了图片质量,请不要多于15个字符")
        return
    img_p = Image.open(path)
    draw_text(img_p, left, 0)
    draw_text(img_p, right, 400)
    await high_eq.send(
        Message([{
            "type": "image",
            "data": {
                "file":
                f"base64://{str(image_to_base64(img_p), encoding='utf-8')}"
            }
        }]))
コード例 #20
0
支持的语言:{', '.join(list(legal_language.keys()))}
""".strip()
__short_cmd__ = "lang {language}; {code}"
__example__ = """
lang py3;
print('hello')
""".strip()
__notice__ = "来源为菜鸟教程的网络编译器,不要试图搞事情"
__usage__ = (
    f"{__des__}\nUsage:\n{__cmd__}\nExample:\n{__example__}\nNotice:\n{__notice__}"
)

compiler = on_regex(
    r"^lang\s+(?P<language>[^;;\s]+)[;;\s]+(?P<code>[^;;\s]+.*)",
    block=True,
    priority=13,
)


@compiler.handle()
async def _(msg: dict = RegexDict()):
    language = str(msg["language"]).strip()
    code = str(msg["code"]).strip()
    if language not in legal_language:
        await compiler.finish(f"支持的语言:{', '.join(list(legal_language.keys()))}"
                              )

    result = await network_compile(language, code)
    if not result:
        await compiler.finish("出错了,请稍后再试")
コード例 #21
0
ファイル: __init__.py プロジェクト: BillyPung/bdg-bot
import nonebot
import re
from .config import Config
from nonebot import on_command, on_regex
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

from .data_source import get_image

# 默认配置
global_config = nonebot.get_driver().config
plugin_config = Config(**global_config.dict())

# 响应命令
group_bqb = on_regex("([\S]+).jpg")


@group_bqb.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
    key = re.findall("([\S]+).jpg", str(event.get_message()))[0]
    print(key)
    key_image_url = await get_image(key)
    await group_bqb.finish(MessageSegment.image(key_image_url))
コード例 #22
0
ファイル: __init__.py プロジェクト: kitUIN/nonebot_tools
import nonebot
from loguru import logger
from nonebot import on_regex, on_command, on_message
from nonebot.adapters import Message, Event
from nonebot.adapters.onebot.v11 import Event, Bot, MessageSegment, ActionFailed, GroupMessageEvent, PrivateMessageEvent
import re

from nonebot.matcher import Matcher
from nonebot.params import Received, EventMessage, CommandArg, State, RegexGroup
from nonebot.typing import T_State

from .data_source import Ncm, music, ncm_config, playlist, setting, Q, cmd

set = on_command("ncm", priority=1, block=False)  # 功能设置
music_regex = on_regex("(song|url)\?id=([0-9]+)(|&)", priority=2,
                       block=False)  # 歌曲id识别 (新增json识别)
playlist_regex = on_regex("playlist\?id=([0-9]+)&", priority=2,
                          block=False)  # 歌单识别
music_reply = on_message(priority=2, block=False)  # 回复下载
search = on_regex("搜(歌|歌单|用户)", priority=2, block=False)  # 搜东西


@music_regex.handle()
async def music_receive(bot: Bot,
                        event: Event,
                        regroup: Tuple[Any, ...] = RegexGroup()):

    if event.dict()["message_type"] == "private":
        return await bot.send(event=event,
                              message=Message(
                                  MessageSegment.text("私聊无法启用解析功能")))
コード例 #23
0
try:
    from ...libs.auth import get_user_token
except ImportError:
    get_user_token = None

ISSUE_REGEX = r"^#(?P<number>\d+)$"
REPO_REGEX: str = (r"^(?P<owner>[a-zA-Z0-9][a-zA-Z0-9\-]*)/"
                   r"(?P<repo>[a-zA-Z0-9_\-]+)$")
REPO_ISSUE_REGEX = (r"^(?P<owner>[a-zA-Z0-9][a-zA-Z0-9\-]*)/"
                    r"(?P<repo>[a-zA-Z0-9_\-]+)#(?P<number>\d+)$")
GITHUB_LINK_REGEX = (
    r"github\.com/"
    r"(?P<owner>[a-zA-Z0-9][a-zA-Z0-9\-]*)/"
    r"(?P<repo>[a-zA-Z0-9_\-]+)/(?:issues|pull)/(?P<number>\d+)")

issue = on_regex(REPO_ISSUE_REGEX, priority=config.github_command_priority)
issue.__doc__ = """
^owner/repo#number$
获取指定仓库 issue / pr
"""
link = on_regex(GITHUB_LINK_REGEX, priority=config.github_command_priority)
link.__doc__ = """
github.com/owner/repo/issues/number
识别链接获取仓库 issue / pr
"""


@issue.handle()
@link.handle()
async def handle(bot: Bot, event: MessageEvent, state: T_State):
    group: Dict[str, str] = state["_matched_dict"]
コード例 #24
0
from nonebot import on_notice, on_message, on_regex
from nonebot.adapters.cqhttp import GroupRecallNoticeEvent, Bot, Message, FriendRecallNoticeEvent, PokeNotifyEvent, \
    MessageEvent
from nonebot.rule import to_me
from random import choice

poke = on_notice(rule=to_me())
recall = on_notice()
# flashimg = on_message()
pa = on_regex(r"^.*派蒙.*爬.*")
jijian = on_regex(r"^.*击剑.*")

# 群聊
@recall.handle()
async def _(bot: Bot, event: GroupRecallNoticeEvent):
    mid = event.message_id
    meg = await bot.get_msg(message_id=mid)
    print(event)
    if event.user_id != event.self_id and 'type=flash,' not in meg['raw_message'] and event.operator_id not in [
        2064338943, event.self_id]:
        re = '刚刚说了:\n' + meg['message'] + '\n\n不要以为派蒙没看见!'
        await recall.finish(message=Message(re), at_sender=True)
        return
    if event.user_id == event.self_id and event.operator_id not in [2064338943, event.self_id]:
        if "你的撤回可不生效哦" in meg['message']:
            await recall.finish(message=Message(meg['message']), at_sender=False)
        else:
            await recall.finish(message=Message(meg['message'] + "\n你的撤回可不生效哦"), at_sender=False)
        return

@poke.handle()
コード例 #25
0
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("语录追加成功,爆点世界重构中……"))
    else:
コード例 #26
0
ファイル: __init__.py プロジェクト: ShawnQiang1/nonebot_tools
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import httpx
from loguru import logger
from nonebot import on_regex, on_command, on_message
from nonebot.adapters.cqhttp import Bot, Event, MessageSegment, Message
from tinydb import TinyDB, Query
import re
from .data_source import Ncm, music, ncm_config

setting = TinyDB("./db/setting.json")
Q = Query()
set = on_command("ncm", priority=1)  # 功能设置
music_regex = on_regex("com\/m\/song\/([0-9]*)\/|id=([0-9]*)&",
                       priority=2)  # 歌曲id识别 (新增json识别)
reply = on_message(priority=2)  # 回复下载


@music_regex.receive()
async def music_receive(bot: Bot, event: Event, state: dict):
    # logger.info(event.get_type())
    if event.dict()["message_type"] == "private":
        return await bot.send(event=event,
                              message=Message(
                                  MessageSegment.text("私聊无法启用解析功能")))
    # logger.info(bot.__dict__)
    # logger.info(event.dict())
    # logger.info(state)
    info = setting.search(Q["group_id"] == event.dict()["group_id"])
    id = list(filter(None, state["_matched_groups"]))  # 去除None