Example #1
0
from graia.saya import Channel, Saya
from graia.saya.builtins.broadcast.schema import ListenerSchema
from graia.saya.event import SayaModuleInstalled

saya = Saya.current()
channel = Channel.current()


@channel.use(ListenerSchema(listening_events=[SayaModuleInstalled]))
async def module_listener(event: SayaModuleInstalled):
    print(f"{event.module}::模块加载成功!!!")
Example #2
0
IMAGE_BASE_PATH = f"{os.getcwd()}/statics/memes/"
THUMB_BASE_PATH = f"{os.getcwd()}/statics/memes/"
DEFAULT_FONT = 'SourceHanSansSC-Regular.otf'
OVER_LENGTH_MSG = '文字长度过长,请适当缩减'
BREAK_LINE_MSG = '文字长度过长,请手动换行或适当缩减'


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([
                UnionMatch("nokia", "鲁迅说", "王境泽", "喜报", "记仇", "狂爱", "狂粉", "低语",
                           "别说了", "一巴掌", "为所欲为", "馋身子", "切格瓦拉", "谁反对", "连连看",
                           "压力大爷", "你好骚啊", "食屎啦你", "五年", "滚屏") @ "prefix",
                RegexMatch(r"[\s\S]+") @ "content"
            ])
        ],
        decorators=[
            FrequencyLimit.require("memes", 2),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]))
async def memes(app: Ariadne, message: MessageChain, group: Group,
                prefix: RegexResult, content: RegexResult):
    prefix = prefix.result.asDisplay().strip()
    content = [content.result.asDisplay()]
    result = None
    if prefix == "nokia":
        result = await Memes.make_nokia(content)
    elif prefix == "鲁迅说":
Example #3
0
from lxml import etree

headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                       'Chrome/81.0.4044.69 Safari/537.36 Edg/81.0.416.34'}

channel = Channel.current()

channel.name("BaiduSearch")
channel.description("发送'百科 [词语]'获取拜读百科词条\n发送热点获取百度热点Top10")
channel.author("I_love_study")


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Kanata([FullMatch('百科'),
                               RequireParam(name='tag')])
                   ]))
async def bdbk(app: GraiaMiraiApplication, group: Group, member: Member,
               tag: MessageChain):
    tags = tag.asDisplay().strip().split(' ', 1)

    bdurl = f'https://baike.baidu.com/item/{urllib.parse.quote(tags[0])}?force=1'
    async with aiohttp.request("GET",
                               bdurl,
                               headers=headers,
                               allow_redirects=True) as r:
        if str(r.url) == 'https://baike.baidu.com/error.html':
            await app.sendGroupMessage(
                group, MessageChain.create([Plain('sorry,百科并没有相关信息')]))
            return
Example #4
0
channel.description("随机餐点")

with open(str(Path(__file__).parent.joinpath("food.json")),
          "r",
          encoding="utf-8") as r:
    food = json.loads(r.read())


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Twilight([
                           RegexMatch(r"[随隨][机機]"),
                           UnionMatch("早餐", "午餐", "晚餐") @ "option"
                       ])
                   ],
                   decorators=[
                       FrequencyLimit.require("random_food", 2),
                       Function.require(channel.module),
                       BlackListControl.enable(),
                       UserCalledCountControl.add(
                           UserCalledCountControl.FUNCTIONS)
                   ]))
async def random_meal(app: Ariadne, message: MessageChain, group: Group,
                      option: MatchResult):
    option = option.result.asDisplay()
    main_amount = 1 if option == "早餐" else 2
    dish = []
    if randrange(101) < 5:
        return "没得吃!"
    if randrange(2) if option != "午餐" else 1:
        dish.append(random.choice(food[option]["drink"]))
from io import BytesIO
import numpy as np

np.seterr(divide="ignore", invalid="ignore")

channel = Channel.current()

channel.name("GhostTank")
channel.description("发送'ghost_tank [图][图]'获取幻影坦克黑白图")
channel.author("I_love_study")


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Kanata([FullMatch('ghost_tank'),
                               RequireParam('para')])
                   ]))
