def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=0,
        help='Indicates the level of messages to be displayed.')
    parser.add_argument('-k',
                        '--keep',
                        const=str,
                        action='store_const',
                        default=False,
                        help='Keeps the temporary files for future runs.')
    parser.add_argument('--path',
                        required=True,
                        help='REQUIRED: Path with all images to work.')
    parser.add_argument(
        '--extension',
        required=True,
        choices=[ext.lower() for ext in ACCEPTED_IMAGE_FORMATS],
        help='REQUIRED: Images extension')
    arguments = parser.parse_args()

    logging.basicConfig(level=LOGGING_LEVELS[min(
        len(LOGGING_LEVELS) - 1, arguments.verbose)],
                        format='[%(levelname)s] %(message)s')

    print(' - IMAGE SIZE CLASSIFIER - ')
    service = Service()
    service.execute(Config(arguments.path, arguments.extension,
                           arguments.keep))
    print(' - DONE - ')
    exit(0)
예제 #2
0
async def process_msg(bot: Bot, event: Event, enable: bool):
    try:
        args = event.get_plaintext().strip()
        if not args:
            msg = _GROUP_USAGE if isinstance(
                event, GroupMessageEvent) else _PRIVATE_USAGE
            raise ValueError('未找到参数。' + msg)
        args = args.split(' ')

        # 从群组内调用
        if isinstance(event, GroupMessageEvent):
            succeed = set()
            failed = set()
            group_id = event.group_id
            services = args
            for sv_name in services:
                sv = Service.get_loaded_services().get(sv_name)
                if sv:
                    await set_sv(sv, group_id, enable)
                    succeed.add(sv_name)
                else:
                    failed.add(sv_name)
            msg = ''
            if succeed:
                msg += '服务' + '、'.join([str(i) for i in succeed]) + \
                       '已启用' if enable else '已禁用' + '\n'
            if failed:
                msg += '不存在这些服务:' + '、'.join([str(i) for i in failed])
            await bot.send(event, msg)

        # 私聊调用,需要superuser权限
        elif isinstance(event, PrivateMessageEvent):
            if not is_superuser(event.get_user_id()):
                return
            parser = ArgParserPrivate(enable, args)
            await parser.run()
            msg = ''
            if parser.succeed:
                msg += '执行完毕。\n'
            if parser.failed:
                msg += '以下群组发生错误:\n'
                msg += '\n'.join(
                    [f'  {name}: {msg}\n'
                     for name, msg in parser.failed]) + '\n'
                msg += _PRIVATE_USAGE
            await bot.send(event, msg)

    except ValueError as e:
        await bot.send(event, str(e))
예제 #3
0
 async def run(self):
     for name, groups in self.parse_result.items():
         sv = Service.get_loaded_services().get(name)
         if not sv:
             self.failed.append((name, '不存在该服务'))
             continue
         if not groups:
             self.failed.append((name, '缺少待操作的群组'))
             continue
         for group in groups:
             try:
                 await set_sv(sv, group, self.enable)
                 self.succeed.append((name, ''))
             except Exception as e:
                 self.failed.append((name, f'发送错误:{str(e)}'))
예제 #4
0
async def ls_sv(bot: Bot, event: Event):
    if isinstance(event, GroupMessageEvent):
        all_sv = Service.get_loaded_services()
        enabled_sv = [
            sv_name for sv_name, sv in all_sv.items()
            if sv.visible and sv.check_enabled_in_group(event.group_id)
        ]
        disabled_sv = [
            sv_name for sv_name, sv in all_sv.items()
            if sv.visible and not sv.check_enabled_in_group(event.group_id)
        ]
        msg = ''
        if enabled_sv:
            msg += '已启用服务:\n    · ' + '\n    · '.join(enabled_sv) + '\n'
        if disabled_sv:
            msg += '已禁用服务:\n    · ' + '\n    · '.join(disabled_sv)
        await bot.send(event, msg)
    else:
        return
예제 #5
0
import re
import random
from nonebot.adapters import Event

from src.Service import Service

sv = Service('dice')

