def _check_at_me(bot: NoneBot, event: CQEvent) -> None: if event.detail_type == 'private': event['to_me'] = True else: # group or discuss event['to_me'] = False at_me_seg = MessageSegment.at(event.self_id) # check the first segment first_msg_seg = event.message[0] if first_msg_seg == at_me_seg: event['to_me'] = True del event.message[0] if not event['to_me']: # check the last segment i = -1 last_msg_seg = event.message[i] if last_msg_seg.type == 'text' and \ not last_msg_seg.data['text'].strip() and \ len(event.message) >= 2: i -= 1 last_msg_seg = event.message[i] if last_msg_seg == at_me_seg: event['to_me'] = True del event.message[i:] if not event.message: event.message.append(MessageSegment.text(''))
async def handle_message(bot: NoneBot, ctx: Dict[str, Any]) -> None: _log_message(ctx) if ctx['message_type'] != 'private': # group or discuss ctx['to_me'] = False first_message_seg = ctx['message'][0] if first_message_seg == MessageSegment.at(ctx['self_id']): ctx['to_me'] = True del ctx['message'][0] if not ctx['message']: ctx['message'].append(MessageSegment.text('')) else: ctx['to_me'] = True while True: try: handled = await handle_command(bot, ctx) break except SwitchException as e: # we are sure that there is no session existing now ctx['message'] = e.new_ctx_message ctx['to_me'] = True if handled: logger.info(f'Message {ctx["message_id"]} is handled as a command') return handled = await handle_natural_language(bot, ctx) if handled: logger.info(f'Message {ctx["message_id"]} is handled ' f'as natural language') return
async def choose_song(bot, ev): key = f'{ev.group_id}-{ev.user_id}' if key not in temp: if str(ev.group_id) in last_check and datetime.datetime.now( ) - last_check[str(ev.group_id)] < expire: await bot.send(ev, '不可以替他人选歌哦', at_sender=True) return song_dict = temp[key] song_idx = [] for msg_seg in ev.message: if msg_seg.type == 'text' and msg_seg.data['text']: song_idx.append(msg_seg.data['text'].strip()) if not song_idx: await bot.send(ev, '你想听什么呀?', at_sender=True) else: song_idx = ''.join(song_idx) for idx in song_idx: if idx in song_dict: song = song_dict[idx] if song['type'] == '163': music = MessageSegment.music(song['type'], song['id']) elif song['type'] == 'custom': music = MessageSegment(type_='music', data=song) else: music = MessageSegment(type_='music', data={ 'id': str(song['id']), 'type': song['type'], 'content': song['artists'] }) await bot.send(ev, music) del temp[key] del last_check[str(ev.group_id)]
async def call(context): if context.get("group_id"): if not cache.get(context.get("group_id")): cache.set(context.get("group_id"), type(str(context.get("group_id")), (Cache, ), {})()) if not list(cache.get(context.get("group_id")).values()): return "现在没人联机了, 自己发起吧." shouldBe = True tick = 0 while shouldBe and tick < 8: result = random.choice( list(cache.get(context.get("group_id")).values())) if result['user_id'] != context['user_id']: shouldBe = False tick += 1 if tick >= 8 and shouldBe: return "错误: 等待列表中可能只有你一个人吧= =" return "".join([ str(MessageSegment.at(result['user_id'])), ", ", str(MessageSegment.at(context['user_id'])), " 找你联机!" ]) else: return "本指令不支持私人聊天."
async def ro(session: CommandSession): userid = session.ctx['user_id'] result = "" if session.get('readable') == 1: array, result = calculate(session.get('expression')) result = MessageSegment.at(userid) + '投掷为' + str(array) + "合计为" + str(result) elif session.get('readable') == 2: skill = session.get('skill') ability = session.get('ability') _, result = roll(1, 100) success = issuccess(result, ability) result = MessageSegment.at(userid) + '投掷的' + skill + '为' + str(result) + ',' + success elif session.get('readable') == 3: skill = session.get('skill') ability = session.get('ability') _, tmp1 = roll(1, 100) _, tmp2 = roll(1, 100) if tmp1 == 100: tmp1 = 0 if tmp2 == 100: tmp2 = 0 result1 = max(tmp1 / 10, tmp2 / 10) result2 = min(tmp1 % 10, tmp2 % 10) result = int(result1) * 10 + result2 success = issuccess(result, ability) result = MessageSegment.at(userid) + '投掷的' + skill + '为[' + \ str(tmp1) + ', ' + str(tmp2) + "]计算惩罚骰结果为" + str(result) + success elif session.get('readable') == 4: skill = session.get('skill') ability = session.get('ability') _, tmp1 = roll(1, 100) _, tmp2 = roll(1, 100) if tmp1 == 100: tmp1 = 0 if tmp2 == 100: tmp2 = 0 result1 = min(tmp1 / 10, tmp2 / 10) result2 = max(tmp1 % 10, tmp2 % 10) result = int(result1) * 10 + result2 success = issuccess(result, ability) result = MessageSegment.at(userid) + '投掷的' + skill + '为[' + \ str(tmp1) + ', ' + str(tmp2) + "]计算奖励骰结果为" + str(result) + "," + success else: result = "骰娘无法读懂您的参数呢QAQ" with open("command_log.txt", "a") as f: f.write(str(result)) await session.send(result)
def _check_at_me(bot: NoneBot, event: CQEvent) -> None: if event.detail_type == 'private': event['to_me'] = True return def is_at_me(seg): return seg.type == 'at' and str(seg.data['qq']) == str(event.self_id) # group or discuss event['to_me'] = False # check the first segment first_msg_seg = event.message[0] if is_at_me(first_msg_seg): event['to_me'] = True del event.message[0] if not event['to_me']: # check the last segment i = -1 last_msg_seg = event.message[i] if last_msg_seg.type == 'text' and \ not last_msg_seg.data['text'].strip() and \ len(event.message) >= 2: i -= 1 last_msg_seg = event.message[i] if is_at_me(last_msg_seg): event['to_me'] = True del event.message[i:] if not event.message: event.message.append(MessageSegment.text(''))
async def send_poke(bot, ev): user_id = extract_target_members(ev.message) text = extract_plain_text(ev.message) m = re.match(r'[x|X](\d+)', text) if user_id and user_id != 'all': if not m: for uid in user_id: await bot.send(ev, MessageSegment(type_='poke', data={'qq': uid})) elif m and int(m.group(1)) <= 5: uid = user_id[0] for _ in range(int(m.group(1))): await bot.send(ev, MessageSegment(type_='poke', data={'qq': uid})) else: await bot.send(ev, '好累的样子, 我不!')
async def tietie(bot, ev): await bot.send(ev, '贴贴成功! 记得回礼哦~') await bot.send( ev, MessageSegment(type_='gift', data={ 'qq': str(ev.user_id), 'id': 0 }))
async def task(event, url): message = await _bot.send(event, MessageSegment.image(url)) await asyncio.sleep(20) if message is not None: await _bot.delete_msg(message_id=message['message_id']) else: await _bot.send(event, "警告:撤回失败")
async def _(session: CommandSession): user_id, group_id = session.event.user_id, session.event.group_id if session.current_arg and session.current_arg.strip() == '文本': await session.send(await group_user_check(user_id, group_id), at_sender=True) else: # 使用 bot 对象来主动调用 api nickname = (await get_bot().get_stranger_info(user_id=user_id))['nickname'] # type: ignore im_b64 = await group_user_check_use_b64img(user_id, group_id, nickname) await session.send(MessageSegment.image(f'base64://{im_b64}'), at_sender=True)
async def cherulize(bot, ev: CQEvent): s = ev.message.extract_plain_text() at = MessageSegment.at(ev.user_id) if len(s) > 500: await bot.send(ev, f'{at} 切、切噜太长切不动勒切噜噜...') return msg = ['切噜~♪' + str2cheru(s)] await bot.send(ev, f'{at}说: ' + '\n'.join(msg)) await util.delete_msg(ev, ev.message_id)
async def get_result(num: int, max: int, userid) -> str: result = 0 result_string = "" if num > 20: return "个数太多骰娘数不过来啦QAQ" for i in range(num): result_string += "," + str(random.randint(1, max)) result_string = MessageSegment.at(userid) + "投掷结果为" + result_string return result_string
async def coc(session: CommandSession): userid = session.ctx["user_id"] attribute = ['力量', '体质', '体型', '敏捷', '外貌', '智力', '意志', '教育', '幸运'] result = "COC7版投掷结果\n" for i in range(6): tmp = get_coc() for j in range(9): result = result + attribute[j] + ":" + str(tmp[j]) result = result + '\n' await session.send(MessageSegment.at(userid) + result)
def has_at_bot(self, event: Event, message: str): """ 是否有人 at 机器人 """ has_at = False msg = Message(message) for seg in msg: if seg == MessageSegment.at(event.self_id): has_at = True return has_at
async def _(event): msg = Message(event.message) numpad = False for seg in msg: if seg == MessageSegment.at(event.self_id): numpad = True if numpad: seg = Message(seg).extract_plain_text().strip() data = reply(seg) await send(event, data) numpad = False
async def diansong(bot, event): msg = event.message.extract_plain_text().strip() if not msg: await bot.send(event, '歌名都没有你点个锤子噢') return mid = query(msg) if isinstance(mid, int) is False: await bot.send(event, id) return music = MessageSegment.music(type_='163', id_=mid) sv.logger.info(f'{music}') await bot.send(event, music)
async def _(session: CommandSession): end_time = datetime.datetime.now() start_time = datetime.datetime.now() + datetime.timedelta(days=-600) a1 = tuple(start_time.timetuple()[0:9]) a2 = tuple(end_time.timetuple()[0:9]) start = time.mktime(a1) end = time.mktime(a2) t = random.randint(int(start), int(end)) date_touple = time.localtime(t) date = time.strftime("%Y-%m-%d", date_touple) res = requests.get( "http://sentence.iciba.com/index.php?c=dailysentence&m=getdetail&title=" + date) json_str = json.loads(res.text) chinese = json_str["note"] english = json_str["content"] pic = json_str["picture2"] voice = json_str["tts"] await session.send("英文原文:" + english + "\n翻译:" + chinese + "\n封面:" + MessageSegment.image(pic)) await session.send(MessageSegment.record(voice))
async def _(session: CommandSession): args = session.current_arg_text.strip().split(' ', 1) if not args[0]: stock = await session.aget(key='city', prompt='请输入股票或指数代码(仅支持沪深市场,上交所代码前请加SH,深交所代码前请加SZ)', at_sender=True) else: stock = args[0] try: func = get_stock_message result = await func(stock) except ServiceException as e: result = e.message await session.send(result,at_sender=True) await session.send(MessageSegment.image("http://image.sinajs.cn/newchart/min/n/"+stock.lower()+".gif"))
async def echo(bot, ev): context = [] for msg_seg in ev.message: if msg_seg.type == 'text': context.append(msg_seg.data['text'].strip()) if context: _type, _dict_text = re.match(r'\[CQ:(\w+),(.*)\]', unescape(''.join(context))).groups() _dict = {} for item in _dict_text.split(','): item = item.split('=') k = item[0] v = ''.join(item[1:]) _dict[k.strip()] = v.strip() await bot.send(ev, MessageSegment(type_=_type, data=_dict))
async def _(session: CommandSession): index = str(random.randint(1, 50)) res = requests.get("https://api.bilibili.com/x/web-interface/popular?ps=1&pn=" + index) json_res = json.loads(res.text) title=json_res["data"]["list"][0]["title"] pic=json_res["data"]["list"][0]["pic"] up=json_res["data"]["list"][0]["owner"]["name"] link=json_res["data"]["list"][0]["short_link"] bv=json_res["data"]["list"][0]["bvid"] localtime = time.asctime(time.localtime(time.time())) await session.send('北京时间:' + localtime + "\n哔哩哔哩随机热门第"+index+":" + "\n视频标题:" + title + "\nUP主:" + up + "\nBV号:" + bv + "\n视频链接:" + link + "\n视频封面:" + MessageSegment.image(pic))
async def farm_bc(bot, ev): if not priv.check_priv(ev, priv.ADMIN): await bot.send(ev, '只有群管理才可以召回成员~', at_sender=True) return d_farm_object = {} with f_farm.open('r') as f: d_farm_object = json.load(f) gid = str(ev['group_id']) if gid not in d_farm_object: await bot.send(ev, '农场里没有人诶') return else: l_uid = d_farm_object[gid] msg = [str(MessageSegment.at(user_id=uid)) for uid in l_uid] await bot.send(ev, f'{"".join(msg)} 是时候从农场回来啦!\n使用【回公会:IDxxxxx】将信息登记到BOT, 可以方便管理员统一邀请哦')
async def handle_message(bot: NoneBot, event: CQEvent) -> None: """INTERNAL API""" _log_message(event) assert isinstance(event.message, Message) if not event.message: event.message.append(MessageSegment.text('')) # type: ignore raw_to_me = event.get('to_me', False) _check_at_me(bot, event) _check_calling_me_nickname(bot, event) event['to_me'] = raw_to_me or event['to_me'] coros = [] plugin_manager = PluginManager() for preprocessor in MessagePreprocessorManager.preprocessors: coros.append(preprocessor.func(bot, event, plugin_manager)) if coros: try: await asyncio.gather(*coros) except CanceledException as e: logger.info( f'Message {event["message_id"]} is ignored: {e.reason}') return while True: try: handled = await handle_command(bot, event, plugin_manager.cmd_manager) break except SwitchException as e: # we are sure that there is no session existing now event['message'] = e.new_message event['to_me'] = True if handled: logger.info(f'Message {event.message_id} is handled as a command') return handled = await handle_natural_language(bot, event, plugin_manager.nlp_manager) if handled: logger.info(f'Message {event.message_id} is handled ' f'as natural language') return logger.debug(f'Message {event.message_id} was not handled')
async def _(session: CommandSession): header = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/89.0.4389.90 " "Safari/537.36 " } res = requests.get("https://news-at.zhihu.com/api/3/stories/latest", headers=header) json_str = json.loads(res.text) index = random.randint(0, len(json_str["stories"]) - 1) title = json_str["stories"][index]["title"] image = json_str["stories"][index]["images"][0] url = json_str["stories"][index]["url"] print(title) print(image) print(url) localtime = time.asctime(time.localtime(time.time())) await session.send('北京时间:' + localtime + " 知乎日报" + "\n文章标题:" + title + "\n文章链接:" + url + "\n文章封面:" + MessageSegment.image(image))
async def choose_song(bot, ev): key = f'{ev.group_id}-{ev.user_id}' if key not in temp: await bot.send(ev, '你还没有点歌呢!', at_sender=True) return song_dict = temp[key] song_idx = [] for msg_seg in ev.message: if msg_seg.type == 'text' and msg_seg.data['text']: song_idx.append(msg_seg.data['text'].strip()) if not song_idx: await bot.send(ev, '你想听什么呀?', at_sender=True) else: song_idx = ''.join(song_idx) if song_idx in song_dict: song = song_dict[song_idx] music = MessageSegment.music(song['type'], song['id']) del temp[key] await bot.send(ev, music) else: await bot.send(ev, '只能选择列表中有的歌曲哦', at_sender=True) return
def getVideoInfo(param_aid, param_bvid): url = f'https://api.bilibili.com/x/web-interface/view?aid={param_aid}&bvid={param_bvid}' try: with requests.get(url, timeout=20) as resp: res = resp.json() data = res['data'] bvid = data['bvid'] aid = data['aid'] pic = data['pic'] title = data['title'] name = data['owner']['name'] view = data['stat']['view'] danmaku = data['stat']['danmaku'] play = humanNum(view) danku = humanNum(danmaku) cover = MessageSegment.image(pic) result = f'{cover}\nav{aid}\n{title}\nUP:{name}\n{play}播放 {danku}弹幕\nhttps://www.bilibili.com/video/{bvid}'.strip( ) return result except Exception as ex: sv.logger.error(f'[getVideoInfo ERROR]:{ex}') return None
def getSearchVideoInfo(keyword): url = f'https://api.bilibili.com/x/web-interface/search/all/v2?keyword={keyword}' try: with requests.get(url, timeout=20) as resp: res = resp.json() data = res['data']['result'] videos = [x for x in data if x['result_type'] == 'video'] if len(videos) == 0: return '' video_list = videos[0]['data'] if len(video_list) > 10: video_list = video_list[0:10] result = '' for item in video_list: aid = item['aid'] bvid = item['bvid'] pic = item['pic'] desc = html2text.html2text(item['description']) play = humanNum(item['play']) danku = humanNum(item['video_review']) title = html2text.html2text(item['title']) title = title.strip() cover = MessageSegment.image(f'https:{pic}') author = item['author'] result += f'''{cover} {title} {desc} av{aid} UP:{author} {play}播放 {danku}弹幕 源地址:https://www.bilibili.com/video/{bvid} ===========> '''.strip() result += '\n搜索结束,冷却时间120秒' return result except Exception as ex: sv.logger.error(f'[getSearchVideoInfo ERROR]:{ex}') return f'搜索{keyword}出错,请稍后再试~'
async def prior_intercept(cls, bot, context, msg, input_vars, update_vars, extras, **kwargs): if context['post_type'] == 'message': if context.get('sender'): for msg_data in context['message']: if msg_data['type'] == 'rich': detail_1 = json.loads(msg_data.get('data', {}).get('content', "{}").replace("[", "[").replace("]", "]").replace(",", ",")).get("detail_1", {}) pic_url = detail_1.get("preview", "") if detail_1.get("title") is not None and detail_1.get("desc") is not None: output_msg = Message(detail_1.get("title", "无标题") + ":" + detail_1.get("desc", "无简介")) if not pic_url is None and not pic_url.strip() == "": if not pic_url.startswith("http"): pic_url = "http://" + pic_url async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session: async with session.get(pic_url) as resp: pic = await resp.read() output_msg = output_msg + MessageSegment(type_='image', data={'file': "base64://" + base64.b64encode(pic).decode("ascii")}) await bot.send(context, output_msg) return False
def getSearchVideoInfo(keyword): url = f'https://api.bilibili.com/x/web-interface/search/all/v2?{keyword}' try: with requests.get(url, timeout=20) as resp: res = resp.json() data = res['data']['result'] videos = [x for x in data if x['result_type'] == 'video'] if (len(videos) == 0): return None video = videos[0]['data'][0] aid = video['aid'] bvid = video['bvid'] pic = video['pic'] play = humanNum(video['play']) danku = humanNum(video['video_view']) title = html2text.html2text(video['title']) cover = MessageSegment.image(f'http://{pic}') author = video['author'] result = f'{cover}\n(搜索)av{aid}\n{title}\nUP:{author}\n{play}播放 {danku}弹幕\nhttps://www.bilibili.com/video/{bvid}'.strip( ) return result except Exception as ex: sv.logger.error(f'[getSearchVideoInfo ERROR]:{ex}') return None
async def send_common_setu(bot, event: Event): uid = event.user_id self_id = event.self_id gid = event.group_id user_priv = get_user_priv(event) is_to_delete = True if gid in g_delete_groups else False if not _num_limiter.check(uid): await bot.send(event, EXCEED_NOTICE) return if not _freq_limiter.check(uid): await bot.send(event, TOO_FREQUENT_NOTICE) return if not ONLINE_MODE: sv.logger.info('发送本地涩图') pic = R.get_random_image('nr18_setu') ret = await bot.send(event, pic) msg_id = ret['message_id'] if is_to_delete: #30秒后删除 await asyncio.sleep(30) await bot.delete_msg(self_id=self_id, message_id=msg_id) return robj = event['match'] try: num = int(robj.group(1)) except: num = 1 #按照数量设置limiter _num_limiter.increase(uid, num) _freq_limiter.start_cd(uid, num * 5) keyword = robj.group(2).strip() if keyword: await bot.send(event, '正在搜索,请稍等~') sv.logger.info(f'含有关键字{keyword},尝试搜索') if user_priv < SUPERUSER: setus = await get_final_setu_async(search_path, keyword=keyword, r18=0) else: setus = await get_final_setu_async(search_path, keyword=keyword, r18=2) if not setus: await bot.send(event, f'没有找到关键字{keyword}的涩图,您将被禁用涩图服务60s') _freq_limiter.start_cd(uid, 60) sv.logger.info( f'{uid} searched keyword {keyword} and returned no result') return setu = setus[0] pic_path = await download_async(setu.url, search_path, setu.pid) pic = MessageSegment.image(pic_path) reply = f'{setu.title}\n画师:{setu.author}\npid:{setu.pid}{pic}' try: await bot.send(event, reply, at_sender=False) _num_limiter.increase(uid) _freq_limiter.start_cd(uid, 30) except Exception as ex: await bot.send(event, f'搜索关键字{keyword}发生异常') sv.logger.error(f'搜索涩图时发生异常 {ex}') else: setus = wh.fetch(num) if not setus: #send_setus为空 await bot.send(event, '色图库正在补充,下次再来吧', at_sender=False) return else: await send_setus(bot, event, 'nr18_setu', setus, WITH_URL, is_to_delete)
async def test_reply_msg(bot, ev): tts = MessageSegment(type_='tts', data={'text': '肥肠抱歉本视频由于以下原因导致无法正常播放'}) await bot.send(ev, tts)