async def ghost_tank(app: GraiaMiraiApplication, group: Group, member: Member,
                     para: MessageChain):
    if len(p := messages.get(Image)) == 2:
        pics = asyncio.gather(*[i.http_to_bytes() for i in p])
        b = bytesIO()
        gray_car(*pics).save(b, format='PNG')
        await app.sendGroupMessage(
            group, MessageChain.create([Image.fromUnsafeBytes(b.getvalue())]))
    else:
        await app.sendGroupMessage(
            group, MessageChain.create([Plain('你这图,数量不对啊kora')]))

Example #6
0
from graia.saya import Saya, Channel
from graia.saya.builtins.broadcast.schema import ListenerSchema
from graia.saya.event import SayaModuleInstalled
from graia.application.entry import FriendMessage, GraiaMiraiApplication, MessageChain, Plain

saya = Saya.current()
channel = Channel.current()


@channel.use(ListenerSchema(listening_events=[SayaModuleInstalled]))
async def module_listener(event: SayaModuleInstalled):
    print(f"{event.module}::模块加载成功!!!")


@channel.use(ListenerSchema(listening_events=[FriendMessage]))
async def hello_world(app: GraiaMiraiApplication, event: FriendMessage):
    await app.sendFriendMessage(event.sender,
                                MessageChain.create([Plain("hello world")]))
Example #7
0
channel = Channel.current()

channel.name("GithubInfo")
channel.author("SAGIRI-kawaii")
channel.description("可以搜索Github项目信息的插件,在群中发送 `/github [-i] {项目名}`")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([
                FullMatch("/github"),
                ArgumentMatch("-i", "-image", action="store_true", optional=True) @ "image",
                RegexMatch(r"[^\s]+") @ "keyword"
            ])
        ],
        decorators=[
            FrequencyLimit.require("github_info", 2),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]
    )
)
async def github_info(app: Ariadne, message: MessageChain, group: Group, image: ArgResult, keyword: RegexResult):
    image = image.matched
    keyword = keyword.result.asDisplay()
    url = "https://api.github.com/search/repositories?q="
    img_url = "https://opengraph.githubassets.com/c9f4179f4d560950b2355c82aa2b7750bffd945744f9b8ea3f93cc24779745a0/"
    async with get_running(Adapter).session.get(url=url + keyword) as resp:
        result = (await resp.json())["items"]
Example #8
0
channel.author("SAGIRI-kawaii")
channel.description("生成CP文的插件,在群中发送 `/cp {攻名字} {受名字}`")

with open(f"{os.getcwd()}/statics/cp_data.json", "r", encoding="utf-8") as r:
    cp_data = json.loads(r.read())


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Twilight([
                           FullMatch("/cp"),
                           RegexMatch(r"[^\s]+") @ "attack",
                           RegexMatch(r"[^\s]+") @ "defence"
                       ])
                   ],
                   decorators=[
                       FrequencyLimit.require("cp_generator", 1),
                       Function.require(channel.module),
                       BlackListControl.enable(),
                       UserCalledCountControl.add(
                           UserCalledCountControl.FUNCTIONS)
                   ]))
async def cp_generator(app: Ariadne, message: MessageChain, group: Group,
                       attack: RegexResult, defence: RegexResult):
    attack = attack.result.asDisplay()
    defence = defence.result.asDisplay()
    template = random.choice(cp_data["data"])
    content = template.replace("<攻>", attack).replace("<受>", defence)
    await app.sendGroupMessage(group,
                               MessageChain(content),
Example #9
0
config = core.get_config()
proxy = config.proxy if config.proxy != "proxy" else ""
image_cache = config.data_related.get("lolicon_image_cache")
data_cache = config.data_related.get("lolicon_data_cache")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight(
                [
                    FullMatch("来点"),
                    RegexMatch(r"[^\s]+") @ "keyword",
                    RegexMatch(r"[色涩瑟]图$"),
                ]
            )
        ],
        decorators=[
            FrequencyLimit.require("lolicon_keyword_searcher", 2),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.SETU),
        ],
    )
)
async def lolicon_keyword_searcher(
    app: Ariadne, message: MessageChain, group: Group, keyword: RegexResult
):
    keyword = keyword.result.asDisplay()
    msg_chain = await get_image(group, keyword)
    if msg_chain.onlyContains(Plain):
channel = Channel.current()