async def do_dice(bot, ev, num, min_, max_, opr, offset, TIP="的掷骰结果是:"):
    if num == 0:
        await bot.send(ev, '咦?我骰子呢?')
        return
    min_, max_ = min(min_, max_), max(min_, max_)
    rolls = list(map(lambda _: random.randint(min_, max_), range(num)))
    sum_ = sum(rolls)
    rolls_str = '+'.join(map(lambda x: str(x), rolls))
    if len(rolls_str) > 100:
        rolls_str = str(sum_)
    res = sum_ + opr * offset
    msg = [
        f'{TIP}\n', str(num) if num > 1 else '', 'D',
        f'{min_}~' if min_ != 1 else '', str(max_),
        (' +-'[opr] + str(offset)) if offset else '',
        '=', rolls_str, (' +-'[opr] + str(offset)) if offset else '',
        f'={res}' if offset or num > 1 else '',
    ]
    msg = ''.join(msg)
    await bot.send(ev, msg, at_sender=True)


@sv.on_regex(r'^\.r\s*((?P<num>\d{0,2})d((?P<min>\d{1,4})~)?(?P<max>\d{0,4})((?P<opr>[+-])(?P<offset>\d{0,5}))?)?\b', flags=re.I)
예제 #6
0

try:
    import ujson as json
except:
    import json


sv_help = '''
[星乃来发十连] 转蛋模拟
[星乃来发单抽] 转蛋模拟
[星乃来一井] 4w5钻!
[查看卡池] 模拟卡池&出率
[切换卡池] 更换模拟卡池
'''.strip()
sv = Service('pcr_gacha')
jewel_limit = DailyNumberLimiter(6000)
tenjo_limit = DailyNumberLimiter(10)

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('~/.hoshino/group_pool_config.json')
_group_pool = {}
try:
    with open(_pool_config_file, encoding='utf8') as f:
        _group_pool = json.load(f)
