async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() room = msg.room() # 不处理群消息 if room is None: if text == 'hi' or text == '你好': conversation = from_contact await conversation.ready() await conversation.say('这是自动回复:机器人目前的功能有:\n1. 收到"ding",自动回复"dong dong dong"\n2. 收到"图片",自动回复一张图片') if text == 'ding': conversation = from_contact await conversation.ready() await conversation.say('这是自动回复:dong dong dong') if text == '图片': conversation = from_contact # 从网络上加载图片到file_box img_url = 'https://images.unsplash.com/photo-1470770903676-69b98201ea1c?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1500&q=80' file_box = FileBox.from_url(img_url, name='xx.jpg') await conversation.ready() await conversation.say('这是自动回复:') await conversation.say(file_box)
async def msg_handler(self, msg: Message) -> dict: """ Handling different types of meme, MessageType.MESSAGE_TYPE_IMAGE or MessageType.MESSAGE_TYPE_EMOTICON :param msg: Message :return: dict like this: {'img_name': '/001/001.jpg', 'md5': 'ff7bd2b664bf65962a924912bfd17507'} """ data_param = {} if msg.type() == MessageType.MESSAGE_TYPE_IMAGE: img = await msg.to_file_box() data_param.update(img_name=img.name, data=img.base64) elif msg.type() == MessageType.MESSAGE_TYPE_EMOTICON: import xml.etree.ElementTree as Etree content = msg.payload.text # xml content, need xml parser to extract msg.emoji(cdnurl) msgtree = Etree.fromstring(content) cdn_url = msgtree.find('emoji').attrib['cdnurl'] ret = self.s.get(cdn_url) b64_str = base64.b64encode(ret.content) data_param.update( img_name=str(uuid.uuid4()) + MemeBot.content_type_mapping[ret.headers['Content-Type']], data=b64_str) ret_json = self.s.post( url=config.backend_upload_url, data=data_param).json() # ret keys: img_name, md5, log return ret_json
async def on_message(msg: Message): from_contact = msg.talker() text = msg.text() room = msg.room() conversation: Union[Room, Contact] = from_contact if room is None else room if text == '#ding': await conversation.ready() await conversation.say('dong')
async def message(msg: Message): """back on message""" from_contact = msg.talker() text = msg.text() room = msg.room() if text == '#ding': conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() await conversation.say('dong')
async def on_message(self, msg: Message): if msg.is_self(): # for self testing if msg.type() == MessageType.MESSAGE_TYPE_IMAGE or msg.type( ) == MessageType.MESSAGE_TYPE_EMOTICON: st_time = time.time() try: ret_json = await self.msg_handler(msg) except KeyError as e: # echoing meme image have no keys print(str(e)) return except (requests.exceptions.ConnectionError or requests.exceptions.ConnectTimeout) as e: await msg.say('访问后端出错:' + str(e)) return # example returning json: {'img_name': '/001/001.jpg', 'md5': 'ff7bd2b664bf65962a924912bfd17507'} if ret_json['md5'] in self.cache_dict: # hit cache ret_path: str = self.cache_dict[ret_json['md5']] if 'log' in ret_json: ret_json['log'] += '\n回复图片命中缓存!' else: ret_img = self.s.get( url=self.config_dict['backend']['backend_static_url'] + ret_json['img_name']) if not str(ret_img.status_code).startswith( '2'): # not 2XX response code raise FileNotFoundError( "Can't get img from URL {}, with HTTP status code {}" .format( self.config_dict['backend'] ['backend_static_url'] + ret_json['img_name'], str(ret_img.status_code))) ret_path = os.path.join( self.config_dict['general']['image_temp_dir'], str(uuid.uuid4()) + os.path.extsep + ret_json['img_name'].split('.')[-1]) with open(ret_path, 'wb') as f: f.write(ret_img.content) self.cache_dict[ret_json['md5']] = ret_path ret_json['log'] += '\n前后端交互耗时:%.2fs' % (time.time() - st_time) if self.debug and 'log' in ret_json: await msg.say(ret_json['log']) with open(ret_path, 'rb') as f: content: str = base64.b64encode(f.read()) ret_img = FileBox.from_base64( name=os.path.basename(ret_path), base64=content) # file_box = FileBox.from_url( # 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/' # 'u=1116676390,2305043183&fm=26&gp=0.jpg', # name='ding-dong.jpg') # await msg.say(file_box) # ret_img = FileBox.from_file(ret_path) await msg.say(ret_img)
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() room = msg.room() if text == 'gif': conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() await conversation.say('dong') file_box = FileBox.from_file('./bot.gif') await conversation.say(file_box)
async def message(msg: Message) -> None: """back on message""" from_contact = msg.talker() text = msg.text() room = msg.room() if text == '#ding': conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() await conversation.say('dong') file_box = FileBox.from_url( 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/' 'u=1116676390,2305043183&fm=26&gp=0.jpg', name='ding-dong.jpg') await conversation.say(file_box)
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() room = msg.room() to = msg.to() if room is None and to.contact_id == self.contact_id: # say msg to the bot if text == '#status': msg = 'busy' if self.busy else 'free' await from_contact.say(f'My status: {msg}') await from_contact.say(self.auto_reply_comment) elif text == '#free': await from_contact.say('auto reply stopped.') elif text == '#busy': self.busy = True await from_contact.say('auto reply enabled') else: await from_contact.say(self.auto_reply_comment)
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() room = self.Room.load('19961884194@chatroom') await room.ready() if msg.type() == MessageType.MESSAGE_TYPE_MINI_PROGRAM: mini_program = await msg.to_mini_program() # save the mini-program data as string mini_program_data = asdict(mini_program.payload) # load the min-program loaded_mini_program = self.MiniProgram.create_from_json( payload_data=mini_program_data) await room.say(loaded_mini_program)
async def message(msg: Message): """back on message""" from_contact = msg.talker() text = msg.text() room = msg.room() conversation: Union[Room, Contact] = from_contact if room is None else room global chat_friend if "#关闭闲聊" == text: try: chat_friend.remove(conversation) except Exception as e: return await conversation.ready() await conversation.say('好的,有需要随时叫我') return elif "#开启闲聊" == text: chat_friend.append(conversation) await conversation.ready() await conversation.say('闲聊功能开启成功!现在你可以和我聊天啦!') return if conversation in chat_friend: data = TencentAI(text) await conversation.ready() await conversation.say(data) return if text == '#ding': await conversation.ready() await conversation.say('dong') file_box = FileBox.from_url( 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/' 'u=1116676390,2305043183&fm=26&gp=0.jpg', name='ding-dong.jpg') await conversation.say(file_box)
async def on_message(self, msg: Message): from_contact = msg.talker() if msg.is_self(): # for self testing if msg.type( ) == MessageType.MESSAGE_TYPE_IMAGE or MessageType.MESSAGE_TYPE_EMOTICON: ret_json = await self.msg_handler(msg) # example returning json: {'img_name': '/001/001.jpg', 'md5': 'ff7bd2b664bf65962a924912bfd17507'} if ret_json['md5'] in self.cache_dict: # hit cache ret_path = self.cache_dict[ret_json['md5']] if 'log' in ret_json: ret_json['log'] += '\n回复图片命中缓存!' else: ret_img = self.s.get(url=config.backend_static_url + ret_json['img_name']) if not str(ret_img.status_code).startswith( '2'): # not 2XX response code raise FileNotFoundError( "Can't get img from URL {}, with HTTP status code {}" .format( config.backend_static_url + ret_json['img_name'], str(ret_img.status_code))) ret_path = os.path.join( config.image_temp_dir, str(uuid.uuid4()) + '.' + ret_json['img_name'].split('.')[-1]) with open(ret_path, 'wb') as f: f.write(ret_img.content) self.cache_dict[ret_json['md5']] = ret_path # ret_path = os.path.join(config.image_temp_dir, '0c4baea3-9792-4d07-8ec0-4fd62afd6117.jpg') if self.debug and 'log' in ret_json: await msg.say(ret_json['log']) with open(ret_path, 'rb') as f: content: str = base64.b64encode(f.read()) ret_img = FileBox.from_base64( name=os.path.basename(ret_path), base64=content) await msg.say(ret_img)
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() log.info(from_contact.get_id()) text = msg.text() room = msg.room() if msg.message_type() == bot.Message.Type.MESSAGE_TYPE_RECALLED: recalled_msg = await msg.to_recalled() log.info("撤回的消息 %s" % recalled_msg) if room: # 如果不是@的消息,不用进行回复 if text.find("@") == -1: return # 根据收到的信息,进行回复 log.info(text) if text.find("英语") != -1: send_msg: Union[str, UrlLink] = get_wx_public_article_url_link("田间小站") elif text.find("早上") != -1: send_msg: Union[str, UrlLink] = get_wx_public_article_url_link("早晨简报") elif text.find("天气") != -1: send_msg: Union[str, UrlLink] = get_weather_url_link() elif text.find("北上资金") != -1: send_msg: Union[str, UrlLink] = get_south_north_fund() elif text.find("音乐") != -1: text = text.replace("音乐-", "") send_msg: Union[str, FileBox] = get_music_file_url(text) else: send_msg: str = "开发中。。。。。。。。。。。。。。" conversation: Union[Room, Contact] = from_contact if room is None else room await conversation.ready() await conversation.say(send_msg)
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() room = msg.room() if room: await room.ready() # send contact-card if msg.type() == MessageType.MESSAGE_TYPE_CONTACT: # we can receive the contact-card event, and get the contact from message contact = await msg.to_contact() if text == 'send card': # find one of my friend to send to `from_contact` contacts = await bot.Contact.find_all() if contacts: # send one of my friend to the talker # !! this interface is not supported now await from_contact.say(contacts[0]) print('have sended') elif msg.type() == MessageType.MESSAGE_TYPE_IMAGE: img = await msg.to_file_box() # save the image as local file await img.to_file(f'./{img.name}') # send image file to the room if room: await room.say(img) elif msg.type() == MessageType.MESSAGE_TYPE_VIDEO: video = await msg.to_file_box() # save the video as local file await video.to_file(f'./{video.name}') # send video file to the room if room: await room.say(video) elif msg.type() == MessageType.MESSAGE_TYPE_AUDIO: audio = await msg.to_file_box() # save the audio file as local file await audio.to_file(f'./{audio.name}') # !! we can't send audio to room/contact print('done')
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() type = msg.type() room = msg.room() # username = from_contact.name if username=='KFu': print('message from myself') return # 不处理群消息 # if room is None: if msg.type() == Message.Type.MESSAGE_TYPE_IMAGE: print('__image') image_file_box = await msg.to_file_box() filename='p'+str(time.time())+'.jpg' await image_file_box.to_file(file_path=filename,overwrite=True) inputdata="#pic#"+filename bot = self.bm.run(username, inputdata) if bot is not None: # print('bot',bot) # print('bot replys',bot.replys[-1]) # print('bot.replys_index',bot.replys_index) for i in range(bot.replys_index): bot, rdict = self.tm.run(bot) print('rdict',rdict) if len(list(rdict.keys()))==0:continue if list(rdict.keys())[0] == "str": print('reply str') conversation: Union[ Room, Contact] = from_contact if room is None else room print('ready') await conversation.ready() print(list(rdict.values())[0]) await conversation.say(list(rdict.values())[0]) elif list(rdict.keys())[0] == "pic" or 'mov': print('reply pic/mov') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() try: file_box = FileBox.from_file(list(rdict.values())[0]) except Exception as e: print('file box error',e) file_box='嗯嗯' await conversation.say(file_box) elif msg.type() == Message.Type.MESSAGE_TYPE_TEXT: inputdata = "#str#" + msg.text() print('————text') bot = self.bm.run(username, inputdata) if bot is not None: # print('bot', bot) # print('bot replys',bot.replys[-1]) # print('bot.replys_index',bot.replys_index) for i in range(bot.replys_index): bot, rdict = self.tm.run(bot) print('rdict',rdict) if len(list(rdict.keys()))==0:continue if list(rdict.keys())[0] == "str": print('reply str') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() print('rdict[splitNum:]',list(rdict.values())[0]) await conversation.say(list(rdict.values())[0]) elif list(rdict.keys())[0] == "pic" or 'mov': print('reply pic/mov') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() try: file_box = FileBox.from_file(list(rdict.values())[0]) except Exception as e: print('file box error',e) file_box='嗯嗯' await conversation.say(file_box) else: print('__new for dict') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() await conversation.say('暂时不支持这种类型的消息哦')
async def message(msg: Message): """back on message""" from_contact = msg.talker() username = from_contact.name text = msg.text() room = msg.room() conversation: Union[Room, Contact] = from_contact if room is None else room global chat_friend global splitNum global bm global tm if "吐槽" in text or "图槽" in text or "树洞" in text: chat_friend.append(conversation) inputdata = "#str#" + msg.text() print('————text') bot = bm.run(username, inputdata) if bot is not None: # print('bot', bot) # print('bot replys',bot.replys[-1]) # print('bot.replys_index',bot.replys_index) for i in range(bot.replys_index): bot, rdict = tm.run(bot) print('rdict', rdict) if len(list(rdict.keys())) == 0: continue if list(rdict.keys())[0] == "str": print('reply str') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() print('rdict[splitNum:]', list(rdict.values())[0]) await conversation.say(list(rdict.values())[0]) elif list(rdict.keys())[0] == "pic" or 'mov': print('reply pic/mov') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() try: file_box = FileBox.from_file(list(rdict.values())[0]) except Exception as e: print('file box error', e) file_box = '嗯嗯' await conversation.say(file_box) # await conversation.ready() # await conversation.say('闲聊功能开启成功!现在你可以和我聊天啦!') return if conversation in chat_friend: if username == 'KFu': print('KFu') return if msg.type() == Message.Type.MESSAGE_TYPE_IMAGE: print('__image') image_file_box = await msg.to_file_box() filename = 'p' + str(time.time()) + '.jpg' await image_file_box.to_file(file_path=filename, overwrite=True) inputdata = "#pic#" + filename elif msg.type() == Message.Type.MESSAGE_TYPE_TEXT: print('--text') inputdata = "#str#" + msg.text() bot = bm.run(username, inputdata) if bot is not None: # print('bot', bot) # print('bot replys',bot.replys[-1]) # print('bot.replys_index',bot.replys_index) for i in range(bot.replys_index): bot, rdict = tm.run(bot) print('rdict', rdict) if len(list(rdict.keys())) == 0: continue if list(rdict.keys())[0] == "str": print('reply str') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() print('rdict[splitNum:]', list(rdict.values())[0]) await conversation.say(list(rdict.values())[0]) elif list(rdict.keys())[0] == "pic" or 'mov': print('reply pic/mov') conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() try: file_box = FileBox.from_file( list(rdict.values())[0]) except Exception as e: print('file box error', e) file_box = '嗯嗯' await conversation.say(file_box) # data = TencentAI(text) # await conversation.ready() # await conversation.say(data) return else: print('not in friend') return
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() type = msg.type() room = msg.room() # 不处理群消息 if room is None: if text == 'hi' or text == '你好': conversation = from_contact await conversation.ready() await conversation.say( '这是自动回复:机器人目前的功能有:\n1 收到"ding",自动回复"dong dong dong"\n2 收到"图片",自动回复一张图片\n3 收到两张图片,将第一张图片转换为第二张图片的风格并返回,如需使用此功能,请回复“风格转换”' ) if text == 'ding': conversation = from_contact await conversation.ready() await conversation.say('这是自动回复:dong dong dong') if text == '图片': conversation = from_contact # 从网络上加载图片到file_box img_url = 'https://images.unsplash.com/photo-1470770903676-69b98201ea1c?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1500&q=80' file_box = FileBox.from_url(img_url, name='xx.jpg') await conversation.ready() await conversation.say('这是自动回复:') await conversation.say(file_box) if text == '风格转换': self.img[1] = 0 conversation = from_contact await conversation.ready() await conversation.say('这是自动回复:请输入第一张图片') # 如果消息类型是图片 if type == Message.Type.MESSAGE_TYPE_IMAGE: if from_contact == self.friend_contact: self.img[0] = not self.img[0] if self.img[1] == 0: self.img[1] = 1 # 将msg转换为file_box file_box = await msg.to_file_box() # 获取图片名 self.img[2] = file_box.name # 图片保存的路径 self.img[3] = './images/' + self.img[2] # 将图片保存到文件中 await file_box.to_file(file_path=self.img[3], overwrite=True) conversation = from_contact await conversation.ready() await conversation.say('这是自动回复:请输入第二张图片') if self.img[1] == 1 and self.img[0]: self.img[1] = None conversation = from_contact await conversation.ready() await conversation.say('这是自动回复:正在飞速处理中...') # 将msg转换为file_box file_box_art = await msg.to_file_box() # 获取图片名 self.img[4] = file_box_art.name # 图片保存的路径 self.img[5] = './images/' + self.img[4] # 将图片保存到文件中 await file_box_art.to_file(file_path=self.img[5], overwrite=True) # 调用函数,获取图片新路径 img_new_path = img_to_art(self.img[2], self.img[3], self.img[5]) # 从文件中加载图片到file_box file_box_new = FileBox.from_file(img_new_path) await conversation.say(file_box_new)
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() type = msg.type() room = msg.room() # 不处理群消息 if room is None: # 识别主人 if text == '你好我的机器人' and self.host_contact is None: # 记录主人的contact self.host_contact = from_contact # 列举所有好友的contact friend_contacts = await self.Contact.find_all() # 列举所有群 self.rooms = await self.Room.find_all() # 过滤一些contact self.friend_contacts = [ contact for contact in friend_contacts if len(contact.contact_id) > 50 ] # 初始化好友权限 self.friend_allow = { contact: [False, None] for contact in self.friend_contacts } # 初始化群聊权限 self.room_allow = {room: [False, None] for room in self.rooms} # 对主人开启权限 self.friend_allow[self.host_contact] = [True, None] # 给主人发消息 conversation = self.host_contact await conversation.ready() await conversation.say( '你好亲爱的主人,机器人目前的功能有:\n1 将图片转换为动漫风格\n2 对好友开启机器人\n3 对好友关闭机器人\n4 对群聊开启机器人\n5 对群聊关闭机器人\n主人回复相应数字即可开启对应功能' ) # 如果是主人的消息 if from_contact == self.host_contact: conversation = self.host_contact await conversation.ready() if self.friend_allow[self.host_contact][1] == 2: # 关闭功能 self.friend_allow[self.host_contact][1] = None # 获取好友备注或昵称 friend_name = text # 记录是否找到好友 is_find = False # 查找好友 for contact in self.friend_contacts: if friend_name == contact.payload.alias or friend_name == contact.name: # 找到 is_find = True # 对好友开启权限 self.friend_allow[contact] = [True, None] # 给好友发消息 conversation_friend = contact await conversation_friend.ready() await conversation_friend.say( '这是自动回复:你好,我是机器人,我的主人是Lovely-Pig,主人对你开启了机器人的功能' ) await conversation_friend.say( '这是自动回复:机器人目前的功能有:\n1 将图片转换为动漫风格\n回复相应数字即可开启对应功能' ) break # 给主人反馈 if is_find: await conversation.say(f'亲爱的主人,已对{friend_name}开启机器人功能') if not is_find: await conversation.say( f'亲爱的主人,{friend_name}不在您的好友列表里,“对好友开启机器人”功能已关闭') if self.friend_allow[self.host_contact][1] == 3: # 关闭功能 self.friend_allow[self.host_contact][1] = None # 获取好友备注或昵称 friend_name = text # 记录是否找到好友 is_find = False # 查找好友 for contact in self.friend_contacts: if friend_name == contact.payload.alias or friend_name == contact.name: # 找到 is_find = True # 对好友关闭权限 self.friend_allow[contact] = [False, None] # 给好友发消息 conversation_friend = contact await conversation_friend.ready() await conversation_friend.say( '这是自动回复:你好,我是机器人,我的主人是Lovely-Pig,主人对你关闭了机器人的功能' ) break # 给主人反馈 if is_find: await conversation.say(f'亲爱的主人,已对{friend_name}关闭机器人功能') if not is_find: await conversation.say( f'亲爱的主人,{friend_name}不在您的好友列表里,“对好友关闭机器人”功能已关闭') if self.friend_allow[self.host_contact][1] == 4: # 关闭功能 self.friend_allow[self.host_contact][1] = None # 获取群聊名称 room_name = text # 记录是否找到群聊 is_find = False # 查找群聊 for room in self.rooms: if room_name == await room.topic(): # 找到 is_find = True # 对群聊开启权限 self.room_allow[room] = [True, None] # 给群聊发消息 conversation_room = room await conversation_room.ready() await conversation_room.say( '这是自动回复:你们好,我是机器人,我的主人是Lovely-Pig,主人对群开启了机器人的功能' ) await conversation_room.say( '这是自动回复:机器人目前的功能有:\n1 将图片转换为动漫风格\n回复相应数字即可开启对应功能' ) break # 给主人反馈 if is_find: await conversation.say(f'亲爱的主人,已对{room_name}开启机器人功能') if not is_find: await conversation.say( f'亲爱的主人,{room_name}不在您的群聊列表里,“对群聊开启机器人”功能已关闭') if self.friend_allow[self.host_contact][1] == 5: # 关闭功能 self.friend_allow[self.host_contact][1] = None # 获取群聊名称 room_name = text # 记录是否找到群聊 is_find = False # 查找群聊 for room in self.rooms: if room_name == await room.topic(): # 找到 is_find = True # 对群聊开启权限 self.room_allow[room] = [False, None] # 给群聊发消息 conversation_room = room await conversation_room.ready() await conversation_room.say( '这是自动回复:你们好,我是机器人,我的主人是Lovely-Pig,主人对群关闭了机器人的功能' ) break # 给主人反馈 if is_find: await conversation.say(f'亲爱的主人,已对{room_name}关闭机器人功能') if not is_find: await conversation.say( f'亲爱的主人,{room_name}不在您的群聊列表里,“对群聊关闭机器人”功能已关闭') if text == '1': self.friend_allow[self.host_contact][1] = 1 await conversation.say('亲爱的主人,您已开启“将图片转换为动漫风格”功能,请发给我一张图片') if text == '2': self.friend_allow[self.host_contact][1] = 2 await conversation.say('亲爱的主人,您已开启“对好友开启机器人”功能,请指明是哪一个好友') if text == '3': self.friend_allow[self.host_contact][1] = 3 await conversation.say('亲爱的主人,您已开启“对好友关闭机器人”功能,请指明是哪一个好友') if text == '4': self.friend_allow[self.host_contact][1] = 4 await conversation.say('亲爱的主人,您已开启“对群聊开启机器人”功能,请指明是哪一个群') if text == '5': self.friend_allow[self.host_contact][1] = 5 await conversation.say('亲爱的主人,您已开启“对群聊关闭机器人”功能,请指明是哪一个群') # 好友的消息 if from_contact in self.friend_contacts and from_contact != self.host_contact: # 如果好友有权限 if self.friend_allow[from_contact][0]: conversation = from_contact await conversation.ready() if text == '1': self.friend_allow[from_contact][1] = 1 await conversation.say( '这是自动回复:你已开启“将图片转换为动漫风格”功能,请发给我一张图片') # 如果消息类型是图片 if type == Message.Type.MESSAGE_TYPE_IMAGE: # 如果有权限 if from_contact in self.friend_contacts and self.friend_allow[ from_contact][0]: # 判断功能 if self.friend_allow[from_contact][1] == 1: # 关闭功能 self.friend_allow[from_contact][1] = None conversation = from_contact await conversation.ready() await conversation.say('这是自动回复:正在飞速处理中...') # 将msg转换为file_box file_box = await msg.to_file_box() # 获取图片名 img_name = file_box.name # 图片保存的路径 img_path = './images/' + img_name # 将图片保存到文件中 await file_box.to_file(file_path=img_path, overwrite=True) # 调用函数,获取图片新路径 img_new_path = img_to_anime(img_name, img_path) # 从文件中加载图片到file_box file_box_new = FileBox.from_file(img_new_path) await conversation.say(file_box_new) # 如果群聊有权限 if room is not None and self.room_allow[room][0]: conversation = room await conversation.ready() if text == '1': self.room_allow[room][1] = 1 await conversation.say('这是自动回复:已开启“将图片转换为动漫风格”功能,请发给我一张图片') # 如果消息类型是图片 if type == Message.Type.MESSAGE_TYPE_IMAGE: # 判断功能 if self.room_allow[room][1] == 1: # 关闭功能 self.room_allow[room][1] = None conversation = room await conversation.ready() await conversation.say('这是自动回复:正在飞速处理中...') # 将msg转换为file_box file_box = await msg.to_file_box() # 获取图片名 img_name = file_box.name # 图片保存的路径 img_path = './images/' + img_name # 将图片保存到文件中 await file_box.to_file(file_path=img_path, overwrite=True) # 调用函数,获取图片新路径 img_new_path = img_to_anime(img_name, img_path) # 从文件中加载图片到file_box file_box_new = FileBox.from_file(img_new_path) await conversation.say(file_box_new)
async def on_message(self, msg: Message): """ listen for message event """ from_contact = msg.talker() text = msg.text() type = msg.type() room = msg.room() # 不处理群消息 if room is None: # 识别主人 if text == '你好我的机器人' and self.host_contact is None: # 记录主人的contact self.host_contact = from_contact # 列举所有好友的contact friend_contacts = await self.Contact.find_all() # 过滤一些contact self.friend_contacts = [ contact for contact in friend_contacts if contact.is_personal() ] # 移除主人的contact self.friend_contacts.remove(self.host_contact) # 初始化好友的友好账户 self.account_kind = { contact: 0 for contact in self.friend_contacts } # 给主人发消息 conversation = self.host_contact await conversation.ready() await conversation.say( '你好我亲爱的主人,我是主人的好友友好账户管家,目前的功能有:\n1 管理主人的好友友好账户\n2 查询主人的好友友好账户\n主人回复相应数字即可查询详细功能' ) # 如果是主人的消息 if from_contact == self.host_contact: conversation = self.host_contact await conversation.ready() if text == '1': await conversation.say( '当有好友给主人发消息时,将自动分析这句话的友好分数,并记录在主人的好友友好账户上') if text == '2': await conversation.say( '主人按照以下格式即可查询好友的友好账户\n查询 好友 张三\n\n主人按照以下格式即可查询好友友好账户排名前五\n查询 前5\n\n主人按照以下格式即可查询好友友好账户排名后五\n查询 后5' ) if '查询 好友' in text: # 提取好友备注或昵称 friend_name = text.split(' ')[-1] # 遍历字典,找打好友的友好账户分数并返回 for contact, score in list(self.account_kind.items()): if friend_name == contact.name or friend_name == contact.payload.alias: friend_score = round(score, 2) break await conversation.say( f'亲爱的主人,{friend_name}目前的友好分数为:{friend_score}') if '查询 前' in text: # 提取数字 number = re.findall(r'\d+', text) number = int(number[0]) # 按照账户分数大小给字典排序 sorted_account_kind = { contact: score for contact, score in sorted(self.account_kind.items(), key=lambda item: item[1], reverse=True) } # 给主人发的消息内容 msg_to_host = f'亲爱的主人,目前好友友好账户排名前{number}的是:' for contact, score in list( sorted_account_kind.items())[:number]: # 获取好友备注或昵称 friend_name = contact.payload.alias if contact.payload.alias != '' else contact.name msg_to_host += f'\n{friend_name}:{round(score, 2)}' await conversation.say(msg_to_host) if '查询 后' in text: # 提取数字 number = re.findall(r'\d+', text) number = int(number[0]) sorted_account_kind = { contact: score for contact, score in sorted(self.account_kind.items(), key=lambda item: item[1]) } # 给主人发的消息内容 msg_to_host = f'亲爱的主人,目前好友友好账户排名后{number}的是:' for contact, score in list( sorted_account_kind.items())[:number]: # 获取好友备注或昵称 friend_name = contact.payload.alias if contact.payload.alias != '' else contact.name msg_to_host += f'\n{friend_name}:{round(score, 2)}' await conversation.say(msg_to_host) # 好友的消息 if from_contact in self.friend_contacts and type == Message.Type.MESSAGE_TYPE_TEXT: # 计算好友消息的友好分数 score = analyse_kind(text) # 更新好友的友好账户 self.account_kind[from_contact] += score self.account_kind[from_contact] = round( self.account_kind[from_contact], 2) # 获取好友备注或昵称 friend_name = from_contact.payload.alias if from_contact.payload.alias != '' else from_contact.name # 给主人汇报消息 conversation = self.host_contact await conversation.ready() await conversation.say( f'亲爱的主人,{friend_name}给您发了一条消息\n消息内容是: {text}\n友好分数是: {score}\n{friend_name}目前的友好分数为:{self.account_kind[from_contact]}' )