channel.name("BWGrass")
channel.author("SAGIRI-kawaii")
channel.description("一个生成黑白草图的插件,在群中发送 `黑白[草]图 内容 图片` 即可")

core = AppCore.get_core_instance()
config = core.get_config()


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Twilight([
                           FullMatch("黑白"),
                           FullMatch("草", optional=True),
                           FullMatch("图"),
                           RegexMatch(r".+") @ "content",
                           ElementMatch(Image) @ "image"
                       ])
                   ]))
async def black_white_grass(app: Ariadne, message: MessageChain, group: Group,
                            member: Member, content: RegexResult,
                            image: ElementResult):
    if result := await BWGrass.handle(app, message, group, member, content,
                                      image):
        await MessageSender(result.strategy).send(app, result.message, message,
                                                  group, member)


class BWGrass(AbstractHandler):
    __name__ = "BWGrass"
import aiohttp
from datetime import date, datetime
from PIL import Image as IMG, ImageDraw, ImageFont
from io import BytesIO

channel = Channel.current()

channel.name("AnimeTimeSchedule")
channel.description("发送anime/anime tomorrow/anime yesterday获取昨/今/明的番剧时刻表")
channel.author("I_love_study")


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Kanata([FullMatch('anime'),
                               OptionalParam('para')])
                   ]))
async def anime(app: GraiaMiraiApplication, group: Group,
                message: MessageChain, member: Member, para):
    today = int(datetime.fromisoformat(date.today().isoformat()).timestamp())
    date2ts = {
        'yesterday': today - 86400,
        '': today,
        'tomorrow': today + 86400
    }
    d = para.asDisplay().strip() if isinstance(para, MessageChain) else ''

    if d in date2ts:
        date_ts = date2ts[d]
    else:
# 插件信息
__name__ = "ZhihuHotSearch"
__description__ = "获取当前知乎热搜"
__author__ = "SAGIRI-kawaii"
__usage__ = "在群内发送 知乎 即可"

saya = Saya.current()
channel = Channel.current()

channel.name(__name__)
channel.description(f"{__description__}\n使用方法:{__usage__}")
channel.author(__author__)


@channel.use(ListenerSchema(listening_events=[GroupMessage], inline_dispatchers=[Kanata([FullMatch('知乎')])]))
async def group_message_listener(app: GraiaMiraiApplication, group: Group):
    try:
        await app.sendGroupMessage(
            group,
            await get_zhihu_hot()
        )
    except AccountMuted:
        pass


async def get_zhihu_hot() -> MessageChain:
    zhihu_hot_url = "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true"
    async with aiohttp.ClientSession() as session:
        async with session.get(url=zhihu_hot_url) as resp:
            data = await resp.json()
saya = Saya.current()
channel = Channel.current()

channel.name("HotWordsExplainer")
channel.author("SAGIRI-kawaii")
channel.description("一个可以查询热门词的插件,在群中发送 `{keyword}是什么梗`")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([RegexMatch(r"[^\s]+") @ "keyword",
                      FullMatch("是什么梗")])
        ],
        decorators=[
            FrequencyLimit.require("hot_words_explainer", 2),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]))
async def hot_words_explainer(app: Ariadne, message: MessageChain,
                              group: Group, keyword: RegexResult):
    await app.sendGroupMessage(group,
                               await get_result(keyword.result.asDisplay()),
                               quote=message.getFirst(Source))


async def get_result(keyword: str) -> MessageChain:
    url = "https://api.jikipedia.com/go/search_definitions"
    headers = {"Content-Type": "application/json;charset=UTF-8"}
Example #14
0
# 读取gid_pool.json的信息
with open(os.path.join(FILE_PATH, 'gid_pool.json'), 'r',
          encoding='UTF-8') as f:
    group_pool = json.load(f)


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[
                       Twilight([
                           RegexMatch(r"原神"),
                           RegexMatch(r"(10|90|180)") @ "count",
                           RegexMatch(r"连?抽?") @ "suffix"
                       ])
                   ],
                   decorators=[
                       FrequencyLimit.require("gacha", 1),
                       Function.require(channel.module),
                       BlackListControl.enable(),
                       UserCalledCountControl.add(
                           UserCalledCountControl.FUNCTIONS)
                   ]))
