from nonebot import MatcherGroup
from nonebot_adapter_gocq.event import GroupRequestEvent
from nonebot.permission import SUPERUSER
from nonebot.rule import ArgumentParser
from nonebot_adapter_gocq.exception import ActionFailed

from src.common import Bot, MessageEvent, T_State, SUPERUSERS, logger
from src.common.rules import comman_rule

entry_and_exit = MatcherGroup()

entry_manager = entry_and_exit.on_request(
    rule=comman_rule(GroupRequestEvent, sub_type='invite'))


@entry_manager.handle()
async def entry_group(bot: Bot, event: GroupRequestEvent):
    if event.user_id in SUPERUSERS:
        try:
            await event.approve()
        except ActionFailed as err:
            logger.warning(err)
    else:
        await bot.set_group_add_request(flag=event.flag,
                                        sub_type=event.sub_type,
                                        approve=False,
                                        reason='请联系维护组申请群授权')
        for sp in SUPERUSERS:
            await bot.send_private_msg(
                user_id=sp,
                message=
Exemple #2
0
/收邮件

**SuperUser Only**
/添加邮箱
/绑定邮箱'''

# 声明本插件可配置的权限节点
__plugin_auth_node__ = ['basic']

# Init plugin export
init_export(export(), __plugin_name__, __plugin_usage__, __plugin_auth_node__)

# 注册事件响应器
OmegaEmail_admin = MatcherGroup(type='message',
                                rule=to_me(),
                                priority=20,
                                permission=SUPERUSER,
                                block=True)

admin_mail_add = OmegaEmail_admin.on_command('添加邮箱')


# 修改默认参数处理
@admin_mail_add.args_parser
async def parse(bot: Bot, event: MessageEvent, state: T_State):
    args = str(event.get_plaintext()).strip().split()
    if not args:
        await admin_mail_add.reject('你似乎没有发送有效的参数呢QAQ, 请重新发送:')
    state[state["_current_key"]] = args[0]
    if state[state["_current_key"]] == '取消':
        await admin_mail_add.finish('操作已取消')
Exemple #3
0
import re
from itertools import zip_longest
from nonebot.adapters.cqhttp import escape, Bot, Event, MessageSegment
from nonebot.permission import MESSAGE
from nonebot import MatcherGroup
from nonebot_plugin_rauthman import isInService

sv = MatcherGroup(type='message', rule=isInService('cherugo', 1))

CHERU_SET = '切卟叮咧哔唎啪啰啵嘭噜噼巴拉蹦铃'
CHERU_DIC = {c: i for i, c in enumerate(CHERU_SET)}
ENCODING = 'gb18030'
rex_split = re.compile(r'\b', re.U)
rex_word = re.compile(r'^\w+$', re.U)
rex_cheru_word: re.Pattern = re.compile(rf'切[{CHERU_SET}]+', re.U)


def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


def word2cheru(w: str) -> str:
    c = ['切']
    for b in w.encode(ENCODING):
        c.append(CHERU_SET[b & 0xf])
        c.append(CHERU_SET[(b >> 4) & 0xf])
    return ''.join(c)


def cheru2word(c: str) -> str:
Exemple #4
0
from nonebot.rule import to_me
from nonebot import CommandGroup, MatcherGroup

cmd = CommandGroup("test", rule=to_me())
match = MatcherGroup(priority=2)

from . import commands, matches
Exemple #5
0
if not configfile.exists():
    with configfile.open('w', encoding='utf-8') as j:
        json.dump({}, j, indent=4)

with configfile.open(encoding='utf-8') as j:
    prob_settings = json.load(j)


def record_settings(gid: str, prob: float):
    prob_settings[gid] = prob
    with configfile.open('w', encoding='utf-8') as j:
        json.dump(prob_settings, j, indent=4)


chatbot = MatcherGroup(type='message')

set_prob = chatbot.on_command('聊天触发率',
                              rule=sv_sw(plugin_name, plugin_usage)
                              & comman_rule(GroupMessageEvent),
                              priority=2)


@set_prob.handle()
async def recieve_arg(bot: Bot, event: GroupMessageEvent, state: T_State):
    arg = event.message.extract_plain_text().strip()
    if arg:
        state['prob'] = arg


@set_prob.got("prob", prompt='请输入聊天触发率,范围0-50,输入[退出]取消设置触发率')
Exemple #6
0
def str2cheru(s: str) -> str:
    c = []
    for w in rex_split.split(s):
        if rex_word.search(w):
            w = word2cheru(w)
        c.append(w)
    return ''.join(c)


def cheru2str(c: str) -> str:
    return rex_cheru_word.sub(lambda w: cheru2word(w.group()), c)


cherugo = MatcherGroup(type='message',
                       rule=sv_sw(plugin_name,
                                  usage=plugin_usage,
                                  hierarchy='其它'))

tocherugo = cherugo.on_startswith('切噜一下')


@tocherugo.handle()
async def cherulize(bot: Bot, event: MessageEvent):
    s = event.get_plaintext()
    if len(s) > 500:
        await tocherugo.finish(reply_header(event, '切、切噜太长切不动勒切噜噜...'))
    await tocherugo.finish(reply_header(event, '切噜~♪' + str2cheru(s)))


fromcherugo = cherugo.on_startswith('切噜~♪')
Exemple #7
0
from collections import defaultdict
import re
from nonebot import MatcherGroup
from nonebot.matcher import Matcher
from nonebot.adapters.cqhttp import Bot, Event, MessageSegment
from nonebot.permission import MESSAGE
from nonebot.log import logger
from nonebot_plugin_rauthman import isInService
from cheru.utils import helper, chara, priv
from .gacha import Gacha
try:
    import ujson as json
except:
    import json

sv = MatcherGroup(type='message', rule=isInService('gacha', 1))

from .update import *

jewel_limit = helper.DailyNumberLimiter(15000)
tenjo_limit = helper.DailyNumberLimiter(5)

JEWEL_EXCEED_NOTICE = f'您今天已经抽过{jewel_limit.max}钻了,欢迎明早5点后再来!'
TENJO_EXCEED_NOTICE = f'您今天已经抽过{tenjo_limit.max}张天井券了,欢迎明早5点后再来!'
POOL = ('MIX', 'JP', 'TW', 'BL')
DEFAULT_POOL = POOL[0]

_pool_config_file = os.path.expanduser('~/.cheru/group_pool_config.json')
_group_pool = {}
try:
    with open(_pool_config_file, encoding='utf8') as f:
Exemple #8
0
from nonebot.typing import T_State
from nonebot.rule import to_me
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.message import MessageSegment
from nonebot.adapters.cqhttp.event import GroupMessageEvent
from nonebot.adapters.cqhttp.permission import GROUP
from omega_miya.utils.Omega_plugin_utils import has_command_permission, permission_level
from .resources import MiyaVoice
"""
miya按钮bot实现版本
测试中
"""

button = MatcherGroup(type='message',
                      rule=to_me() & has_command_permission()
                      & permission_level(level=10),
                      permission=GROUP,
                      priority=100,
                      block=False)

miya_button = button.on_endswith(msg='喵一个')


@miya_button.handle()
async def miya_button(bot: Bot, event: GroupMessageEvent, state: T_State):
    arg = str(event.get_plaintext()).strip().lower()
    voice = re.sub('喵一个', '', arg)
    voice_file = MiyaVoice().get_voice_filepath(voice=voice)
    if not os.path.exists(voice_file):
        await bot.send(event=event, message='喵?')
    else:
        msg = MessageSegment.record(file=f'file:///{voice_file}')
Exemple #9
0
absPath = os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".")
config_file = f'{absPath}/config.json'

# data = {
#     'calendar_days': 7,  # 日程表返回包括今天在内多长时间的日程,默认是7天
#     'Refresh_date': '',  # 上次爬取日程表的日期
#     'schedule_data': ''  # 从官方日历爬取下来的数据
# }

# day_key里保存的是每天的信息分类,"qdhd"是多倍掉落庆典,"tdz"是公会战,
# "tbhd"是公会之家家具上架,"jqhd"是活动地图,"jssr"是角色生日
# 你可以自定义这个列表,删掉不想看到的活动
day_key = ["qdhd", "tdz", "tbhd", "jqhd"]


sv = MatcherGroup(type='message', rule=isInService('schedule', 1))
sv_query = sv.on_command(cmd='schedule', aliases={
                         '国服日程表', '日程表'}, permission=MESSAGE, block=True)


@sv_query.handle()
async def Schedule(bot: Bot, ev: Event, state: dict):
    # 调用的时候比对上次爬取日程表时间,不是今天就重新爬取日程表,是今天就直接返回
    p = config_file
    await checkFolder(p)
    data = await readJson(p)
    if data == FAILURE:
        data = {
            'calendar_days': 7,
            'Refresh_date': '',
            'schedule_data': ''
Exemple #10
0
from nonebot import MatcherGroup
from nonebot.adapters.cqhttp import Bot, Event
from nonebot_plugin_rauthman import isInService
from nonebot.permission import MESSAGE
from nonebot.log import logger
from nonebot.plugin import on_message

from cheru.utils import res, helper
from cheru import config
from typing import (Any, Callable, Dict, Iterable, List, NamedTuple, Optional,
                    Set, Tuple, Union)

from .argparse import ArgParser
from .exception import *

sv = MatcherGroup(type='message', rule=isInService('clanbattle'))
SORRY = 'ごめんなさい!嘤嘤嘤(〒︿〒)'
_registry: Dict[str, Tuple[Callable, ArgParser]] = {}


async def _clanbattle_bus(bot: Bot, event: Event, state: dict):
    # check prefix
    start = ''
    for m in event.message:
        if m.type == 'text':
            start = m.data.get('text', '').lstrip()
            break
    # if not start or start[0] not in '!!':
    #     return

    # find cmd
Exemple #11
0
        empty = '░' * 9
    elif pct > 0.95 and pct <= 0.975:
        fill = '█' * 9 + '▌'
        empty = ''
    elif pct < 0:
        fill = ''
        empty = '░' * 10
    else:
        bk_amt = round(pct * 10)
        fill = '█' * round(bk_amt)
        empty = '░' * (10 - bk_amt)

    return '┃%s┃' % (fill + empty)


level_sys = MatcherGroup(type="message")

sign = level_sys.on_command("签到")


@sign.handle()
async def sign_(bot: Bot, event: MessageEvent):
    uid = event.user_id
    user = UserLevel(uid)

    # 是否可以签到
    today = date.today()
    last_sign_day = user.last_sign.date()

    if today > last_sign_day:
        with QbotDB() as botdb:
Exemple #12
0
**Usage**
/我的状态
/重置状态
/我的假期
/请假 [时间] [理由]
/销假
/谁有空 [技能名称]
/谁在休假'''

# Init plugin export
init_export(export(), __plugin_name__, __plugin_usage__)

# 注册事件响应器
vocation = MatcherGroup(type='message',
                        rule=has_command_permission()
                        & permission_level(level=80),
                        permission=GROUP,
                        priority=10,
                        block=True)

my_status = vocation.on_command('我的状态')


@my_status.handle()
async def handle_first_receive(bot: Bot, event: GroupMessageEvent,
                               state: T_State):
    user_id = event.user_id
    user = DBUser(user_id=user_id)
    result = user.status()
    if result.success():
        status = result.result
        if status == 1:
Exemple #13
0
import nonebot
from nonebot import MatcherGroup
from nonebot.permission import MESSAGE, SUPERUSER
from nonebot.adapters.cqhttp import Bot, Event
import cheru

sv = MatcherGroup(type='message')
sv_status = sv.on_command(cmd='status',
                          aliases={'/status'},
                          permission=SUPERUSER,
                          block=True)


@sv_status.handle()
async def handle_get_status(bot: Bot, event: Event, state: dict):
    try:
        sid = bot.self_id
        res = await bot.get_status(self_id=sid)
    except:
        await sv_status.finish('error')
    stat = res['stat']
    packet_received = stat['packet_received']
    packet_sent = stat['packet_sent']
    packet_lost = stat['packet_lost']
    message_received = stat['message_received']
    message_sent = stat['message_sent']
    disconnect_times = stat['disconnect_times']
    lost_times = stat['lost_times']
    info = await bot.call_api('get_login_info')
    nickname = info['nickname']
    msg = f'''
Exemple #14
0
from nonebot import MatcherGroup

sv = MatcherGroup(type='message')

from .login_bouns import *
from .whois import *
from .comic import *
from .news import *
Exemple #15
0
from PIL import Image, ImageSequence, ImageDraw, ImageFont
import numpy as np

font_path = res.get('font/seguiemj.ttf').path

aliases = {
    '怎么拆', '怎么解', '怎么打', '如何拆', '如何解', '如何打', '怎麼拆', '怎麼解', '怎麼打', 'jjc查询',
    'jjc查詢'
}
aliases_b = {'b' + a for a in aliases}
aliases_b1 = {'B' + a for a in aliases}
aliases_b.update(aliases_b1)
aliases_tw = {'台' + a for a in aliases}
aliases_jp = {'日' + a for a in aliases}

sv = MatcherGroup(type='message')
sv_all = sv.on_command(cmd='arena_all',
                       aliases=aliases,
                       permission=MESSAGE,
                       block=True)


@sv_all.handle()
async def arena_all(bot: Bot, event: Event, state: dict):
    res = await _arena_query(bot, event, 1)
    await sv_all.finish(res)


sv_bl = sv.on_command(cmd='arena_bl',
                      aliases=aliases_b,
                      permission=MESSAGE,
Exemple #16
0
                ],
            # 'invite': [
            #     '欢迎{name}来到{admin}的女装殿堂,让{admin}亲自为您挑选合适的款式吧!',
            #     '{admin}邀请{name}给大家展示女装姐妹丼啦,欸欸~米娜桑不要脱裤子啊(#°Д°)'
            #     ],
            'locked': False
            }  # 暂时没发现有条件能上报operator_id,所以invite就先不管了


def save_wl_settings():
    """保存群欢迎语句设置"""
    with welcome_settings_file.open('w', encoding='utf-8') as j:
        json.dump(welcome_settings, j, ensure_ascii=False, escape_forward_slashes=False, indent=4)


welcome = MatcherGroup()
welcome_sw = sv_sw(welcome_name, welcome_usage, hierarchy='群助手')

speech_editor = welcome.on_command('设置入群欢迎', rule=welcome_sw&comman_rule(GroupMessageEvent), priority=2)


@speech_editor.handle()
async def show_speech(bot: Bot, event: GroupMessageEvent, state: T_State):
    gid = str(event.group_id)
    if gid not in welcome_settings:
        wl_setting = DEFAULT_SPEECH
    else:
        wl_setting = welcome_settings[gid]
    ap_speeches = '\n'.join([f'{i+1}.{speech}' for i, speech in enumerate(wl_setting['approve'])])
    # in_speeches = '\n'.join([f'{i+1+len(wl_setting["approve"])}.{speech}' for i, speech in enumerate(wl_setting['invite'])])
    status = '已锁定' if wl_setting['locked'] else '未锁定'
Exemple #17
0
from cheru import aiorequests
from cheru.utils import helper
import nonebot
from nonebot import MatcherGroup
from nonebot.log import logger
from nonebot.permission import MESSAGE
from nonebot.adapters.cqhttp import Bot, Event, MessageSegment
from nonebot_plugin_rauthman import isInService
from urllib.parse import quote
# from pixivpy3 import AppPixivAPI
from pixivpy3 import ByPassSniApi
from .config import *
import random
import datetime

sv = MatcherGroup(type='message', rule=isInService('pixiv', 1))
# aapi = AppPixivAPI()
aapi = ByPassSniApi()
aapi.require_appapi_hosts(hostname="public-api.secure.pixiv.net")
aapi.set_accept_language('jp')
sv_search = sv.on_startswith(msg='/pixiv', permission=MESSAGE, block=True)


@sv_search.handle()
async def pixiv_handle(bot: Bot, event: Event, state: dict):
    msg = str(event.message).strip()
    msg = msg.replace('/pixiv', '')
    if not msg:
        logger.info('pixiv_handle | no keyword')
        await sv_search.finish()
    state['keyword'] = msg
Exemple #18
0
plugin_name = '问答对话'
plugin_usage = """
﹟ 使用学习功能可增加经验值与资产,支持图片、emoji
﹟ 学习之后的内容会按照出现概率进行回复,短时间内不会回复重复的内容
﹟ 设置的概率为相对概率,实际的概率会根据相同对话的条目数与对话地点进行调整
———————
发送以下指令查看相应的使用方式(带上两边的Q和A)
Q学习方法A
Q查询方法A
Q修改方法A
Q批量学习A
""".strip()

#—————————————————功能说明——————————————————

guide = MatcherGroup(type='message', priority=2)

learn_method = guide.on_message(rule=full_match('Q学习方法A'))
query_method = guide.on_message(rule=full_match('Q查询方法A'))
modify_method = guide.on_message(rule=full_match('Q修改方法A'))
batch_learn_method = guide.on_message(rule=full_match('Q批量学习A'))


@learn_method.handle()
async def guide_learn(bot: Bot):
    await learn_method.finish(""">>>学习方法:
﹟ [学习 问句 回答 答句] 可快速设置对话,记得用空格做分隔,
﹟ 不方便连续发送的内容(如内容中包含图片)可单独发送[学习]然后按照说明输入
﹟ 可分别在私聊和群中使用[私聊学习]和[群内学习]进行仅能在学习地点出现的对话
   (也就是群内学习的内容不会在其它群内散播,私聊学习的内容仅仅只能创建人在私聊中触发)
﹟ 答句里使用{name}可在回复时自动替换掉触发者的昵称(带上中括号)
from datetime import datetime
from asyncio import sleep as asleep

from nonebot import MatcherGroup
from nonebot_adapter_gocq.event import GroupRecallNoticeEvent
from nonebot_adapter_gocq.exception import ActionFailed
from nonebot_adapter_gocq.utils import unescape

from src.common import Bot, GroupMessageEvent, Message, logger
from src.common.rules import sv_sw, comman_rule
from src.utils import reply_header

plugin_name = '防撤回'
plugin_usage = '[N号记录是什么] N换成撤回时返回的记录号则会返回被撤回的内容,注意不要带标点\n※※不喜欢的话使用关闭功能开关就好'

antirecall = MatcherGroup(
    rule=sv_sw(plugin_name, plugin_usage, hierarchy='群助手'))

ta_map = {'male': '他', 'female': '她', 'unknown': '它'}
recalled = defaultdict(dict)  # 存储每个群的每个撤回消息的字典
"""
结构:group_id:
        {fake_id:
            [msg_id: int, passive: bool, time]
        }
"""


def store_recall(gid: int,
                 fake_id: int,
                 message_id: int,
                 passive: bool,
from nonebot.plugin import on_keyword, on_command
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot import MatcherGroup, CommandGroup, export, logger
from src.plugins.hoke.selectMysql import QueryWeiboAll, QueryQQ, QueryMobole, QueryWeibo
from src.urils.tool import is_number, validPhone, fomatMessage
'''聊天模式'''
pBot_mes_group = MatcherGroup(type='message', priority=20, block=True)
pbot_cmd = pBot_mes_group.on_command('q')


@pbot_cmd.handle()
async def queryPhoneInfo(bot: Bot, event: MessageEvent):
    mes = str(event.message).strip()
    if mes == '637442240':
        return 0
    bool = validPhone(mes)
    bList = ""
    mobiles = []
    weibo = []
    if is_number(mes):
        if bool:
            mobiles = QueryMobole(mes)
            weibo = QueryWeibo(mes)
        else:
            mobiles = QueryQQ(mes)
            weibo = QueryWeiboAll(mobiles)
        bList = fomatMessage(mobiles, weibo)
    else:
        bList = "你说啥?"