except FileNotFoundError as e:
    logger.warning(
예제 #7
0
from nonebot.adapters import Bot, Event
from src.Service import Service

from nonebot import logger
from .data_source import get_single_continuation

sv = Service('novel_continuation', enable_on_default=True, visible=True)


@sv.on_command('续写')
async def novel_continue(bot: Bot, event: Event):
    await bot.send(event, '请耐心等候', at_sender=True)
    text = event.get_plaintext().strip()
    res = await get_single_continuation(text)
    if res:
        await bot.send(event, res, at_sender=True)
예제 #8
0
from nonebot.adapters import Bot, Event
try:
    import ujson as json
except:
    import json

from src import aiorequests, R
# from hoshino import aiorequests, R, Service
# from hoshino.typing import *
from src.Service import Service

sv_help = '''
官方四格漫画更新(日文)
[官漫132] 阅览指定话
'''.strip()
sv = Service('pcr-comic')


def load_index():
    with open(R.get('img/priconne/comic/index.json').path,
              encoding='utf8') as f:
        return json.load(f)


def get_pic_name(id_):
    pre = 'episode_'
    end = '.png'
    return f'{pre}{id_}{end}'


@sv.on_startswith('官漫')
예제 #9
0
from nonebot.adapters.cqhttp.utils import escape
from src.plugins.pcr import _pcr_data, chara
from src.Service import Service

from . import GameMaster

global_config = get_driver().config

PREPARE_TIME = 5
ONE_TURN_TIME = 12
TURN_NUMBER = 5
# DB_PATH = os.path.expanduser("~/.hoshino/pcr_desc_guess.db")
DB_PATH = os.path.join(global_config.cache_dir, "pcr_desc_guess.db")

gm = GameMaster(DB_PATH)
sv = Service("pcr-desc-guess")


@sv.on_fullmatch(("猜角色排行", "猜角色排名", "猜角色排行榜", "猜角色群排行"))
async def description_guess_group_ranking(bot, event: GroupMessageEvent):
    ranking = gm.db.get_ranking(event.group_id)
    msg = ["【猜角色小游戏排行榜】"]
    for i, item in enumerate(ranking):
        uid, count = item
        m = await bot.get_group_member_info(self_id=event.self_id, group_id=event.group_id, user_id=uid)
        name = escape(m["card"]) or escape(m["nickname"]) or str(uid)
        msg.append(f"第{i + 1}名:{name} 猜对{count}次")
    await bot.send(event, "\n".join(msg))


@sv.on_fullmatch(("猜角色", "猜人物"))
예제 #10
0
from nonebot import logger
from nonebot.adapters import Bot
from nonebot.adapters.cqhttp.event import Event
from src.Service import Service
from src.util import DailyNumberLimiter, FreqLimiter
from .local_img import get_local_setu
from .request_img import get_web_img

_max = 5
EXCEED_NOTICE = f'您今天已经冲过{_max}次了,请明早5点后再来!'
_nlmt = DailyNumberLimiter(_max)
_flmt = FreqLimiter(5)

sv = Service('setu', enable_on_default=False, visible=False)


@sv.on_regex(r'不够[涩瑟色]|[涩瑟色]图|来一?[点份张].*[涩瑟色]|再来[点份张]|看过了|铜')
async def setu(bot: Bot, event: Event):
    """随机叫一份涩图,对每个用户有冷却时间"""
    uid = event.get_user_id()
    if not _nlmt.check(uid):
        await bot.send(event, EXCEED_NOTICE, at_sender=True)
        return
    if not _flmt.check(uid):
        await bot.send(event, '您冲得太快了,请稍候再冲', at_sender=True)
        return
    _flmt.start_cd(uid)
    _nlmt.increase(uid)

    # conditions all ok, send a setu.
    try:
예제 #11
0
from src import util
from src.plugins.pcr import _pcr_data, chara
from src.Service import Service

from . import GameMaster

global_config = get_driver().config

PATCH_SIZE = 32
ONE_TURN_TIME = 20
DB_PATH = os.path.join(global_config.cache_dir, "pcr_avatar_guess.db")
# DB_PATH = os.path.expanduser("~/.hoshino/pcr_avatar_guess.db")
BLACKLIST_ID = [1072, 1908, 4031, 9000]

gm = GameMaster(DB_PATH)
sv = Service("pcr-avatar-guess", )


@sv.on_fullmatch(("猜头像排行", "猜头像排名", "猜头像排行榜", "猜头像群排行"))
async def description_guess_group_ranking(bot: Bot, event: GroupMessageEvent):
    ranking = gm.db.get_ranking(event.group_id)
    msg = ["【猜头像小游戏排行榜】"]
    for i, item in enumerate(ranking):
        uid, count = item
        m = await bot.get_group_member_info(self_id=event.self_id,
                                            group_id=event.group_id,
                                            user_id=uid)
        name = escape(m["card"]) or escape(m["nickname"]) or str(uid)
        msg.append(f"第{i + 1}名:{name} 猜对{count}次")
    await bot.send(event, "\n".join(msg))
예제 #12
0
from flask import Flask, jsonify
from flask import request
from flask import after_this_request
from src.Service import Service
from flask_cors import CORS, cross_origin
from mysql.connector import Error

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app, resources=r'/*', headers='Content-Type')
service = Service()


# @app.after_request
# def after_request(response):
#   response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
#   response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
#   response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
#   response.headers.add('Access-Control-Allow-Credentials', 'true')
#   return response


@app.before_request
def oauth_verify(*args, **kwargs):
    """Ensure the oauth authorization header is set"""
    if request.method in ['OPTIONS', ]:
        return


@app.route('/query', methods=['POST'])
@cross_origin()
예제 #13
0
import random
from nonebot.adapters import Event
from src.Service import Service
from src import R
from src.util import DailyNumberLimiter

sv = Service('pcr-login-bonus')