@switch()
@blacklist()
@frequency_limit_require_weight_free(1)
async def gacha(app: Ariadne, group: Group, message: MessageChain,
                member: Member, count: RegexResult):
    gid = group.id
    user_id = member.id
    count = int(count.result.asDisplay())
Example #15
0
cred = credential.Credential(user_data["secret_id"], user_data["secret_key"])
http_profile = HttpProfile()
http_profile.endpoint = "tts.tencentcloudapi.com"
client_profile = ClientProfile()
client_profile.httpProfile = http_profile


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([
                FullMatch("说").space(SpacePolicy.FORCE),
                ArgumentMatch("-v", "--voice", type=int, optional=True)
                @ "voice_type",
                WildcardMatch().flags(re.DOTALL) @ "content"
            ])
        ],
        decorators=[
            FrequencyLimit.require("speak", 2),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]))
async def speak(app: Ariadne, message: MessageChain, group: Group,
                voice_type: ArgResult, content: RegexResult):
    text = content.result.asDisplay()
    voice_type = voice_type.result if voice_type.matched else await group_setting.get_setting(
        group.id, Setting.voice)
    if voice_type == "off":
        return None
    if voice := await Speak.aget_voice(text, voice_type):
import math

headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                       'Chrome/81.0.4044.69 Safari/537.36 Edg/81.0.416.34'}

channel = Channel.current()

channel.name("DDSystem")
channel.description('''输入 '直播 [Hololive/Hanayori/Paryi_hop]'
或者 监控室 [Hololive/Hanayori/Paryi_hop]''')
channel.author("I_love_study")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[Kanata([FullMatch('直播 '),
                                    RequireParam('tag')])]))
async def dd_watch(app: GraiaMiraiApplication, group: Group, member: Member,
                   tag: MessageChain):
    dd_data = yaml.safe_load(
        (Path(__file__).parent / 'dd_info.yml').read_text(encoding='UTF-8'))
    name = tag.asDisplay().strip()
    if name not in dd_data:
        await app.sendGroupMessage(group,
                                   MessageChain.create([Plain('未发现你要D的组织')]))
        return
    status_api = "https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom?room_id="
    conn = aiohttp.TCPConnector(limit=5)  #防爆毙
    async with aiohttp.ClientSession(connector=conn) as session:
        tasks = [
            fench(session, f'{status_api}{live_id}')
Example #17
0
host_qq = AppCore.get_core_instance().get_config().host_qq

channel.name("DailyNewspaper")
channel.author("SAGIRI-kawaii")
channel.description("一个定时发送每日日报的插件\n"
                    "主人私聊bot发送 `发送早报` 可在群中发送早报\n"
                    "在群中发送 `今日早报` 可在群中发送早报")


@channel.use(SchedulerSchema(crontabify("30 8 * * *")))
async def something_scheduled(app: Ariadne):
    await send_newspaper(app)


@channel.use(
    ListenerSchema(listening_events=[FriendMessage],
                   inline_dispatchers=[Twilight([FullMatch("发送早报")])]))
async def main(app: Ariadne, friend: Friend):
    if not friend.id == host_qq:
        return None
    await send_newspaper(app)


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[Twilight([FullMatch("今日早报")])]))
async def main(app: Ariadne, group: Group):
    await app.sendMessage(group,
                          MessageChain([Image(data_bytes=await get_image())]))


async def send_newspaper(app: Ariadne):
Example #18
0
core = AppCore.get_core_instance()
bcc = core.get_bcc()
config = core.get_config()
proxy = config.proxy if config.proxy != "proxy" else ''
SAUCENAO_API_KEY = config.functions.get("saucenao_api_key", None)


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([
                UnionMatch("搜图", "识图", "以图搜图"),
                RegexMatch(r"[\s]+", optional=True),
                ElementMatch(Image, optional=True) @ "image"
            ])
        ],
        decorators=[
            FrequencyLimit.require("image_searcher", 3),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]
    )
)
async def image_searcher(app: Ariadne, message: MessageChain, group: Group, member: Member, image: ElementResult):

    @Waiter.create_using_function(listening_events=[GroupMessage])
    async def image_waiter(
        waiter_group: Group, waiter_member: Member, waiter_message: MessageChain
    ):
        if waiter_group.id == group.id and waiter_member.id == member.id:
Example #19
0
from sagiri_bot.control import FrequencyLimit, Function, BlackListControl, UserCalledCountControl

saya = Saya.current()
channel = Channel.current()

channel.name("RandomWife")
channel.author("SAGIRI-kawaii")
channel.description("生成随机老婆图片的插件,在群中发送 `[来个老婆|随机老婆]`")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[Twilight([RegexMatch(r"(来个老婆|随机老婆)$")])],
        decorators=[
            FrequencyLimit.require("random_wife", 4),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]))
async def random_wife(app: Ariadne, message: MessageChain, group: Group):
    await app.sendGroupMessage(
        group,
        MessageChain([
            Image(
                url=
                f"https://www.thiswaifudoesnotexist.net/example-{random.randint(1, 100000)}.jpg"
            )
        ]),
        quote=message.getFirst(Source))
Example #20
0
import matplotlib.font_manager as fm
import numpy as np
from io import BytesIO

__plugin_name__ = '新冠病毒查看'
__plugin_usage__ = '"COVID-19"'

channel = Channel.current()

channel.name("COVID-19")
channel.description("发送'COVID-19'获取新冠确诊病例排名前20的国家")
channel.author("I_love_study")


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[Kanata([FullMatch('COVID-19')])]))
async def COVID(app: GraiaMiraiApplication, group: Group):
    back = await get_COVID_19()
    await app.sendGroupMessage(
        group,
        MessageChain.create([
            Plain("新型冠状病毒前10:\n" + "\n".join(back[0])),
            Image.fromUnsafeBytes(back[1])
        ]))


async def get_COVID_19(Pic=True):
    country_get = []
    headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                       'Chrome/81.0.4044.69 Safari/537.36 Edg/81.0.416.34'}
    async with aiohttp.request(
from graia.application.group import Group, Member
from graia.saya import Saya, Channel
from graia.saya.builtins.broadcast.schema import ListenerSchema
from graia.template import Template
from graiax import silkcoder
from expand import Netease
from expand import transcode

channel = Channel.current()

channel.name("BarMusic")
channel.description("发送'bar_music [歌曲名]'获取语音音乐")
channel.author("I_love_study")

@channel.use(ListenerSchema(
	listening_events=[GroupMessage],
	inline_dispatchers=[Kanata([FullMatch('bar_music'), RequireParam(name = 'tag')])]
	))
async def bar_music(app: GraiaMiraiApplication, group: Group, member: Member, tag: MessageChain):
	if tag.asDisplay().strip() == '':
		await app.sendGroupMessage(group, Template('点啥歌?').render())
		return
	search_data = await Netease.search(tag.asDisplay().strip())
	try:
		download = await Netease.download_song(search_data[0]['id'])
	except Exception as e:
		await app.sendGroupMessage(group, Template('不知道为什么,但是我就是放不了').render())
		return
	music_b = await silkcoder.encode(download, rate=80000, ss=0, t=60)
	await app.sendGroupMessage(group, MessageChain.create([await app.uploadVoice(music_b)]))

Example #22
0
channel = Channel.current()

channel.name("XsList")
channel.author("SAGIRI-kawaii")
channel.description("一个简查老师的插件,发送 `/查老师 {作品名/老师名/图片}` 即可")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([
                FullMatch("/查老师"), RegexMatch(r"[\s]+", optional=True),
                ElementMatch(Image, optional=True) @ "image",
                WildcardMatch(optional=True) @ "keyword"
            ])
        ],
        decorators=[
            FrequencyLimit.require("xslist", 3),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]
    )
)
async def xslist_handler(app: Ariadne, group: Group, keyword: RegexResult, image: ElementResult):
    if image.matched:
        await app.sendGroupMessage(group, await search(data_bytes=await image.result.get_bytes()))
    elif keyword.matched:
        keyword = keyword.result.asDisplay().strip()
        await app.sendGroupMessage(group, await search(keyword=keyword))
    else:
Example #23
0
saya = Saya.current()
channel = Channel.current()

