websocket=True # Graia 已经可以根据所配purecloud.top置的消息接收的方式来保证消息接收部分的正常运作. ) ) @bcc.receiver("FriendMessage") async def friend_message_listener(app: GraiaMiraiApplication, friend: Friend): await app.sendFriendMessage(friend, MessageChain.create([ Plain("你好呀我是Mirai机器人,有事请留言,我的主人看到会回复的哦") ])) # 帮助 @bcc.receiver("GroupMessage", dispatchers=[ # 注意是 dispatcher, 不要和 headless_decorater 混起来 Kanata([FullMatch("帮助")]) ]) async def group_message_handler_help_zh( message: MessageChain, app: GraiaMiraiApplication, group: Group, member: Member, saying: MessageChain ): print(saying.asDisplay()) await app.sendGroupMessage(group, MessageChain.create([ Plain(f"帮助\n发送'帮助'或者'help'来获取更多信息\n新功能\n测缘分(空格)男名(空格)女名 来测俩人缘分,快来试试吧"), Plain(f"\n输入真心话大冒险可以进行娱乐哦") ])) # goodnight @bcc.receiver("GroupMessage", dispatchers=[
from graia.saya import Saya, Channel from graia.saya.builtins.broadcast.schema import ListenerSchema from graia.template import Template import random channel = Channel.current() channel.name("Material") channel.description("发送'learn'获取学❤习❤资❤料") channel.author("I_love_study") #这些都是厚大法考的学习资料 @channel.use( ListenerSchema(listening_events=[GroupMessage], inline_dispatchers=[Kanata([FullMatch('learn')])])) async def learn(app: GraiaMiraiApplication, group: Group, message: MessageChain, member: Member): learning_urls = [ 'http://oss.fk.houdask.com/sys/v/19/10/f64809ee7ccd44319ffddf74c8c8abf7.rar', 'http://oss.fk.houdask.com/sys/v/19/10/3f036ac7d1fc4912b2a11331c3ef33c5.rar', 'http://oss.fk.houdask.com/sys/v/19/10/461c32c3904e44f08b721600fcf32fb7.rar', 'http://oss.fk.houdask.com/sys/v/19/10/192c231fc56c4ca09bffe69856dba705.rar', 'http://oss.fk.houdask.com/sys/v/20/01/5cdc62ab47e1460789a0cd691b572415.zip', 'http://oss.fk.houdask.com/sys/v/20/01/24901a9ebeab4ac5a8bc551572af8c24.zip', 'http://oss.fk.houdask.com/sys/v/20/01/e48ea55b6c8147a9ac90ced8ef3bc80e.rar', 'http://oss.fk.houdask.com/sys/v/20/01/10ebebeae4d14f6aa786537b3adc374d.zip', 'http://oss.fk.houdask.com/sys/v/20/01/51dc2a25b3474022b982191174dda41c.zip', 'http://oss.fk.houdask.com/sys/v/20/01/1043c2175f84478baa8be09ed92aac7c.zip', 'http://oss.fk.houdask.com/sys/v/20/01/d15be5ac6027461794e399402bb8ddec.rar', 'http://oss.fk.houdask.com/sys/v/20/01/0dd665e49ec24999b772475fbf78a65a.zip'
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')]))
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
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}')
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.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'))
from graia.application.message.elements.internal import At, Plain from graia.application.message.parser.kanata import Kanata from graia.application.message.parser.signature import FullMatch from graia.saya import Channel, Saya from graia.saya.builtins.broadcast.schema import ListenerSchema import random saya = Saya.current() channel = Channel.current() @channel.use( ListenerSchema( listening_events=[GroupMessage], inline_dispatchers=[Kanata([FullMatch("随机禁言")])], )) async def jy(app: GraiaMiraiApplication, group: Group, member: Member): randint = random.randint(1, 60) await app.sendGroupMessage( group, MessageChain.create( [At(member.id), Plain(f" 恭喜{member.name}获得{randint}秒的禁言时间!")]), ) try: await app.mute(group, member, randint) except PermissionError: await app.sendGroupMessage( group, MessageChain.create([At(member.id), Plain(" 没管理禁nm")]))
from decimal import Decimal, ROUND_HALF_UP from time import time from math import radians, tan, cos, sin import shlex channel = Channel.current() channel.name("5000M") channel.description("发送'5000m [词] [词]'制作'5000兆円欲しい'图片") channel.author("I_love_study") @channel.use( ListenerSchema(listening_events=[GroupMessage], inline_dispatchers=[ Kanata([FullMatch('5000m'), RequireParam('para')]) ])) async def give5000M(app: GraiaMiraiApplication, group: Group, para: MessageChain): if len(tag := shlex.split(para.asDisplay())) == 2: pic = BytesIO() genImage(*tag).save(pic, format='PNG') msg = [Image.fromUnsafeBytes(pic.getvalue())] else: msg = [Plain('消息有误,请重试')] await app.sendGroupMessage(group, MessageChain.create(msg)) _round = lambda f, r=ROUND_HALF_UP: int( Decimal(str(f)).quantize(Decimal("0"), rounding=r))
lsps = Group_save.get('data/lsps.json') ultra_admin = [] apikey = '' def ero_check(group: Group): if ero_setting.get_item(group.id).get('status') is not True: raise ExecutionStop() bcc = get.bcc() @bcc.receiver(GroupMessage, headless_decorators=[judge.config_check(__name__)], dispatchers=[Kanata([FullMatch('涩图来'), OptionalParam('tag')])]) async def ero_pic(app: GraiaMiraiApplication, group: Group, member: Member, tag): global ero_f, apikey g_setting = ero_setting.get_item(group.id) getup = datetime.fromisoformat(date.today().isoformat() + "T06:30") sleep = datetime.fromisoformat(date.today().isoformat() + "T23:00") lsp = lsps.get_item(group.id, member.id, date.today()) if not g_setting.get('status'): msg = '我们这个群是正经群,不搞这些玩意的' elif member.id in g_setting.get('black_list', []): msg = '黑名单人是没有涩图看的' elif not getup < datetime.now() < sleep and not g_setting.get('compel'): msg = '我要睡觉,不要打扰我' elif lsp.get('t',
_setu_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=[FriendMessage], inline_dispatchers=[ Kanata([FullMatch(_setu_commond), OptionalParam(name="keyword")]) ])) async def friend_setu_handler(app: GraiaMiraiApplication, friend: Friend, keyword: MessageChain): if keyword is None: keyword_str = "" else: keyword_str = keyword.asDisplay().strip() res = await setu.get_setu_with_keyword(True, keyword_str) if res is None: await app.sendFriendMessage( friend, MessageChain.create([Plain("没有找到这个tag...")])) elif res is False: await app.sendFriendMessage(friend, MessageChain.create([Plain("请求好像失败了QAQ")]))
saya = Saya.current() bcc = saya.broadcast channel = Channel.current() inc = InterruptControl(bcc) channel.name(__name__) channel.description(f"{__description__}\n使用方法:\n\u3000{__usage__}") channel.author(__author__) @channel.use(ListenerSchema( listening_events=[ApplicationLaunched] )) async def app_launch(app: GraiaMiraiApplication): welcome = Welcome().read() await app.sendFriendMessage(master_id, welcome) @channel.use(ListenerSchema( listening_events=[FriendMessage], inline_dispatchers=[Kanata([FullMatch(_restart_commond)])] )) async def app_restart(app: GraiaMiraiApplication, friend: Friend): if friend.id == master_id: await app.sendFriendMessage(master_id, MessageChain.create([Plain('bot即将重启,请输入yes进行确认')])) await inc.wait( FriendMessageInterrupt( master_id, custom_judgement=lambda x: x.messageChain.asDisplay().startswith("yes"))) python = sys.executable os.execl(python, python, *sys.argv)
__name__ = "GithubHotSearch" __description__ = "获取当前github热搜(trend)" __author__ = "SAGIRI-kawaii" __usage__ = "在群内发送 github热搜 即可" 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('github热搜')])])) async def group_message_listener(app: GraiaMiraiApplication, group: Group): try: await app.sendGroupMessage(group, await get_github_hot()) except AccountMuted: pass async def get_github_hot() -> MessageChain: url = "https://github.com/trending" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36" } async with aiohttp.ClientSession() as session: async with session.get(url=url, headers=headers) as resp:
# 插件信息 __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()
channel.author(__author__) # 账号信息 _account_path = "./modules/AutoPix/pixiv_account.json" # 图片保存路径 _img_save_path = "./pixiv_img" # 代理(可无) _proxy = "socks5://192.168.0.60:2089" # 手动更新命令 _commond = ".pixup" pix = Pix(_account_path, _img_save_path, proxy=_proxy) @channel.use( ListenerSchema(listening_events=[FriendMessage], inline_dispatchers=[Kanata([FullMatch(_commond)])])) async def pix_update(app: GraiaMiraiApplication, friend: Friend): logger.info("收到手动更新请求,正在处理") msg_list = await pix.run(friend.id) if not msg_list: await app.sendFriendMessage( friend, MessageChain.create([Plain("无更新哟~再等一会吧~~")])) elif isinstance(msg_list, list): async def send_msg_list(m_list): for msg in m_list: await app.sendFriendMessage(master_id, MessageChain.create(msg)) await asyncio.sleep(1) await app.sendFriendMessage(master_id, MessageChain.create([Plain("结束")]))
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:
saya = Saya.current() channel = Channel.current() bcc = saya.broadcast inc = InterruptControl(bcc) channel.name(__name__) channel.description(f"{__description__}\n使用方法:{__usage__}") channel.author(__author__) # 填入你的saucenao_cookie saucenao_cookie = "" @channel.use( ListenerSchema(listening_events=[GroupMessage], inline_dispatchers=[Kanata([FullMatch('搜图')])])) async def pixiv_image_searcher(app: GraiaMiraiApplication, member: Member, group: Group): image_get: bool = False message_received = None try: await app.sendGroupMessage( group, MessageChain.create( [At(member.id), Plain("请在30秒内发送要搜索的图片呐~(仅支持pixiv图片搜索呐!)")])) except AccountMuted: return None @Waiter.create_using_function([GroupMessage])
from utils import messagechain_to_img # 插件信息 __name__ = "TraceMoeImageSearcher" __description__ = "TraceMoe以图搜番" __author__ = "SAGIRI-kawaii" __usage__ = "发送搜番后发送图片即可" platform = SagiriGraiaPlatformCore.get_platform_instance() loop = platform.get_loop() bcc = platform.get_bcc() inc = InterruptControl(bcc) app: GraiaMiraiApplication = platform.get_app() @bcc.receiver(GroupMessage, dispatchers=[Kanata([FullMatch('搜番')])]) async def tracemoe_image_searcher(app: GraiaMiraiApplication, member: Member, group: Group): image_get: bool = False message_received = None try: await app.sendGroupMessage( group, MessageChain.create([At(member.id), Plain("请在30秒内发送要搜索的图片呐~")])) except AccountMuted: return None @Waiter.create_using_function([GroupMessage])
group, MessageChain.create([Plain("开始执行.")])) 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"]:
from sagiri_core.core import SagiriGraiaPlatformCore # 插件信息 __name__ = "PluginsManager" __description__ = "SagiriGraiaPlatform的插件管理器(目前还没啥功能)" __author__ = "SAGIRI-kawaii" __usage__ = "" platform: SagiriGraiaPlatformCore = SagiriGraiaPlatformCore.get_platform_instance( ) loop = platform.get_loop() bcc = platform.get_bcc() app: GraiaMiraiApplication = platform.get_app() @bcc.receiver("GroupMessage", dispatchers=[Kanata([FullMatch('plugins')])]) async def plugins_manager(app: GraiaMiraiApplication, group: Group): plugins = platform.get_plugins() text = "SagiriGraiaPlatform\n\n目前已加载插件:" serial_number = 1 for plugin in plugins: text += f"\n\n{serial_number}. {plugin['name']}:" text += f"\n{plugin['description']}" serial_number += 1 text += "\n\n你可输入 'pluginHelp 插件序号' 命令来查看插件详情" await app.sendGroupMessage(group, MessageChain.create([Plain(text=text)])) @bcc.receiver("GroupMessage", dispatchers=[Kanata([RegexMatch('pluginHelp ([0-9]*)')])]) async def plugins_manager(app: GraiaMiraiApplication, group: Group,
_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("输入参数不合法")]))
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)]))
from PIL import Image as IMG, ImageDraw from io import BytesIO import shlex words2img = EmojiWriter().text2pic channel = Channel.current() channel.name("PornHubStyleWord") channel.description("发送'ph [字] [字]'获取熟悉的ph图标") channel.author("I_love_study") @channel.use( ListenerSchema( listening_events=[GroupMessage], inline_dispatchers=[Kanata([FullMatch('ph'), RequireParam('para')])])) async def pornhub(app: GraiaMiraiApplication, group: Group, member: Member, para: MessageChain, message: MessageChain): if len(tag := shlex.split(para.asDisplay())) == 2: pic = make_porn_logo(*tag, 109) #必须是109(emoji) msg = [Image.fromUnsafeBytes(pic)] else: msg = [Plain('消息有误,请重试')] await app.sendGroupMessage(group, MessageChain.create(msg)) def make_porn_logo(left: str, right: str, font_size: int): gap = int(font_size / 4) right_font = words2img(right, (0, 0, 0), font_size) r_wide, r_height = right_font.size
__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"]
__usage__ = "发送'.帮助'即可" _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=[FriendMessage], inline_dispatchers=[Kanata([FullMatch(_commond)])])) async def friend_listener(app: GraiaMiraiApplication, friend: Friend): out = table.img_bytes await app.sendFriendMessage( friend, MessageChain.create([Img.fromUnsafeBytes(out.getvalue())])) @channel.use( ListenerSchema(listening_events=[GroupMessage], inline_dispatchers=[Kanata([FullMatch(_commond)])])) async def group_listener(app: GraiaMiraiApplication, group: Group): out = table.img_bytes await app.sendGroupMessage( group, MessageChain.create([Img.fromUnsafeBytes(out.getvalue())]))
loop = asyncio.get_event_loop() 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) ])
@channel.use(SchedulerSchema(timer=every_custom_hours(5))) async def check_news_update(app: GraiaMiraiApplication): if not news.is_update: await news.update() if news.is_update: out_msg = MessageChain.create( [Image.fromUnsafeBytes(news.img_bytes)]) group_list = await app.groupList() for group in group_list: await app.sendGroupMessage(group.id, out_msg) await app.sendFriendMessage(master_id, out_msg) @channel.use( ListenerSchema(listening_events=[GroupMessage], inline_dispatchers=[Kanata([FullMatch("今日新闻")])])) async def send_news(app: GraiaMiraiApplication, group: Group): if not news.is_update: await news.update() out_msg = MessageChain.create( [Plain("每日新闻每天九点半更新哦~"), Image.fromUnsafeBytes(news.img_bytes)]) await app.sendGroupMessage(group.id, out_msg) class DailyNews: def __init__(self): self.is_update: bool = True self.img_name: Optional[str] = None self.img_bytes = None self.api_url: str = "http://api.soyiji.com//news_jpg"