bcc = Broadcast(loop=loop)
'''
kanata 是匹配对话框中的第一个元素。当且仅当发送的消息中第一个元素为文本时可用。
FullMatch是从第一个文本开始进行匹配的
RegexMatch使用正则进行匹配,返回匹配的部分的后面剩余的部分。
RequireParm 是指定前一个匹配结果的名称,没有就不满足条件
OptionalParam 是指定前一个匹配结果的名称,是一个可选条件。不满足时为None
'''


@bcc.receiver(
    "GroupMessage",
    dispatchers=[
        Kanata(
            [FullMatch("test full match:"),
             RequireParam("full_match_result")],
            stop_exec_if_fail=True)
    ])
def test_full_match(full_match_result, event: GroupMessage):
    print(full_match_result)


@bcc.receiver("GroupMessage",
              dispatchers=[
                  Kanata([
                      RegexMatch(r"test regex match:(.*)"),
                      RequireParam("regex_match_result")
                  ],
                         stop_exec_if_fail=True)
              ])
def test_regex_match(regex_match_result, event: GroupMessage):
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 #3
0
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
        reponse = await r.text()
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}')
            for live_id in dd_data[name]['room_id']
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 #6
0
_commond = ".帮助"

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

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


@channel.use(
    ListenerSchema(
        listening_events=[GroupMessage],
        inline_dispatchers=[Kanata([FullMatch("cy5"),
                                    RequireParam("text")])]))
async def send_img(app: GraiaMiraiApplication, group: Group,
                   text: MessageChain):
    text_list = text.asDisplay().strip().split()
    logger.info(text_list)
    if len(text_list) == 2:
        logger.info(f"触发cy5:[{text_list[0]},{text_list[1]}]")
        url = f"https://api.dihe.moe/5000choyen/?upper={text_list[0]}&lower={text_list[1]}"
        async with aiohttp.request("GET", url) as res:
            img_bytes = await res.read()
        await app.sendGroupMessage(
            group.id, MessageChain.create([Image.fromUnsafeBytes(img_bytes)]))
    else:
        await app.sendGroupMessage(group.id,
                                   MessageChain.create([Plain("输入参数不合法")]))
Example #7
0
async def command_handler(app: GraiaMiraiApplication, group: Group):
    infos = await apis.AuthlibInjectorLatest.get()
    _message = f'authlib-injector 最新版本:{infos.version}\n{infos.download_url}'
    await app.sendGroupMessage(group, MessageChain.create([Plain(_message)]))


@bcc.receiver(GroupMessage, dispatchers=[Kanata([CommandMatch('csl.latest', False)])])
async def command_handler(app: GraiaMiraiApplication, group: Group):
    infos = await apis.CustomSkinLoaderLatest.get()
    _message = f'''CustomSkinLoader 最新版本:{infos.version}
Forge: {infos.downloads.Forge}
Fabric: {infos.downloads.Fabric}'''
    await app.sendGroupMessage(group, MessageChain.create([Plain(_message)]))


@bcc.receiver(GroupMessage, dispatchers=[Kanata([CommandMatch('csl'), RequireParam(name='params')])])
async def command_handler(app: GraiaMiraiApplication, group: Group, params: MessageChain):
    player_name = params.asDisplay()
    result = await apis.CustomSkinLoaderApi.get('https://mcskin.littleservice.cn/csl', player_name)
    if not result.existed:
        _message = f'「{player_name}」不存在'
    else:
        _message = f'''「{player_name}」
Skin: {result.skins.slim[:7] or result.skins.default[:7]} [{result.skin_type}]
Cape: {result.cape[:7] if result.cape else None}'''
    await app.sendGroupMessage(group, MessageChain.create([Plain(_message)]))


@bcc.receiver(GroupMessage, dispatchers=[Kanata([CommandMatch('ygg'), RequireParam(name='params')])])
async def command_handler(app: GraiaMiraiApplication, group: Group, params: MessageChain):
    player_name = params.asDisplay()
Example #8
0
                    return event

            # await asyncio.wait_for(waiter, 60)
            try:
                await asyncio.wait_for(inc.wait(waiter), timeout=10)
            except asyncio.TimeoutError:
                await app.sendGroupMessage(
                    group, MessageChain.create([Plain("命令超时")]))
            await app.sendGroupMessage(group,
                                       MessageChain.create([Plain("执行完毕.")]))


@bcc.receiver(
    "GroupMessage",
    dispatchers=[Kanata([FullMatch("/"),
                         RequireParam(name="command")])])  # 配置工具
async def group_settings(message: MessageChain, app: GraiaMiraiApplication,
                         group: Group, member: Member, command: MessageChain):
    if member.id == Admin:
        commands = command.asDisplay().split(" ")
        # await app.sendGroupMessage(group, MessageChain.create([Plain("执行命令ing")]))
        if commands[0] == "reload":
            global settings, ScheduleGroup, TestGroup
            settings = json.load(open("./Settings.json", encoding='utf-8'))
            ScheduleGroup = []
            TestGroup = []
            for i in settings["Group"]:
                if i["function"]["Schedule"]:
                    ScheduleGroup.append(i["id"])
                if i["function"]["test"]:
                    TestGroup.append(i["id"])