channel.name("AvatarFunPic")
channel.author("SAGIRI-kawaii")
channel.description("一个可以生成头像相关趣味图的插件,在群中发送 `[摸|亲|贴|撕|丢|爬|精神支柱|吞] [@目标|目标qq|目标图片]` 即可")


@channel.use(ListenerSchema(
    listening_events=[GroupMessage],
    inline_dispatchers=[
        Twilight([
            RegexMatch("(摸|亲|贴|撕|丢|爬|精神支柱|吞)") @ "cmd",
            ElementMatch(At, optional=True) @ "at1",
            ElementMatch(At, optional=True) @ "at2",
            RegexMatch(r"[0-9]+", optional=True) @ "qq1",
            RegexMatch(r"[0-9]+", optional=True) @ "qq2",
            ElementMatch(Image, optional=True) @ "img1",
            ElementMatch(Image, optional=True) @ "img2"
        ])
    ]
))
async def avatar_fun_pic(
    app: Ariadne,
    message: MessageChain,
    group: Group,
    member: Member,
    cmd: RegexResult,
    at1: ElementResult,
    at2: ElementResult,
    qq1: RegexResult,
Example #24
0
])

delete_keyword_twilight = Twilight([
    FullMatch(r"删除"),
    FullMatch("群组", optional=True) @ "group_only",
    RegexMatch(r"(模糊|正则)", optional=True) @ "op_type",
    FullMatch("回复关键词#"),
    RegexMatch(r"[^\s]+") @ "keyword"
])


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   inline_dispatchers=[add_keyword_twilight],
                   decorators=[
                       BlackListControl.enable(),
                       Function.require("keyword_respondent",
                                        response_administrator=True,
                                        log=False)
                   ]))
async def add_keyword(app: Ariadne, message: MessageChain, group: Group,
                      member: Member, group_only: RegexResult,
                      op_type: RegexResult, keyword: RegexResult,
                      response: RegexResult):
    if not await user_permission_require(group, member, 2):
        await app.sendGroupMessage(group,
                                   MessageChain("权限不足,爬!"),
                                   quote=message.getFirst(Source))
        return
    op_type = ("regex" if op_type.result.asDisplay() == "正则" else
               "fuzzy") if op_type.matched else "fullmatch"
    response = await message_chain_to_json(response.result)
Example #25
0
__sayamname__ = "coolapk"
__description__ = "获取酷安酷图"
__author__ = "purofle"
__usage__ = "在群内发送 酷图 即可"

saya = Saya.current()
channel = Channel.current()

channel.name(__sayamname__)
channel.author(__author__)
channel.description(f"{__description__}\n使用方法:{__usage__}")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[Kanata([FullMatch("酷安酷图")])],
    ))
async def coolapk(app: GraiaMiraiApplication, group: Group, member: Member):
    await app.sendGroupMessage(
        group, MessageChain.create([At(member.id),
                                    Plain(" 图片发送较慢,请稍等...")]))

    n = await request(
        "https://api.coolapk.com/v6/page/dataList?url=%2Ffeed%2FcoolPictureList%3FfragmentTemplate%3Dflex&title=&subTitle=&page=1"
    )

    choice_dict = random.choice(n)

    url = choice_dict["pic"]
    username = choice_dict["username"]
    tag = choice_dict["tags"]
Example #26
0
from graia.ariadne.message.parser.twilight import Twilight
from graia.ariadne.message.parser.twilight import FullMatch
from graia.ariadne.event.message import Group, GroupMessage
from graia.saya.builtins.broadcast.schema import ListenerSchema

from statics.pero_dog_contents import pero_dog_contents
from sagiri_bot.control import FrequencyLimit, Function, BlackListControl, UserCalledCountControl

saya = Saya.current()
channel = Channel.current()

channel.name("PeroDog")
channel.author("SAGIRI-kawaii")
channel.description("一个获取舔狗日记的插件,在群中发送 `舔` 即可")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[Twilight([FullMatch("舔")])],
        decorators=[
            FrequencyLimit.require("pero_dog", 1),
            Function.require(channel.module),
            BlackListControl.enable(),
            UserCalledCountControl.add(UserCalledCountControl.FUNCTIONS)
        ]
    )
)
async def pero_dog(app: Ariadne, group: Group):
    await app.sendGroupMessage(group, MessageChain(random.choice(pero_dog_contents).replace('*', '')))
