async def handle(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member): if message.asDisplay() == "搜番": await update_user_call_count_plus1(group, member, UserCalledCount.search, "search") if not await get_setting(group.id, Setting.bangumi_search): return MessageItem( MessageChain.create([Plain(text="搜番功能未开启呐~请联系管理员哦~")]), Normal(GroupStrategy())) try: await app.sendGroupMessage( group, MessageChain.create( [At(member.id), Plain("请在30秒内发送要搜索的图片呐~")])) except AccountMuted: logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!") return None image_get = None message_received = None @Waiter.create_using_function([GroupMessage]) def waiter(event: GroupMessage, waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): nonlocal image_get nonlocal message_received if time.time() - start_time < 30: if all([ waiter_group.id == group.id, waiter_member.id == member.id, len(waiter_message[Image]) == len( waiter_message.__root__) - 1 ]): image_get = True message_received = waiter_message return event else: logger.warning("等待用户超时!BangumiSearchHandler进程推出!") return event bcc = AppCore.get_core_instance().get_bcc() inc = InterruptControl(bcc) start_time = time.time() await inc.wait(waiter) if image_get: logger.success("收到用户图片,启动搜索进程!") try: await app.sendGroupMessage( group, await BangumiSearchHandler.search_bangumi( message_received[Image][0]), quote=message_received[Source][0]) except AccountMuted: logger.error(f"Bot 在群 <{group.name}> 被禁言,无法发送!") pass return None else: return None
async def delete_keyword(app: GraiaMiraiApplication, group: Group, member: Member, message_serialization: str) -> MessageItem: _, keyword = message_serialization.split("#") if re.match(r"\[mirai:image:{.*}\..*]", keyword): keyword = re.findall(r"\[mirai:image:{(.*?)}\..*]", keyword, re.S)[0] if record := await orm.fetchone( select(TriggerKeyword.function).where( TriggerKeyword.keyword == keyword)): await app.sendGroupMessage( group, MessageChain.create([ Plain( text=f"查找到以下信息:\n{keyword} -> {record[0]}\n是否删除?(是/否)") ])) inc = InterruptControl(AppCore.get_core_instance().get_bcc()) @Waiter.create_using_function([GroupMessage]) def confirm_waiter(waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): if all([ waiter_group.id == group.id, waiter_member.id == member.id ]): if re.match(r"[是否]", waiter_message.asDisplay()): return waiter_message.asDisplay() else: return "" result = await inc.wait(confirm_waiter) if not result: return MessageItem( MessageChain.create([Plain(text="非预期回复,进程退出")]), Normal(GroupStrategy())) elif result == "是": try: await orm.delete(TriggerKeyword, [TriggerKeyword.keyword == keyword]) except: logger.error(traceback.format_exc()) return MessageItem( MessageChain.create([Plain(text="发生错误!请查看日志!")]), QuoteSource(GroupStrategy())) return MessageItem( MessageChain.create([Plain(text=f"关键词 {keyword} 删除成功")]), Normal(GroupStrategy())) else: return MessageItem(MessageChain.create([Plain(text="进程退出")]), Normal(GroupStrategy()))
async def wait_confirm(kwargs: dict): """ 一次性模板,用于等待触发对象确认,兼容Group和Friend消息 :param kwargs: 函数传入的dict :return: 若对象发送confirm_command中的其一文本时返回True,反之则返回False """ inc = InterruptControl(bcc) confirm_command = [ "是", "对", '确定', '是吧', '大概是', '也许', '可能', '对的', '是呢', '对呢', '嗯', '嗯呢', '吼啊', '资瓷', '是呗', '也许吧', '对呗', '应该', 'yes', 'y', 'yeah', 'yep', 'ok', 'okay', '⭐', '√' ] if Group in kwargs: @Waiter.create_using_function([GroupMessage]) def waiter(waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): if all([ waiter_group.id == kwargs[Group].id, waiter_member.id == kwargs[Member].id, ]): if waiter_message.asDisplay() in confirm_command: return True else: return False if Friend in kwargs: @Waiter.create_using_function([FriendMessage]) def waiter(waiter_friend: Friend, waiter_message: MessageChain): if all([ waiter_friend.id == kwargs[Friend].id, ]): if waiter_message.asDisplay() in confirm_command: return True else: return False return await inc.wait(waiter)
async def wait_anything(kwargs: dict): inc = InterruptControl(bcc) if Group in kwargs: @Waiter.create_using_function([GroupMessage]) def waiter(waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): if all([ waiter_group.id == kwargs[Group].id, waiter_member.id == kwargs[Member].id, ]): return True if Friend in kwargs: @Waiter.create_using_function([FriendMessage]) def waiter(waiter_friend: Friend, waiter_message: MessageChain): if all([ waiter_friend.id == kwargs[Friend].id, ]): return True return await inc.wait(waiter)
async def add(content: "MessageChain", broadcast: Broadcast, sender: Member, app: Ariadne, group: Group): if not content: inc = InterruptControl(broadcast) await app.sendMessage( group, MessageChain([At(sender), " 请发送要存入回声洞的消息\n" "发送 “取消” 来取消操作"])) @Waiter.create_using_function([GroupMessage]) async def wait_for_chain(chain: MessageChain, i_sender: Member): if i_sender.id == sender.id and i_sender.group.id == sender.group.id: await chain.download_binary() chain = chain.include(Plain, Image) if chain: if chain.asDisplay() != "取消": id: int = db.add_cave(sender.name, chain) await app.sendMessage(group, MessageChain([f"添加成功,ID: {id}"])) else: await app.sendMessage(group, MessageChain(["请发送图片或文本"])) return True try: await inc.wait(wait_for_chain, timeout=60.0) except TimeoutError: await app.sendMessage(group, MessageChain(["操作超时"])) else: await content.download_binary() content = content.include(Plain, Image) if content: id: int = db.add_cave(sender.name, content) await app.sendMessage(group, MessageChain([f"添加成功,ID: {id}"])) else: await app.sendMessage(group, MessageChain(["请发送图片或文本"]))
config.read("tao.ini") bcc = Broadcast(loop=loop) app = GraiaMiraiApplication( broadcast=bcc, connect_info=Session( host="{}:{}".format(config['connect_mirai']['host'],config['connect_mirai']['port']), # 填入 httpapi 服务运行的地址 authKey=config['connect_mirai']['authKey'], # 填入 authKey account=config.getint('connect_mirai','account'), # 机器人的 qq 号 websocket=config.getboolean('connect_mirai','websocket') # Graia 已经可以根据所配置的消息接收的方式来保证消息接收部分的正常运作. ), logger=log.CustomLogger() #继承日志输出的抽象调用方法 ) inc =InterruptControl(bcc) async def netease_cloud_music_hot(some,*member): send_message = MessageChain.create([Plain(wangyiyun.reping())]) if member[0] == (): await app.sendFriendMessage(some, send_message) else: at = MessageChain.create([At(member[0][0].id)]) await app.sendGroupMessage(some,MessageChain.join(at,send_message)) async def netease_cloud_music_get(some,rmsg,*member): m = rmsg.split(' ') if len(m) == 2: send_message = MessageChain.create([Xml(wangyiyun.diange(m[1]))]) else: MessageChain.create([Plain("您输入的参数有误请使用 点歌 [歌曲名] 来进行点歌")])
from sagiri_bot.orm.async_orm import orm from sagiri_bot.core.app_core import AppCore from sagiri_bot.orm.async_orm import KeywordReply from sagiri_bot.utils import user_permission_require from sagiri_bot.control import BlackListControl, Function saya = Saya.current() channel = Channel.current() channel.name("KeywordRespondent") channel.author("SAGIRI-kawaii") channel.description("一个关键字回复插件,在群中发送已添加关键词可自动回复\n" "在群中发送 `添加回复关键词#{keyword}#{reply}` 可添加关键词\n" "在群中发送 `删除回复关键词#{keyword}` 可删除关键词") inc = InterruptControl(AppCore.get_core_instance().get_bcc()) regex_list = [] parse_big_bracket = "\\{" parse_mid_bracket = "\\[" parse_bracket = "\\(" class NumberWaiter(Waiter.create([GroupMessage])): """ 超时Waiter """ def __init__(self, group: Union[int, Group], member: Union[int, Member], max_length: int): self.group = group if isinstance(group, int) else group.id self.member = (member if isinstance(member, int) else member.id) if member else None self.max_length = max_length
from sagiri_bot.message_sender.message_sender import MessageSender # saya_init() saya = Saya.current() channel = Channel.current() channel.name("SayaManager") channel.author("SAGIRI-kawaii") channel.description("插件管理插件" "发送 `已加载插件` 查看已加载插件\n" "发送 `插件详情 [编号|名称]` 可查看插件详情\n" "发送 `[加载|重载|卸载|打开|关闭]插件 [编号|名称]` 可加载/重载/卸载/打开/关闭插件") core = AppCore.get_core_instance() inc = InterruptControl(core.get_bcc()) class SayaManager(AbstractHandler): __name__ = "SayaManager" __description__ = "插件管理" __usage__ = "发送 `已加载插件` 查看已加载插件\n" \ "发送 `插件详情 [编号|名称]` 可查看插件详情\n" \ "发送 `[加载|重载|卸载|打开|关闭]插件 [编号|名称]` 可加载/重载/卸载/打开/关闭插件" @staticmethod async def handle(app: Ariadne, message: MessageChain, group: Group, member: Member) -> MessageItem: # global saya_data if message.asDisplay().strip() == "已加载插件": loaded_channels = SayaManager.get_loaded_channels()
async def delete_keyword(app: GraiaMiraiApplication, message_serialization: str, group: Group, member: Member): try: _, keyword = message_serialization.split("#") except ValueError: return MessageItem( MessageChain.create([ Plain(text="设置格式:\n添加关键词#关键词/图片#回复文本/图片\n"), Plain(text="注:目前不支持文本中含有#!") ]), QuoteSource(GroupStrategy())) keyword = keyword.strip() if re.match(r"\[mirai:image:{.*}\..*]", keyword): keyword = re.findall(r"\[mirai:image:{(.*?)}\..*]", keyword, re.S)[0] if results := orm.fetchall( select(KeywordReply).where(KeywordReply.keyword == keyword)): replies = list() for result in results: content_type = result[1] content = result[2] content_md5 = result[3] replies.append([content_type, content, content_md5]) msg = [Plain(text=f"关键词{keyword}目前有以下数据:\n")] for i in range(len(replies)): msg.append(Plain(text=f"{i + 1}. ")) msg.append( Plain(text=replies[i][1]) if replies[i][0] == "text" else Image.fromUnsafeBytes(base64.b64decode(replies[i][1]))) msg.append(Plain(text="\n")) msg.append(Plain(text="请发送你要删除的回复编号")) try: await app.sendGroupMessage(group, MessageChain.create(msg)) except AccountMuted: return None inc = InterruptControl(AppCore.get_core_instance().get_bcc()) @Waiter.create_using_function([GroupMessage]) def number_waiter(waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): if all([ waiter_group.id == group.id, waiter_member.id == member.id, waiter_message.asDisplay().isnumeric() and 0 < int(waiter_message.asDisplay()) <= len(replies) ]): return int(waiter_message.asDisplay()) elif all([ waiter_group.id == group.id, waiter_member.id == member.id ]): return -1 number = await inc.wait(number_waiter) if number == -1: return MessageItem( MessageChain.create([Plain(text="非预期回复,进程退出")]), Normal(GroupStrategy())) elif 1 <= number <= len(replies): try: await app.sendGroupMessage( group, MessageChain.create([ Plain(text="你确定要删除下列回复吗(是/否):\n"), Plain(text=keyword), Plain(text="\n->\n"), Plain(text=replies[number - 1][1]) if replies[number - 1][0] == "text" else Image.fromUnsafeBytes( base64.b64decode(replies[number - 1][1])) ])) except AccountMuted: return None @Waiter.create_using_function([GroupMessage]) def confirm_waiter(waiter_group: Group, waiter_member: Member, waiter_message: MessageChain): if all([ waiter_group.id == group.id, waiter_member.id == member.id ]): if re.match(r"[是否]", waiter_message.asDisplay()): return waiter_message.asDisplay() else: return "" result = await inc.wait(confirm_waiter) if not result: return MessageItem( MessageChain.create([Plain(text="非预期回复,进程退出")]), Normal(GroupStrategy())) elif result == "是": try: orm.delete( KeywordReply, { "keyword": keyword, "reply_md5": replies[number - 1][2], "reply_type": replies[number - 1][0] }) return MessageItem( MessageChain.create([Plain(text=f"删除成功")]), Normal(GroupStrategy())) except Exception as e: logger.error(traceback.format_exc()) orm.session.rollback() return MessageItem( MessageChain.create([Plain(text=str(e))]), Normal(GroupStrategy())) else: return MessageItem(MessageChain.create([Plain(text="进程退出")]), Normal(GroupStrategy()))
@staticmethod def catch(interface: DispatcherInterface): if interface.name == "u": yield 1 elif interface.annotation == str: yield 12 @staticmethod def afterDispatch(interface: "IDispatcherInterface"): print("in ad.") event = TestEvent() loop = asyncio.get_event_loop() #loop.set_debug(True) broadcast = Broadcast(loop=loop, debug_flag=True) inc = InterruptControl(broadcast) i = 0 l = asyncio.Lock() @broadcast.receiver(TestEvent) async def r(u, v: str, p: "123"): #print("???") global i i += 1 async def main(): """ start = time.time() print("将在 5 s 后开始测试.") for i in range(1, 6):
def InitInterruptControl(bcc: Broadcast): global interruptcontrol interruptcontrol = InterruptControl(bcc)