Example #9
0
                        logger.error("发送时出错:")
                        logger.error(e)
                        await app.sendFriendMessage(
                            account,
                            MessageChain.create(
                                [Plain("发送时出错,具体类型请看日志,等待450s重试")]))
                        await asyncio.sleep(450)
                        await send_msg_list(msg_list)
    else:
        logger.info("不进行更新")


@channel.use(
    ListenerSchema(listening_events=[FriendMessage],
                   inline_dispatchers=[
                       Kanata([FullMatch(".pixauto"),
                               RequireParam("code")])
                   ]))
async def set_auto_pix(app: GraiaMiraiApplication, friend: Friend,
                       code: MessageChain):
    if friend.id == master_id:
        commond = code.asDisplay().strip()
        if commond == "0":
            pix.auto = False
            await app.sendFriendMessage(
                friend, MessageChain.create([Plain("自动更新已关闭")]))
        if commond == "1":
            pix.auto = True
            await app.sendFriendMessage(
                friend, MessageChain.create([Plain("自动更新已开启")]))
from graia.application.event.messages import GroupMessage
from graia.application.message.elements.internal import *
from graia.application.message.chain import MessageChain
from graia.application.message.parser.kanata import Kanata
from graia.application.message.parser.signature import FullMatch, RequireParam
from graia.application.group import Group, Member
from graia.saya import Channel
from graia.saya.builtins.broadcast.schema import ListenerSchema

channel = Channel.current()

data_path = Path(__file__).parent / 'dd_info.yml'

@channel.use(ListenerSchema(
    listening_events=[GroupMessage],
    inline_dispatchers=[Kanata([FullMatch('组织添加 '), RequireParam('tag')])]
    ))
async def dd_group_add(app: GraiaMiraiApplication, group: Group, member: Member, tag: MessageChain):
	name = tag.asDisplay().strip()
	dd_data = yaml.safe_load(data_path.read_text(encoding = 'UTF-8'))
	dd_data.append(name)
	data_path.write_text(yaml.safe_dump(dd_data), encoding = 'UTF-8')
	await app.sendGroupMessage(group, MessageChain.create([Plain(f'增加团队"{name}"成功')]))

@channel.use(ListenerSchema(
    listening_events=[GroupMessage],
    inline_dispatchers=[Kanata([FullMatch('组织删除 '), RequireParam('tag')])]
    ))
async def dd_group_del(app: GraiaMiraiApplication, group: Group, member: Member, tag: MessageChain):
	name = tag.asDisplay().strip()
	dd_data = yaml.safe_load(data_path.read_text(encoding = 'UTF-8'))
Example #11
0

@bcc.receiver(GroupMessage,
              dispatchers=[Kanata([CommandMatch('csl.latest', False)])])
async def command_csl_latest(app: GraiaMiraiApplication, group: Group):
    infos = await apis.CustomSkinLoaderLatest.get()
    _message = f'''CustomSkinLoader 最新版本:{infos.version}
Forge: {infos.downloads.Forge}
Fabric: {infos.downloads.Fabric}'''
    await app.sendGroupMessage(group, MessageChain.create([Plain(_message)]))


@bcc.receiver(
    GroupMessage,
    dispatchers=[Kanata([CommandMatch('csl'),
                         RequireParam(name='params')])])
async def command_csl(app: GraiaMiraiApplication, group: Group,
                      params: MessageChain):
    player_name = params.asDisplay()
    result = await apis.CustomSkinLoaderApi.get(
        'https://mcskin.littleservice.cn/csl', player_name)
    if not result.existed:
        _message = f'「{player_name}」不存在'
    else:
        _message = f'''「{player_name}」
Skin: {result.skins.slim[:7] or result.skins.default[:7]} [{result.skin_type}]
Cape: {result.cape[:7]}'''
    await app.sendGroupMessage(group, MessageChain.create([Plain(_message)]))


@bcc.receiver(
Example #12
0
                    for j in err:
                        msg.append(Plain(j))
                        msg.append(Plain(f"\n"))
                await app.sendGroupMessage(group, MessageChain.create(msg))
            '''
            for i in result:
                await app.sendGroupMessage(group, MessageChain.create([
                    At(i)
                ]))
'''

# yf.yf()
# 缘分测定小程序
@bcc.receiver("GroupMessage", dispatchers=[
    # 注意是 dispatcher, 不要和 headless_decorater 混起来
    Kanata([FullMatch("测缘分"), RequireParam(name="saying")])
])
async def group_message_handler_yf(
    message: MessageChain,
    app: GraiaMiraiApplication,
    group: Group, member: Member,
    saying: MessageChain
):
    print(saying.asDisplay())
    try:
        temp_yf = saying.asDisplay()[1:]
        temp_yf = temp_yf.split(" ")
        print(temp_yf)
        temp_yf = yf.yf(temp_yf[0],temp_yf[1])
        await app.sendGroupMessage(group, MessageChain.create([
            Plain(temp_yf)