lmt = DailyNumberLimiter(1)
login_presents = [
    '扫荡券×5',
    '卢币×1000',
    '普通EXP药水×5',
    '宝石×50',
    '玛那×3000',
    '扫荡券×10',
    '卢币×1500',
    '普通EXP药水×15',
    '宝石×80',
    '白金转蛋券×1',
    '扫荡券×15',
    '卢币×2000',
    '上级精炼石×3',
    '宝石×100',
    '白金转蛋券×1',
]
todo_list = [
    '找伊绪老师上课', '给宫子买布丁', '和真琴寻找伤害优衣的人', '找镜哥探讨女装', '跟吉塔一起登上骑空艇',
    '和霞一起调查伤害优衣的人', '和佩可小姐一起吃午饭', '找小小甜心玩过家家', '帮碧寻找新朋友', '去真步真步王国', '找镜华补习数学',
    '陪胡桃排练话剧', '和初音一起午睡', '成为露娜的朋友', '帮铃莓打扫咲恋育幼院', '和静流小姐一起做巧克力',
    '去伊丽莎白农场给栞小姐送书', '观看慈乐之音的演出', '解救挂树的队友', '来一发十连', '井一发当期的限定池', '给妈妈买一束康乃馨',
예제 #14
0
import json
import os
import random

from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp.event import HonorNotifyEvent
from nonebot.adapters.cqhttp.message import MessageSegment
from src import R, util
from src.privilege import is_superuser
from src.Service import Service

sv = Service('chat', visible=False)


@sv.on_notice('notify.honor')
async def longwang(bot: Bot, event: HonorNotifyEvent):
    if event.honor_type == 'talkative':
        reply = ['龙王出来喷水', '呼风唤雨']
        msg = MessageSegment.at(event.get_user_id())
        msg += random.choice(reply)
        await bot.send(event, msg)


@sv.on_fullmatch(('沙雕机器人', '沙雕機器人'))
async def say_sorry(bot: Bot, event: Event):
    await bot.send(event, 'ごめんなさい!嘤嘤嘤(〒︿〒)')


@sv.on_fullmatch(('老婆', 'waifu', 'laopo'), only_to_me=True)
async def chat_waifu(bot: Bot, event: Event):
    if not is_superuser(event.get_user_id()):
예제 #15
0
from typing import Type
from src.Service import Service
from .spider import *
from nonebot import logger

svtw = Service('pcr-news-tw')
svbl = Service('pcr-news-bili')


async def news_poller(spider: Type[BaseSpider], sv: Service, TAG):
    if not spider.item_cache:
        await spider.get_update()
        logger.info(f'{TAG}新闻缓存为空,已加载至最新')
        return
    news = await spider.get_update()
    if not news:
        logger.info(f'未检索到{TAG}新闻更新')
        return
    logger.info(f'检索到{len(news)}条{TAG}新闻更新!')
    await sv.broadcast(spider.format_items(news), TAG, interval_time=0.5)


@svtw.scheduled_job('cron', minute='*/5', jitter=20)
async def sonet_news_poller():
    await news_poller(SonetSpider, svtw, '台服官网')


@svbl.scheduled_job('cron', minute='*/5', jitter=20)
async def bili_news_poller():
    await news_poller(BiliSpider, svbl, 'B服官网')
예제 #16
0
from src.Service import Service

svtw = Service('pcr-arena-reminder-tw', enable_on_default=False)
svjp = Service('pcr-arena-reminder-jp', enable_on_default=False)
msg = '骑士君、准备好背刺了吗?'


@svtw.scheduled_job('cron', hour='14', minute='45')
async def pcr_reminder_tw():
    await svtw.broadcast(msg, 'pcr-reminder-tw', 0.2)


@svjp.scheduled_job('cron', hour='13', minute='45')
async def pcr_reminder_jp():
    await svjp.broadcast(msg, 'pcr-reminder-jp', 0.2)
예제 #17
0
from nonebot.adapters import Bot, Event
from src.privilege import SUPERUSER
from nonebot import get_driver
from src.Service import Service

from .data_source import pick_comment

global_config = get_driver().config

sv = Service('网易云热评')


@sv.on_keyword(('网易云', '网抑云', '到点网抑', 'wyy', '老网易云了'), only_to_me=False)
async def wyy(bot: Bot, event: Event):
    comment = await pick_comment()
    await bot.send(event, comment)
예제 #18
0
from typing import Dict, List

from nonebot import get_driver, logger
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp.event import (GroupMessageEvent,
                                           PrivateMessageEvent)
from src.privilege import GROUP_ADMIN, PRIVATE, SUPERUSER, is_superuser
from src.Service import Service

global_config = get_driver().config

sv = Service('sv_manager',
             visible=False,
             use_priv=GROUP_ADMIN | PRIVATE,
             manage_priv=SUPERUSER)

_GROUP_USAGE = '用法:「启用 sv1 sv2 sv3...」'
_PRIVATE_USAGE = '用法:「启用 sv1 -123123123 -456456456 sv2 -234234234 sv3...」'


async def set_sv(sv: Service, group: int, enable: bool):
    """
    在一个群内,启用或关闭服务

    :参数:
      - `group: int`: 群号
      - `enable: bool`: 是否启用
    """
    if enable:
        await sv.set_enable_in_group(group)
    else:
예제 #19
0
from nonebot.adapters import Bot, Event
from src.Service import Service
import random
from .blessing import get_blessing_sentence, get_blessing_voice
from .song import get_song

sv = Service('new_year_blessing', enable_on_default=True, visible=True)


@sv.on_keyword('春节 过年 新年 除夕 牛年 新春 拜年 红包 过节 恭喜 祝福 发财'.split(' '))
async def func(bot: Bot, event: Event):
    if random.random() > 0.8:
        return
    funcs = [get_song, get_blessing_sentence, get_blessing_voice]
    await bot.send(event, random.choice(funcs)())
예제 #20
0
from loguru import logger
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, Event
from src.Service import Service
from .data_source import sim_draw

sv = Service('gacha')


@sv.on_command(
    "Fgo_Draw",
    aliases={"FGO抽卡", "FGO来一单", "fgo抽卡", "fgo来一单", "Fgo抽卡", "Fgo来一单"})
async def fgo_draw_handler(bot: Bot, event: Event):
    args = str(event.get_message()).strip()
    msg = sim_draw(55, game="fgo")
    await bot.send(event, msg)


@sv.on_command("Prts_Draw", aliases={"明日方舟抽卡", "明日方舟来一单", "方舟抽卡", "方舟来一单"})
async def prts_draw_handler(bot: Bot, event: Event):
    args = str(event.get_message()).strip()
    msg = sim_draw(55, game="prts")
    await bot.send(event, msg)


@sv.on_command("Ys_Draw", aliases={"原神抽卡"})
async def ys_draw_handler(bot: Bot, event: Event):
    args = str(event.get_message()).strip()
    try:
        msg = sim_draw(10, game="yuanshen")
예제 #21
0
import random
from typing import List
from loguru import logger

from nonebot import get_driver
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp.event import GroupMessageEvent
from src.Service import Service

from .config import Config

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

sv = Service('yygq_chat', variables={
    'YYGQ_RATE': 0.01,
})

# YYGQ_RATE: float = sv.get_config('YYGQ_RATE') or 0.2  # 回复概率
FORCE_UNIVERSAL_ANSWER_RATE: float = 0.13

UNIVERSAL_ANSWERS = [
    "你说你🐎呢?", "那没事了。", "真别逗我笑啊。", "那可真是有趣呢。", "就这?就这?", "你品,你细品。",
    "不会真有人觉得是这样的吧,不会吧不会吧?", "你在教我做事?", "给👴整笑了"
    # "お前の🐎さんのことですか?",
    # "お邪魔します。",
    # "笑わせないでください。",
    # "それは面白いですね。",
    # "これだけですか?これだけですか?",
    # "あなたの細品。",
    # "本当にそうだと思う人はいないでしょう。ね?ね?",
예제 #22
0
from src.Service import Service

sv_help = '''
[pcr速查] 常用网址/图书馆
[bcr速查] B服萌新攻略
[日rank] rank推荐表
[台rank] rank推荐表
[陆rank] rank推荐表
[挖矿15001] 矿场余钻
[黄骑充电表] 黄骑1动规律
[一个顶俩] 台服接龙小游戏
[谁是霸瞳] 角色别称查询
'''.strip()

sv = Service('pcr-query')

from .query import *
from .whois import *
from .miner import *
예제 #23
0
import random
from nonebot import logger
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp.event import GroupMessageEvent

from src.Service import Service

sv = Service('random-repeater', visible=False)

PROB_A = 1.4
group_stat = {}  # group_id: (last_msg, is_repeated, p)
'''
不复读率 随 复读次数 指数级衰减
从第2条复读,即第3条重复消息开始有几率触发复读

a 设为一个略大于1的小数,最好不要超过2,建议1.6
复读概率计算式:p_n = 1 - 1/a^n
递推式:p_n+1 = 1 - (1 - p_n) / a
'''


@sv.on_message()
async def random_repeater(bot: Bot, event: GroupMessageEvent):
    group_id = event.group_id
    msg = str(event.get_message())

    if group_id not in group_stat:
        group_stat[group_id] = (msg, False, 0)
        return

    last_msg, is_repeated, p = group_stat[group_id]
예제 #24
0
import math
import random
from datetime import timedelta
from nonebot import logger
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp.event import GroupMessageEvent

from src import util, R
from src.Service import Service
from src.privilege import set_block_user

sv = Service('sleeping-set', visible=False)


@sv.on_fullmatch(('睡眠套餐', '休眠套餐', '精致睡眠', '来一份精致睡眠套餐', '精緻睡眠', '來一份精緻睡眠套餐'))
async def sleep_8h(bot: Bot, event: GroupMessageEvent):
    await util.silence(event, 8 * 60 * 60, skip_su=False)


@sv.on_regex(r'(来|來)(.*(份|个)(.*)(睡|茶)(.*))套餐')
async def sleep(bot: Bot, event: GroupMessageEvent):
    base = 0 if '午' in event.get_plaintext() else 5 * 60 * 60
    length = len(event.get_plaintext())
    sleep_time = base + round(
        math.sqrt(length) * 60 * 30 + 60 * random.randint(-15, 15))
    await util.silence(event, sleep_time, skip_su=False)


BANNED_WORD = ('rbq', 'RBQ', '憨批', '废物', '死妈', '崽种', '傻逼', '傻逼玩意', '没用东西',
               '傻B', '傻b', 'SB', 'sb', '煞笔', 'cnm', '爬', 'kkp', 'nmsl', 'D区',
               '口区', '我是你爹', 'nmbiss', '弱智', '给爷爬', '杂种爬', '爪巴')
예제 #25
0
定义:
    W_cheru = '切' ^ `CHERU_SET`+
    切噜词均以'切'开头,可用字符集为`CHERU_SET`

    L_cheru = {W_cheru ∪ `\\W`}*
    切噜语由切噜词与标点符号连接而成
"""

import re
from itertools import zip_longest

from nonebot.adapters import Event
from nonebot.adapters.cqhttp.message import escape
from src.Service import Service

sv = Service('pcr-cherugo')

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:
예제 #26
0
from nonebot import logger, get_driver
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp.event import GroupDecreaseNoticeEvent, GroupIncreaseNoticeEvent
from src.Service import Service

global_config = get_driver().config

sv1 = Service('group-leave-notice', visible=False)


@sv1.on_notice('group_decrease.leave')
async def leave_notice(bot: Bot, event: GroupDecreaseNoticeEvent):
    await bot.send(event, f"{event.get_user_id()}退群了。")


sv2 = Service('group-welcome', visible=False)


@sv2.on_notice('group_increase')
async def increace_welcome(bot: Bot, event: GroupIncreaseNoticeEvent):
    if event.get_user_id() == bot.self_id:
        return  # ignore myself

    welcomes = global_config.increase_welcomes
    gid = event.group_id
    if gid in welcomes:
        await bot.send(event, welcomes[gid], at_sender=True)
    elif 'default' in welcomes:
        await bot.send(event, welcomes['default'], at_sender=True)
예제 #27
0
from src.privilege import SUPERUSER
from nonebot import on_notice, get_driver
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp.event import GroupDecreaseNoticeEvent, NoticeEvent, PrivateMessageEvent
from src.Service import Service
from nonebot import logger

global_config = get_driver().config

sv = Service('bot_manage',
             visible=False)


@sv.on_notice('group_decrease.kick_me')
async def kick_me_alert(bot: Bot, event: GroupDecreaseNoticeEvent):
    group_id = event.group_id
    operator_id = event.operator_id
    coffee = list(global_config.superusers)[0]
    await bot.send_private_msg(self_id=event.self_id, user_id=coffee, message=f'被Q{operator_id}踢出群{group_id}')

# @sv.on_command('帮助')
# async def help(bot: Bot, event: Event):
#     await bot.send(event, '查看http://asdasdasda/help')

@sv.on_command('广播',aliases={'群发'}, permission=SUPERUSER.permission)
async def su_broadcast(bot: Bot, event: PrivateMessageEvent):
    await sv.broadcast(event.get_plaintext().strip())


@sv.on_command('解除禁言')
async def set_unban(bot: Bot, event: Event):