async def abWord(session: CommandSession): target = session.current_arg_text.strip() imageList = await getImage(target, 5) for x in imageList: msg = Message() msg.append(MessageSegment.image(x)) await session.send(msg, ensure_private=True)
async def test_once(self, cl: Client): cl.proxy.send_private_msg('/weather') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('你想查询哪个城市的天气呢?') cl.proxy.send_private_msg('合肥') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('合肥的天气是……') await cl.proxy.wait_for_handler_complete()
async def ai_chat(session: CommandSession): message = session.get('message', prompt=expr(e.I_AM_READY)) ctx_id = context_id(session.event) tmp_msg = Message(message) text = tmp_msg.extract_plain_text() # call ai_chat api reply = await tencent_ai.chat(text, ctx_id) logger.debug(f'Got AI reply: {reply}') if reply: session.finish(escape(reply)) else: session.finish(expr(e.I_DONT_UNDERSTAND))
def _extract_image_urls(arg: Message_T) -> List[str]: """Extract all image urls from a message-like object.""" arg_as_msg = Message(arg) return [ s.data['url'] for s in arg_as_msg if s.type == 'image' and 'url' in s.data ]
def current_arg_text(self) -> str: """ Plain text part in the current argument, without any CQ codes. """ if self._current_arg_text is None: self._current_arg_text = Message( self.current_arg).extract_plain_text() return self._current_arg_text
async def banVote(session: CommandSession): banQQ = None for x in session.ctx['message']: if x.type == 'at': banQQ = x.data['qq'] if banQQ is None: return groupId = session.ctx['group_id'] if banList.get(groupId) is None: banList[groupId] = {} groupBanList = banList[groupId] if groupBanList.get(banQQ) is None: groupBanList[banQQ] = [] usrId = session.ctx.get('user_id') if usrId not in groupBanList[banQQ]: groupBanList[banQQ].append(usrId) limit = banConfig.get(str(groupId)) bot = nonebot.get_bot() if limit is None: try: info = await bot.get_group_info(group_id=groupId) limit = info.get('member_count') // 3 except CQHttpError as e: pass return msg = Message() try: info = await bot.get_group_member_info(group_id=groupId, user_id=banQQ) except CQHttpError as e: pass return msg.extend( f"投票对{info.get('nickname')}的禁言{len(groupBanList[banQQ])}/{limit}") await session.send(msg) if len(groupBanList[banQQ]) >= limit: try: info = await bot.set_group_ban(group_id=groupId, user_id=banQQ, duration=60 * limit) groupBanList[banQQ] = None except CQHttpError as e: pass return
def current_arg_images(self) -> List[str]: """ Images (as list of urls) in the current argument. """ if self._current_arg_images is None: self._current_arg_images = [ s.data['url'] for s in Message(self.current_arg) if s.type == 'image' and 'url' in s.data ] return self._current_arg_images
async def handle(context): #if str(context['message']) == '赞': # await bot.send_like(user_id=context['user_id'],times=10) # await bot.send(context,Message('已赞')) x = await bot.get_group_member_info(group_id=context['group_id'], user_id=context['user_id'], no_cache=True) a = context['group_id'] print(a) n = x['card'] if n == '': if a == 537154370: await bot.send( context, MessageSegment.at(context['user_id']) + Message('\n请修改群名片哦,群名片格式:\n年级-地区-名称')) else: await bot.send( context, MessageSegment.at(context['user_id']) + Message('\n请修改群名片哦,群名片格式:\n年级-专业-名称')) else: pass
async def colorImage(session: CommandSession): # 获取城市的天气预报 # 向用户发送天气预报 msg=Message() url="http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E8%89%B2%E5%9B%BE" imgurl='https://s2.ax1x.com/2019/03/29/A00Whn.png' # msg.append(MessageSegment.share(url,"色图","网警已介入本群",imgurl)) msg.append(MessageSegment.image('https://s2.ax1x.com/2019/11/16/MBYbmd.jpg')) msg.extend('没有色图给👴爬') await session.send(msg)
async def getImage(keyword, limit=1): array = [] param = {'keyword': keyword} async with aiohttp.request('GET', 'http://www.doutula.com/search', params=param) as r: js = await r.text() soup = bs4.BeautifulSoup(js, "lxml") img = soup.find_all('img') msg = Message() for x in img: if x.attrs.get('data-backup'): array.append(x.attrs.get('data-backup')) limit -= 1 if limit == 0: break return array
async def test_fire_msg_preprocessor(self, cl: Client): cl.proxy.send_private_msg('hello all') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('echo!') await cl.proxy.wait_for_handler_complete() cl.proxy.send_private_msg('/ping') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('echo!') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('pong!') await cl.proxy.wait_for_handler_complete()
async def test_loop(self, cl: Client): cl.proxy.send_private_msg('/weather') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('你想查询哪个城市的天气呢?') for _ in range(5): cl.proxy.send_private_msg(' ') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('要查询的城市名称不能为空呢,请重新输入') cl.proxy.send_private_msg('合肥') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('合肥的天气是……') await cl.proxy.wait_for_handler_complete()
def switch(self, new_ctx_message: Message_T) -> None: """ Finish the session and switch to a new (fake) message context. The user may send another command (or another intention as natural language) when interacting with the current session. In this case, the session may not understand what the user is saying, so it should call this method and pass in that message, then NoneBot will handle the situation properly. """ if self.is_first_run: # if calling this method during first run, # we think the command is not handled raise _FinishException(result=False) if not isinstance(new_ctx_message, Message): new_ctx_message = Message(new_ctx_message) raise SwitchException(new_ctx_message)
async def switch(session: CommandSession): parser = ArgumentParser(session=session, usage=USAGE) parser.add_argument('-r', '--repeat-message', action='store_true', default=False) parser.add_argument('message') args = parser.parse_args(session.argv) kill_current_session(session.ctx) msg = Message(args.message) if args.repeat_message: await session.send(msg) ctx = session.ctx.copy() ctx['message'] = msg ctx['to_me'] = True # ensure to_me asyncio.ensure_future(handle_message(session.bot, ctx))
async def test_everyone_ping(self, cl: Client): cl.proxy.send_private_msg('/ping') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('pong!') assert resp['user_id'] == TESTER_ID await cl.proxy.wait_for_handler_complete()
def _extract_text(arg: Message_T) -> str: """Extract all plain text segments from a message-like object.""" arg_as_msg = Message(arg) return arg_as_msg.extract_plain_text()
async def test_fire_overload2(self, cl: Client): cl.proxy.send_private_msg('今天预报') resp = await cl.proxy.wait_for_private_msg() assert Message(resp['message']) == Message('weather_report response') await cl.proxy.wait_for_handler_complete()
async def sendMessageCached(): bot = nonebot.get_bot() try: pass data = {'formBot': True} try: async with aiohttp.request( 'POST', f'http://{configJs["serverip"]}:{configJs["messageServerListen"]}', data=json.dumps(data), timeout=aiohttp.client.ClientTimeout(total=timeWait - 1)) as r: js = await r.text() js = json.loads(js) # res = requests.post('http://127.0.0.1:50382', data=json.dumps(data),timeout=3) # js = json.loads(res.text) # print('messcache') except: return for i in js: print(i) msg = Message('') # int(i.get('qq_group_id')) if not i.get('ensure_private'): for j in i.get('qq_id_list'): msg.append(MessageSegment.at(int(j))) if len(i.get('qq_id_list')) > 0: msg.extend('\n') textObj = i.get('text') if isinstance(textObj, list): for j in textObj: msg.extend(j.replace('$', ' ')) else: try: msg.extend(textObj) except: print(f'i.get() error') imageList = i.get('img') if isinstance(imageList, list): for j in imageList: if len(j) > 0: msg.append(MessageSegment.image(j)) else: try: if len(imageList) > 0: msg.append(MessageSegment.image(imageList)) except: print(f'image send error') if i.get('ensure_private'): for qqid in i.get('qq_id_list'): await bot.send_private_msg(user_id=qqid, message=msg) else: await bot.send_group_msg(group_id=int(i.get('qq_group_id')), message=msg) # await bot.send_group_msg(group_id=967636480, # message=f'给爬') except CQHttpError: pass
def replace_event_msg(event: Event, msg: str): new_event = Event.from_payload(event) new_event["message"] = Message(msg) new_event["raw_message"] = msg return new_event
async def var_replace(event: Event, message: Message, kwargs: Dict[str, Any]): origin_msg_str = str(message) repaced_msg_str = replace(origin_msg_str, event) message.clear() message.extend(repaced_msg_str)