Example #27
0
from sagiri_bot.orm.async_orm import orm
from sagiri_bot.orm.async_orm import ChatRecord
from sagiri_bot.control import UserCalledCountControl

saya = Saya.current()
channel = Channel.current()

channel.name("ChatRecorder")
channel.author("SAGIRI-kawaii")
channel.description("一个记录聊天记录的插件,可配合词云等插件使用")


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        decorators=[UserCalledCountControl.add(UserCalledCountControl.CHAT)]))
async def chat_record(message: MessageChain, group: Group, member: Member):
    content = "".join([plain.text for plain in message.get(Plain)]).strip()
    filter_words = re.findall(r"\[mirai:(.*?)\]", content, re.S)
    for i in filter_words:
        content = content.replace(f"[mirai:{i}]", "")
    seg_result = jieba.lcut(content) if content else ''
    await orm.add(
        ChatRecord, {
            "time": datetime.datetime.now(),
            "group_id": group.id,
            "member_id": member.id,
            "persistent_string": message.asPersistentString(),
            "seg": "|".join(seg_result) if seg_result else ''
        })
Example #28
0
    try:
        await gw.github_schedule(app=app, manual=False)
    except:
        pass


twilight = Twilight([
    FullMatch("/github-watch "),
    UnionMatch("disable", "add", "remove", "check", "cache"),
    WildcardMatch()
])


@channel.use(
    ListenerSchema(listening_events=[FriendMessage],
                   # inline_dispatchers=[twilight]
                   ))
async def github_watcher_friend_handler(app: Ariadne, message: MessageChain,
                                        friend: Friend):
    if result := await gw.real_handle(app, message, friend=friend):
        await MessageSender(result.strategy).send(app, result.message, message,
                                                  friend, friend)


@channel.use(
    ListenerSchema(listening_events=[GroupMessage],
                   # inline_dispatchers=[twilight]
                   ))
async def github_watcher_group_handler(app: Ariadne, message: MessageChain,
                                       group: Group, member: Member):
    if result := await gw.real_handle(app, message, group=group,
Example #29
0
from sagiri_bot.message_sender.strategy import Normal
from sagiri_bot.decorators import switch, blacklist
from sagiri_bot.handler.handler import AbstractHandler
from sagiri_bot.message_sender.message_item import MessageItem
from sagiri_bot.message_sender.message_sender import MessageSender

saya = Saya.current()
channel = Channel.current()

channel.name("FakeForward")
channel.author("SAGIRI-kawaii")
channel.description("一个生成转发消息的插件,发送 '/fake [@目标] [内容]' 即可")


@channel.use(ListenerSchema(listening_events=[GroupMessage]))
async def fake_forward(app: Ariadne, message: MessageChain, group: Group,
                       member: Member):
    if result := await FakeForward.handle(app, message, group, member):
        await MessageSender(result.strategy).send(app, result.message, message,
                                                  group, member)


class FakeForward(AbstractHandler):
    __name__ = "FakeForward"
    __description__ = "转发消息生成器"
    __usage__ = "None"

    @staticmethod
    @switch()
    @blacklist()
Example #30
0
                        quote=message_source)
                return False


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[
            Twilight([
                FullMatch("/wordle"),
                ArgumentMatch("-single", action="store_true",
                              optional=True) @ "single_game",
                ArgumentMatch("-group", action="store_true",
                              optional=True) @ "group_game",
                RegexMatch(r"-(l|length)=[0-9]+", optional=True) @ "length",
                RegexMatch(r"-(d|dic)=\w+", optional=True) @ "dic",
                ArgumentMatch(
                    "-help", "-h", action="store_true",
                    optional=True) @ "get_help",
                ArgumentMatch(
                    "-giveup", "-g", action="store_true", optional=True)
                @ "give_up",
                ArgumentMatch(
                    "-s", "-statistic", action="store_true", optional=True)
                @ "statistic"
            ])
        ]))
async def wordle(app: Ariadne, message: MessageChain, group: Group,
                 member: Member, single_game: ArgResult, dic: RegexResult,
                 length: ArgResult, get_help: ArgResult, give_up: ArgResult,
                 statistic: ArgResult) -> NoReturn:
    if get_help.matched: