示例#1
0
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,
示例#2
0
        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:
示例#3
0
        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,输入[退出]取消设置触发率')
async def prob_handle(bot: Bot, event: GroupMessageEvent, state: T_State):
    prob = state[
        "prob"] if "prob" in state else event.message.extract_plain_text(
示例#4
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('切噜~♪')
示例#5
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 '未锁定'
    msg = '当前新人入群欢迎语句为:\n' + ap_speeches + '\n────────────\n可修改状态:' + status
示例#6
0
        return self.__str__()

    def pgup(self):
        if self.crupg != 1:
            self.crupg -= 1
            self.pagebar.pgup()
        return self.__str__()

    def pgdn(self):
        if self.crupg != len(self.rcd_ls):
            self.crupg += 1
            self.pagebar.pgdn()
        return self.__str__()


qanda = MatcherGroup(type='message', rule=sv_sw('问答对话', plugin_usage))


#—————————————————回复——————————————————
async def reply_checker(bot: Bot, event: MessageEvent, state: T_State) -> bool:
    """问答对话触发规则"""
    q = await msg2str(Message(event.raw_message)
                      )  # 仅仅使用message会去掉呼唤bot昵称的原文本,造成问句中有bot昵称时逻辑混乱
    logger.debug(f'Search question <{q}> in corpus...')
    gid = event.group_id if event.message_type == 'group' else 0
    result = query(q, gid)
    logger.debug(f'当前获得了可触发的对话:{result}')
    if not result:
        return False

    alter = [(s, a) for s, a, p in result
示例#7
0

def filter_noarg(bot: Bot, event: MessageEvent, state: T_State):
    """过滤掉“我想听”但是没有参数的情况"""
    if event.raw_message != '我想听'.strip():
        return True


# 命令部分
music = on_command('点歌',
                   aliases={
                       '搜歌', '我想听', '来首', '网易云', '搜网易云', '网易云点歌', '网易云搜歌',
                       'QQ音乐', '搜QQ音乐', 'QQ音乐点歌', 'QQ音乐搜歌', '咪咕', '搜咪咕',
                       '咪咕点歌', '咪咕搜歌'
                   },
                   rule=sv_sw(plugin_name, plugin_usage) & filter_noarg,
                   priority=2)
limiter = FuncLimiter('点歌', cd_rel=120, max_free=2, cost=3)


@music.handle()
@limiter.limit_verify(cding='稍等一下,音乐冷却还剩{left_time}秒',
                      overdraft='资金不够啦,点歌台也是要电费的哟')
async def recieve_cmd(bot: Bot, event: MessageEvent, state: T_State):
    state['trigger'] = event.raw_message  # 检测搜索的指定音乐源还是混合列表
    kwd = event.message.extract_plain_text().strip()
    if kwd:
        state['kwd'] = kwd


@music.got("kwd", prompt='你想听什么歌呢?')
示例#8
0
from random import choice, shuffle
from pathlib import Path
import asyncio

from nonebot import require, get_bots
from nonebot_adapter_gocq.exception import ActionFailed

from src.common import logger, RESPATH
from src.common.rules import group_func_off, sv_sw
from src.common.verify import Enable_Group, Group_Blocker
from src.utils import mediaseg

plugin_name = '饮茶提醒'
plugin_usage = '每日提醒饮茶小助手'

sv_sw(plugin_name, plugin_usage)  # 要运行一下把功能名装进去 TODO: 统一功能开关

TEATIME_NOTICE = ('喂!', '三点几嚟!', '做 做撚啊做!', '饮茶先啦!三点几嚟 饮茶先啦!', '做咁多都冇用嘅!',
                  '老细唔锡你嘅嚟!', '喂饮下茶先啊!', '三点几嚟!', '做碌鸠啊做!')

TEATIME_ATTACH = [
    mediaseg(f) for f in (Path(RESPATH) / 'tea_time').glob('*.*')
]  # 随机附加在后面一个媒体文件

scheduler = require('nonebot_plugin_apscheduler').scheduler


@scheduler.scheduled_job("cron",
                         day_of_week='mon-sat',
                         hour=15,
                         id='3clock',
示例#9
0
from nonebot.plugin import on_message
from nonebot_adapter_gocq.exception import ActionFailed

from src.common import Bot, MessageEvent, logger, BOTNAME, MessageSegment, RESPATH
from src.common.rules import sv_sw, full_match
from src.common.levelsystem import UserLevel, is_user, filter_users
from src.utils import imgseg, DailyNumberLimiter
from .ballot_fortune import query_fortune, draw_fortune, get_active_user

plugin_name = '运势'
plugin_usage = """[今日运势] 没日一抽,运气好的话当天可能出门被撞到异世界当美少女"""

assets_folder = Path(RESPATH) / 'fortune'
sticks = [i for i in assets_folder.glob('*.[jp][pn]*g')]

fortune = on_message(rule=sv_sw(plugin_name, plugin_usage) & full_match(
    ('运势', '今日运势')),
                     priority=2)


@fortune.handle()
async def check_fortune(bot: Bot, event: MessageEvent):
    name = event.sender.card if event.message_type == 'group' else event.sender.nickname
    dlmt = DailyNumberLimiter(event.user_id, func_name='运势', max_num=1)
    stick = query_fortune(event.user_id)
    rp = 0  # 如果抽中了特殊的签要发生一些事件 TODO:加入一些今天功能冷却减少之类的什么奖励吧
    if dlmt.check(close_conn=False) or not stick:
        stick = choice(sticks)
        if dlmt.count == 0:
            if stick.name == '28.jpg':  # 恋爱运,惩罚
                rp = 1
示例#10
0
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]
示例#11
0
    headers = {
        'origin': 'https://lab.magiconch.com',
        'referer': 'https://lab.magiconch.com/nbnhhsh/',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
    }
    data = {
        "text": f"{word}"
    }
    async with aiohttp.ClientSession() as session:
        async with session.post(url=url, headers=headers, data=data) as resp:
            msg = await resp.json()
            return msg if msg else []


sx = on_regex(r'([a-zA-Z]+)是(?:什么|啥)[??]?$', rule=sv_sw(plugin_name, plguin_usage, hierarchy='其它'), priority=2)


@sx.handle()
async def sx_rev(bot: Bot, event: MessageEvent, state: T_State):
    logger.debug(f'Match sx {state["_matched_groups"]}')
    abbr = state["_matched_groups"][0]
    try:
        data = await get_sx(abbr)
    except aiohttp.ClientError as err:
        logger.error(f'query sx {abbr} error: {err}')
        await sx.finish("查询出错了,要不要稍后再试试?")
    try:
        name = data[0]['name']
        logger.debug(f'查询缩写:{name}')
        content = data[0]['trans']
示例#12
0
        }
        logger.debug(f'{str(cur_msg)}')
        return False

    gr = cur_msg[event.group_id]

    # 复读过的人不在列表中,计算概率,如果是复读过的人会完全忽略消息,不刷新列表也不增加次数
    if event.user_id not in gr['uid_ls']:
        # if event.raw_message == gr['message']:
        gr['times'] += 1
        gr['uid_ls'].add(event.user_id)
        logger.debug(f'{str(cur_msg)}')
        if event.self_id not in gr[
                'uid_ls'] and event.user_id != event.self_id:  # 自己已在消息记录中,也可能是自己发送的消息,不能触发自己复读
            c = random()
            r = (1 - repeat_rate)**gr['times']
            # if random() > (1 - repeat_rate) ** gr['times']:
            logger.debug(f"c: {c}, r: {r}")
            if c > r:
                logger.debug(f'在第{gr["times"]}次触发了复读')
                state['raw_msg'] = gr['message']
                return True


repeater = on(rule=sv_sw(plugin_name, plugin_usage, '群助手') & store_talk)


@repeater.handle()
async def standby(bot: Bot, event: GroupMessageEvent, state: T_State):
    await repeater.finish(Message(state['raw_msg']))
示例#13
0
from nonebot.rule import Rule
from nonebot_adapter_gocq.event import GroupBanNoticeEvent
from src.common import T_State, BOTNAME
from src.common.rules import sv_sw, comman_rule
from nonebot_adapter_gocq.bot import Bot


async def didiban(bot: Bot, event: GroupBanNoticeEvent, state: T_State):
    if not isinstance(event, GroupBanNoticeEvent):
        return False
    selfinfo = await bot.get_group_member_info(group_id=event.group_id,
                                               user_id=event.self_id)
    if selfinfo[
            "role"] == "admin" and event.group_id == 973573381 and event.operator_id == 3548597378:
        state["uid"] = event.user_id
        return True


antididi = on_notice(rule=Rule(didiban) & sv_sw('抗蒂蒂', '被蒂蒂禁言自动解封', '群专享'))


@antididi.handle()
async def unban(bot: Bot, event: GroupBanNoticeEvent, state: T_State):
    try:
        await bot.set_group_ban(group_id=event.group_id,
                                user_id=state["uid"],
                                duration=0)
        await antididi.finish('Poor man, 苗苗会拯救不知道有没有罪的你')
    except:
        await antididi.finish('要是苗苗有力量的话...就可以拯救你了..岂可修!')