async def neurasthenia_game(bot, ev: CQEvent): if gm.is_playing(ev.group_id): await bot.finish(ev, "游戏仍在进行中…") with gm.start_game(ev.group_id) as game: chosen_ids = random.sample(game_util.VALID_IDS, TOTAL_PIC_NUM // 2) chosen_ids.extend(chosen_ids) random.shuffle(chosen_ids) # 记忆阶段 await bot.send(ev, f'记忆阶段: ({SHOW_TIME}s后我会撤回图片哦~)') pic = MessageSegment.image(util.pic2b64(game_util.generate_full_pic(ROW_NUM, COL_NUM, chosen_ids))) msg = await bot.send(ev, pic) await asyncio.sleep(SHOW_TIME) await bot.delete_msg(message_id=msg['message_id']) await asyncio.sleep(2) # 回答阶段 displayed_sub_pic_index = random.randint(0, TOTAL_PIC_NUM - 1) chosen_id = chosen_ids[displayed_sub_pic_index] explanation = game_util.EXPLANATION[chosen_id] ids = [game_util.JUMP_ID if i != displayed_sub_pic_index else id for i, id in enumerate(chosen_ids)] pic = MessageSegment.image(util.pic2b64(game_util.generate_full_pic(ROW_NUM, COL_NUM, ids, True))) await bot.send(ev, f'请告诉我另一个"{explanation}"所在位置的编号~ ({ANSWER_TIME}s后公布答案){pic}') game.answer = [i for i, id in enumerate(chosen_ids) if i != displayed_sub_pic_index and id == chosen_id][0] + 1 await asyncio.sleep(ANSWER_TIME) # 结算 game.update_score() msg_part1 = f'{MessageSegment.at(game.winner[0])}首先答对,真厉害~ 加2分! 当前总分为{game.get_first_winner_score()}分' if game.winner else '' msg_part2 = f'{game_util.generate_at_message_segment(game.winner[1:])}也答对了, 加1分~' if game.winner[1:] else '' msg_part3 = f'{game_util.generate_at_message_segment(game.loser)}答错了, 扣1分o(╥﹏╥)o' if game.loser else '' msg_part4 = '咦, 这轮游戏没人参与, 看来题目可能有点难...' if not (msg_part1 or msg_part2 or msg_part3) else "" msg_part = '\n'.join([s for s in [msg_part1, msg_part2, msg_part3, msg_part4] if s]) await bot.send(ev, f'正确答案是: {game.answer}{MessageSegment.image(util.pic2b64(game_util.generate_full_pic(ROW_NUM, COL_NUM, chosen_ids)))}{msg_part}')
async def poke_back(session: NoticeSession): if session.ctx['target_id'] != session.event.self_id: return if not daily_limiter.check( (session.ctx['group_id'], session.ctx['user_id'])) or random.random() < 0.33: poke = MessageSegment(type_='poke', data={ 'qq': str(session.ctx['user_id']), }) await session.send(poke) else: cards_list = card_file_names_rare if random.random( ) < 0.10 else card_file_names_normal card_id, card = get_random_card(cards_list) rarity, chara_name = get_chara_name(card_id) rarity_desc = '【稀有】的' if rarity == 1 else '' at_user = MessageSegment.at(session.ctx['user_id']) await session.send( f'别戳了别戳了o(╥﹏╥)o{card}{at_user}这张{rarity_desc}「{chara_name}」送给你了, 让我安静会...' ) db.add_card_num(session.ctx['group_id'], session.ctx['user_id'], card_id) daily_limiter.increase( (session.ctx['group_id'], session.ctx['user_id']))
async def poke_back(session: NoticeSession): uid = session.ctx['user_id'] if not cooling_time_limiter.check(uid): return cooling_time_limiter.start_cd(uid) if session.ctx['target_id'] != session.event.self_id: return if not daily_limiter.check( (session.ctx['group_id'], session.ctx['user_id'])) or random.random() < 0.33: poke = MessageSegment(type_='poke', data={ 'qq': str(session.ctx['user_id']), }) await session.send(poke) else: card_ids, rarity_counter, card = get_random_cards( card_file_names_all, roll_card_amount()) at_user = MessageSegment.at(session.ctx['user_id']) dash = '----------------------------------------' msg_part1 = f'\n超稀有x{rarity_counter[1]}' if rarity_counter[1] else '' msg_part2 = f'\n稀有卡x{rarity_counter[0]}' if rarity_counter[0] else '' msg_part3 = f'\n普通卡x{rarity_counter[-1]}' if rarity_counter[-1] else '' await session.send( f'别戳了别戳了o(╥﹏╥)o{card}{at_user}这些卡送给你了, 让我安静会...\n{dash}\n获得了:{msg_part1}{msg_part2}{msg_part3}' ) for card_id in card_ids: db.add_card_num(session.ctx['group_id'], session.ctx['user_id'], card_id) daily_limiter.increase( (session.ctx['group_id'], session.ctx['user_id']))
async def on_query_arena_all(bot, ev): global binds, lck robj = ev['match'] id = robj.group(1) uid = str(ev['user_id']) async with lck: if id == None: if not uid in binds: await bot.finish(ev, '您还未绑定竞技场', at_sender=True) return else: id = binds[uid]['id'] try: res = await query(id) sv.logger.info('开始生成竞技场查询图片...') # 通过log显示信息 # result_image = await generate_info_pic(res, cx) result_image = await generate_info_pic(res, uid) result_image = pic2b64(result_image) # 转base64发送,不用将图片存本地 result_image = MessageSegment.image(result_image) result_support = await generate_support_pic(res, uid) result_support = pic2b64(result_support) # 转base64发送,不用将图片存本地 result_support = MessageSegment.image(result_support) sv.logger.info('竞技场查询图片已准备完毕!') try: await bot.finish(ev, f"\n{str(result_image)}\n{result_support}", at_sender=True) except Exception as e: sv.logger.info("do nothing") except ApiException as e: await bot.finish(ev, f'查询出错,{e}', at_sender=True)
async def poke_back(session: NoticeSession): uid = session.ctx['user_id'] at_user = MessageSegment.at(session.ctx['user_id']) guid = session.ctx['group_id'], session.ctx['user_id'] if not cooling_time_limiter.check(uid): return cooling_time_limiter.start_cd(uid) if session.ctx['target_id'] != session.event.self_id: return if not daily_limiter.check(guid) and not daily_tip_limiter.check(guid): poke_tip_cd_limiter.start_cd(guid) if not daily_limiter.check(guid) and poke_tip_cd_limiter.check(guid): daily_tip_limiter.increase(guid) await session.send(f'{at_user}你今天戳得已经够多的啦,再戳也不会有奇怪的东西掉下来的~') return daily_tip_limiter.reset(guid) if not daily_limiter.check(guid) or random.random() > POKE_GET_CARDS: poke = MessageSegment(type_='poke', data={ 'qq': str(session.ctx['user_id']), }) await session.send(poke) else: card_counter, card_descs, card = get_random_cards( db.get_cards_num(session.ctx['group_id'], session.ctx['user_id']), card_file_names_all, roll_cards_amount(), True) dash = '----------------------------------------' msg_part = '\n'.join(card_descs) await session.send( f'别戳了别戳了o(╥﹏╥)o{card}{at_user}这些卡送给你了, 让我安静会...\n{dash}\n获得了:\n{msg_part}' ) for card_id in card_counter.keys(): db.add_card_num(session.ctx['group_id'], session.ctx['user_id'], card_id, card_counter[card_id]) daily_limiter.increase(guid)
def get_music_from_song_data(song_data): if song_data[0] == 'bili': return MessageSegment.share(url='https://www.bilibili.com/video/' + song_data[1], title=song_data[3], content=song_data[4], image_url="http://i0.hdslb.com/bfs/archive/b28c463d04db58f6eb79e238757b78ab1f609ec0.png") elif song_data[0] == 'qq': return MessageSegment(type_='music', data={ 'type': song_data[0], 'id': str(song_data[1]), 'content': song_data[4] }) else: return MessageSegment.music(type_=song_data[0], id_=song_data[1])
def get_icons(arr,size=64,types='skill'): num = len(arr) des = Image.new('RGBA', (num*size, size), (255, 255, 255, 255)) for i, chara in enumerate(arr): pic = icon(chara,types).open().convert('RGBA').resize((size, size), Image.LANCZOS) des.paste(pic, (i * size, 0), pic) return str(MessageSegment.image(pic2b64(des)))
async def add_repass(self, tag: str, data): po = "——{}——".format(tag) for line in data: if THUMB_ON: try: #thumbnail_image = str(MessageSegment.image(pic2b64(ats_pic(Image.open(BytesIO(await get_pic(line[2]))))))) thumbnail_image = str( MessageSegment.image( pic2b64( ats_pic( Image.open( BytesIO( self.scraper.get( line[2], timeout=20, proxies=proxies).content)))))) except Exception as e: print(format_exc()) thumbnail_image = "[预览图下载失败]" else: thumbnail_image = "" putline = f"{thumbnail_image}\n[{line[1]}][{line[0]}]\n{line[3]}" po = "\n".join([po, putline]) return po
def get_random_cards(card_file_names_list=card_file_names_all, amount=1): card_ids = [] size = 80 margin = 5 col_num = math.ceil(amount / 2) row_num = 2 if amount != 1 else 1 base = Image.new('RGBA', (col_num * size + (col_num - 1) * margin, (row_num * size + (row_num - 1) * margin)), (255, 255, 255, 255)) rarity_counter = {-1: 0, 0: 0, 1: 0} for i in range(amount): random_card = random.choice( card_file_names_list ) if card_file_names_list != card_file_names_all else random.choice( get_random_cards_list()) card_id, rarity = get_card_id_by_file_name(random_card) card_ids.append(card_id) rarity_counter[rarity] += 1 if PRELOAD: img = image_cache[random_card] else: img = Image.open(DIR_PATH + f'/{random_card}') row_index = i // col_num col_index = i % col_num img = img.resize((size, size), Image.ANTIALIAS) base.paste(add_rarity_frame(img, rarity), (col_index * (size + margin), row_index * (size + margin))) return card_ids, rarity_counter, MessageSegment.image(util.pic2b64(base))
async def on_input_image(bot, ev: CQEvent): if str(ev.group_id) not in gacha_threshold.threshold: return for seg in ev.message: if seg.type == 'image': img = seg.data['file'] need_ocr = await is_possible_gacha_image(bot, ev, img) if need_ocr: need_delete_msg, need_silence = await check_image(bot, ev, img) if need_delete_msg: bot_auth = judge_bot_auth(bot, ev) if need_silence: await bot.send(ev, '检测到海豹行为(╯‵□′)╯︵┻━┻') if bot_auth == True: await bot.delete_msg(self_id=ev.self_id, message_id=ev.message_id) await util.silence(ev, 10 * 60, skip_su=True) await bot.send( ev, str( MessageSegment.image( f'file:///{os.path.abspath(PIC_PATH)}')) + '\n拒绝海豹,从我做起!') else: if bot_auth == True: await bot.delete_msg(self_id=ev.self_id, message_id=ev.message_id) await bot.send(ev, '虽然没看出你有没有在晒卡,总之消息先撤回了~')
async def jc(bot, ev: CQEvent): kw = ev.message.extract_plain_text().strip() arr = kw.split('/') image = Image.open(os.path.join(os.path.dirname(__file__),'jichou.jpg')) # 创建Font对象: font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),'simhei.ttf'), 80) time = datetime.datetime.now().strftime('%Y年%m月%d日') msg = f'{time},{arr[0]},{arr[1]},这个仇我先记下了' place = 12 line = len(msg.encode('utf-8')) // place + 1 positions = measure(msg, 80, 974) str_list = list(msg) for pos in positions: str_list.insert(pos,'\n') msg = "".join(str_list) # 创建Draw对象: image_text = Image.new('RGB', (974, 32 * line), (255, 255, 255)) draw = ImageDraw.Draw(image_text) draw.text((0, 0), msg, fill=(0 , 0, 0), font=font) # 模糊: image_text = image_text.filter(ImageFilter.BLUR) image_back = Image.new('RGB', (974, 32 * line + 764), (255, 255, 255)) image_back.paste(image, (0, 0)) image_back.paste(image_text, (0, 764)) await bot.send(ev, str(MessageSegment.image(pic2b64(image_back))))
async def friend(bot, ev: CQEvent): # 定义非管理员的冷却时间 # if ev.user_id not in bot.config.SUPERUSERS: # if not _flmt.check(ev.user_id): # return # _flmt.start_cd(ev.user_id) data = load_config(os.path.join(os.path.dirname(__file__), 'config.json'))['friend'] arr = [] is_at = False for m in ev.message: if m.type == 'at' and m.data['qq'] != 'all': arr = [int(m.data['qq'])] sid = int(m.data['qq']) is_at = True if not is_at: try: arr = data[f'{ev.group_id}'] except: member_list = await bot.get_group_member_list(self_id=ev.self_id, group_id=ev.group_id) for member in member_list: arr.append(member['user_id']) sid = choice(arr) info = await bot.get_group_member_info(group_id=ev.group_id, user_id=sid, no_cache=True) name = info['card'] or info['nickname'] match = ev['match'] msg = match.group('kw') msg = msg.replace('他', '我').replace('她', '我') image = Image.open(BytesIO(get_pic(sid))) img_origin = Image.new('RGBA', (100, 100), (255, 255, 255)) scale = 3 # 使用新的半径构建alpha层 r = 100 * scale alpha_layer = Image.new('L', (r, r), 0) draw = ImageDraw.Draw(alpha_layer) draw.ellipse((0, 0, r, r), fill=255) # 使用ANTIALIAS采样器缩小图像 alpha_layer = alpha_layer.resize((100, 100), Image.ANTIALIAS) img_origin.paste(image, (0, 0), alpha_layer) # 创建Font对象: font = ImageFont.truetype( os.path.join(os.path.dirname(__file__), 'simhei.ttf'), 30) font2 = ImageFont.truetype( os.path.join(os.path.dirname(__file__), 'simhei.ttf'), 25) # 创建Draw对象: image_text = Image.new('RGB', (450, 150), (255, 255, 255)) draw = ImageDraw.Draw(image_text) draw.text((0, 0), name, fill=(0, 0, 0), font=font) draw.text((0, 40), msg, fill=(125, 125, 125), font=font2) image_back = Image.new('RGB', (700, 150), (255, 255, 255)) image_back.paste(img_origin, (25, 25)) image_back.paste(image_text, (150, 40)) await bot.send(ev, str(MessageSegment.image(pic2b64(image_back))))
async def word_back_10_(bot, ev): gid = ev['group_id'] uid = ev['user_id'] at_user = MessageSegment.at(ev['user_id']) guid = ev['group_id'], ev['user_id'] if not cooling_time_limiter.check(uid): return cooling_time_limiter.start_cd(uid) if not daily_limiter.check(guid) and not daily_tip_limiter.check(guid): poke_tip_cd_limiter.start_cd(guid) if not daily_limiter.check(guid) and poke_tip_cd_limiter.check(guid): daily_tip_limiter.increase(guid) await bot.send(ev, f'{at_user}你今天戳得已经够多的啦,再戳也不会有奇怪的东西掉下来的~') return daily_tip_limiter.reset(guid) while daily_limiter.check(guid): amount = roll_cards_amount() col_num = math.ceil(amount / 2) row_num = 2 if amount != 1 else 1 card_counter, card_descs, card = get_random_cards( db.get_cards_num(gid, uid), row_num, col_num, amount, True, get_random_cards_list, SUPER_RARE_PROBABILITY, RARE_PROBABILITY) dash = '----------------------------------------' msg_part = '\n'.join(card_descs) await bot.send( ev, f'别戳了别戳了o(╥﹏╥)o{card}{at_user}这些卡送给你了, 让我安静会...\n{dash}\n获得了:\n{msg_part}' ) for card_id in card_counter.keys(): db.add_card_num(gid, uid, card_id, card_counter[card_id]) daily_limiter.increase(guid)
async def voice_guess(bot, ev: CQEvent): if gm.is_playing(ev.group_id): await bot.finish(ev, "游戏仍在进行中…") with gm.start_game(ev.group_id) as game: record_path = os.path.join(HOSHINO_RES_PATH, 'record') if not os.path.exists(record_path): await cygames_voice_guess(bot, ev) return file_list = os.listdir(record_path) chosen_chara = random.choice(file_list) chara_path = os.path.join(HOSHINO_RES_PATH, 'record', chosen_chara) chara_list = os.listdir(chara_path) chosen_file = random.choice(chara_list) file_path = os.path.join(chara_path, chosen_file) await bot.send(ev, f'猜猜这段语音来自哪位角色? ({ONE_TURN_TIME}s后公布答案)') await bot.send( ev, MessageSegment.record(f'file:///{os.path.abspath(file_path)}')) #兼容"小仓唯骂我"插件的语音资源 if chosen_chara == 'mawo': game.answer = 1036 else: game.answer = int(chosen_chara) #print(chara.fromid(game.answer).name) await asyncio.sleep(ONE_TURN_TIME) # 结算 if game.winner: return c = chara.fromid(game.answer) await bot.send(ev, f"正确答案是: {c.name} {c.icon.cqcode}\n很遗憾,没有人答对~")
async def do_revgif(bot, ev, image_url, ifturn): print("正在准备图片") response = await aiorequests.get(image_url, headers=headers) image = Image.open(BytesIO(await response.content)) info = image.info print(f"frames:{image.n_frames}, mode:{image.mode}, info:{image.info}") if image.n_frames == 1: await bot.finish(ev, "并非GIF图片") if image.n_frames > 200: await bot.finish(ev, "GIF帧数太多了,懒得倒放[CQ:face,id=13]") turnAround = random.randint(0, 6) sequence = [f.transpose(turnAround).copy() if ifturn else f.copy() for f in ImageSequence.Iterator(image)] if len(sequence) > 30: await bot.send(ev, "ℹ正在翻转图片序列,请稍候") sequence.reverse() buf = BytesIO() sequence[0].save(buf, format='GIF', save_all=True, append_images=sequence[1:], disposal=2, quality=80, **info) base64_str = base64.b64encode(buf.getvalue()).decode() await bot.send(ev, ms.image('base64://' + base64_str))
async def diary(bot, ev: CQEvent): global pre name = '富婆' for i in ev.message: if i.get('type', False) == 'at': name = get_name(i.data['qq']) kw = ev.message.extract_plain_text().strip() time = datetime.datetime.now().strftime('%Y年%m月%d日') arr = kw.split('/') content = '' if len(arr) >= 2: weather, content = arr weather = weather.split(' ')[-1] else: weather = '' if arr[0].split(' ') == 2: weather = arr[0].split(' ')[-1] if not content: with open(os.path.join(os.path.dirname(__file__), 'diary_data.json'), 'r', encoding='utf-8') as file: diaries = json.load(file) while True: index = random.randint(0, len(diaries) - 1) if index != pre: pre = index content = diaries[index] for s in '你她': content = content.replace(s, name) break image = Image.open(os.path.join(os.path.dirname(__file__), 'diary.png')) img_width, img_height = image.size # 创建Font对象: font_size = img_width // 18 font = ImageFont.truetype( os.path.join(os.path.dirname(__file__), 'simhei.ttf'), font_size) positions = measure(content, font_size, img_width) str_list = list(content) for pos in positions: str_list.insert(pos, '\n') # 日期单独一行 line = len(positions) + 2 content = f'{time},{weather}\n' + "".join(str_list) line_h = font_size + 4 # 创建Draw对象: image_text = Image.new('RGB', (img_width, line_h * line), (255, 255, 255)) draw = ImageDraw.Draw(image_text) draw.text((0, 0), content, fill=(0, 0, 0), font=font, spacing=2) # 模糊: # image_text = image_text.filter(ImageFilter.BLUR) image_back = Image.new('RGB', (img_width, line_h * line + img_height), (255, 255, 255)) image_back.paste(image, (0, 0)) image_back.paste(image_text, (0, img_height)) await bot.send(ev, str(MessageSegment.image(pic2b64(image_back))))
async def get_song_info_from_song(song): song_data = _song_data.SONG_DATA[song] pic_url = await get_pic_url(song_data[5]) if song_data[5] else "" img = MessageSegment.image(pic_url) if pic_url else "" msg_part = '' if song_data[6] == '' else '\n-------------------------------------------\n' song_info = song_data[2] + song + str(img) + '歌曲名: ' + song_data[3] + '\n' + '歌手: ' + song_data[4] + msg_part + \ song_data[6] return song_info, song_data
def format_tweet(tweet): name = tweet.user.name time = format_time(tweet.created_at) text = tweet.text media = tweet.get('extended_entities', {}).get('media', []) imgs = ' '.join([str(ms.image(m.media_url)) for m in media]) msg = f"@{name}\n{time}\n\n{text}" if imgs: msg = f"{msg}\n{imgs}" return msg
async def avatar_find(bot, ev: CQEvent): if gm.is_playing(ev.group_id): await bot.finish(ev, "游戏仍在进行中…") with gm.start_game(ev.group_id) as game: game.answer, answer_pic = get_merge_avatar() answer_pic = MessageSegment.image(util.pic2b64(answer_pic)) await bot.send(ev, f'请找出不一样的头像坐标?({ONE_TURN_TIME}s后公布答案){answer_pic}') await asyncio.sleep(ONE_TURN_TIME) if game.winner: return await bot.send(ev, f'正确答案是: {game.answer}\n很遗憾,没有人答对~')
async def poke_back(bot, event, mode='poke'): uid = event['user_id'] gid = event['group_id'] me_id = await bot.get_login_info() me_id = me_id['user_id'] at_user = MessageSegment.at(uid) guid = gid, uid if not cooling_time_limiter.check(uid): return cooling_time_limiter.start_cd(uid) if mode == 'poke' and event['target_id'] != me_id: return if not daily_limiter.check(guid) and not daily_tip_limiter.check(guid): poke_tip_cd_limiter.start_cd(guid) if not daily_limiter.check(guid) and poke_tip_cd_limiter.check(guid): daily_tip_limiter.increase(guid) await bot.send(event, f'{at_user}你今天戳得已经够多的啦,再戳也不会有奇怪的东西掉下来的~') return daily_tip_limiter.reset(guid) if not daily_limiter.check(guid) or random.random() > POKE_GET_CARDS: poke = MessageSegment(type_='poke', data={ 'qq': str(uid), }) await bot.send(event, poke) else: amount = roll_cards_amount() col_num = math.ceil(amount / 2) row_num = 2 if amount != 1 else 1 card_counter, card_descs, card = get_random_cards( db.get_cards_num(gid, uid), row_num, col_num, amount, True, get_random_cards_list, SUPER_RARE_PROBABILITY, RARE_PROBABILITY) dash = '----------------------------------------' msg_part = '\n'.join(card_descs) await bot.send( event, f'别戳了别戳了o(╥﹏╥)o\n{card}\n{at_user}这些卡送给你了, 让我安静会...\n{dash}\n获得了:\n{msg_part}' ) for card_id in card_counter.keys(): db.add_card_num(gid, uid, card_id, card_counter[card_id]) daily_limiter.increase(guid)
async def perfect_match(bot, ev: CQEvent): if gm.is_playing(ev.group_id): await bot.finish(ev, "游戏仍在进行中…") with gm.start_game(ev.group_id) as game: chosen_ids = random.sample(game_util.VALID_IDS, TOTAL_PIC_NUM) pushed_index = set() # 发送若干轮的隐藏部分子图的合成图,保证所有子图至少都被发送一次。发送完毕后等待若干秒再撤回图片 for i in range(TURN_NUM): await bot.send(ev, f'记忆阶段{i+1}/{TURN_NUM}: ({BASIC_SHOW_TIME - i * 2}s后我会撤回图片哦~)') if i < TURN_NUM-1: shown_index = random.sample(range(TOTAL_PIC_NUM), TOTAL_PIC_NUM - HIDDEN_NUM) ids = [chosen_ids[i] if i in shown_index else game_util.UNKNOWN_ID for i in range(TOTAL_PIC_NUM)] pushed_index = pushed_index.union(set(shown_index)) else: remnant_index = set(range(TOTAL_PIC_NUM)) - pushed_index shown_index = list(remnant_index) shown_index.extend(random.sample(pushed_index, TOTAL_PIC_NUM - HIDDEN_NUM - len(remnant_index))) ids = [chosen_ids[i] if i in shown_index else game_util.UNKNOWN_ID for i in range(TOTAL_PIC_NUM)] pic = MessageSegment.image(util.pic2b64(game_util.generate_full_pic(ROW_NUM, COL_NUM, ids))) msg = await bot.send(ev, pic) await asyncio.sleep(BASIC_SHOW_TIME - i * 2) await bot.delete_msg(message_id=msg['message_id']) await asyncio.sleep(3) # 开始答题 correct_index = random.randint(0, TOTAL_PIC_NUM - 1) correct_id = chosen_ids[correct_index] game.answer = correct_index + 1 correct_pic_img = MessageSegment.image(util.pic2b64(game_util.get_sub_pic_from_id(correct_id))) answer_number_img = MessageSegment.image(f'file:///{os.path.abspath(game_util.BACKGROUND_PIC_PATH)}') await bot.send(ev, f'还记得"{game_util.EXPLANATION[correct_id]}"的位置吗?{correct_pic_img}请告诉我它的编号~ ({ANSWER_TIME}s后公布答案){answer_number_img}') await asyncio.sleep(ANSWER_TIME) # 结算 game.update_score() msg_part1 = f'{MessageSegment.at(game.winner[0])}首先答对,真厉害~ 加2分! 当前总分为{game.get_first_winner_score()}分' if game.winner else '' msg_part2 = f'{game_util.generate_at_message_segment(game.winner[1:])}也答对了, 加1分~' if game.winner[1:] else '' msg_part3 = f'{game_util.generate_at_message_segment(game.loser)}答错了, 扣1分o(╥﹏╥)o' if game.loser else '' msg_part4 = '咦, 这轮游戏没人参与, 看来题目可能有点难...' if not (msg_part1 or msg_part2 or msg_part3) else "" msg_part = '\n'.join([s for s in [msg_part1, msg_part2, msg_part3, msg_part4] if s]) await bot.send(ev, f'正确答案是: {game.answer}{MessageSegment.image(util.pic2b64(game_util.generate_full_pic(ROW_NUM, COL_NUM, chosen_ids)))}{msg_part}')
async def see_a_see_frame(bot, ev): user_id = str(ev.user_id) current_dir = os.path.join(os.path.dirname(__file__), 'frame.json') with open(current_dir, 'r', encoding='UTF-8') as f: f_data = json.load(f) id_list = list(f_data['customize'].keys()) if user_id not in id_list: frame_tmp = f_data['default_frame'] else: frame_tmp = f_data['customize'][user_id] path = os.path.join(os.path.dirname(__file__), f'img/frame/{frame_tmp}') msg = MessageSegment.image(f'file:///{os.path.abspath(path)}') await bot.send(ev, msg)
async def show_custom_reply(bot, ev): if not ev.group_id: await bot.finish(ev, "抱歉,自定义回复仅可在群聊中使用") msg = "[本群自定义回复]\n" if custom_reply.get(str(ev.group_id)): for key in custom_reply.get(str(ev.group_id)): msg += f"{html.unescape(key)}: {custom_reply.get(str(ev.group_id))[key]['content']}\n" else: msg += "无\n" msg += "[全局自定义回复]\n" for key in custom_reply.get("global"): msg += f"{html.unescape(key)}: {custom_reply.get('global')[key]['content']}\n" await bot.send(ev, MessageSegment.image(text2img(msg)))
async def music_daily_push(): bot = hoshino.get_bot() glist = await sv.get_enable_groups() info_head = '今日份的午间音乐广播~' for gid, selfids in glist.items(): song_info, song_data = await get_next_song(gid) if song_data[0] == 'bili': music = MessageSegment.share( url='https://www.bilibili.com/video/' + song_data[1], title=song_data[3], content=song_data[4], image_url= "http://i0.hdslb.com/bfs/archive/b28c463d04db58f6eb79e238757b78ab1f609ec0.png" ) else: music = MessageSegment.music(type_=song_data[0], id_=song_data[1]) await bot.send_group_msg(self_id=random.choice(selfids), group_id=gid, message=info_head + song_info) await bot.send_group_msg(self_id=random.choice(selfids), group_id=gid, message=music) await asyncio.sleep(0.5)
async def spider_work(spider: BaseSpider, bot, gid, sv: Service, TAG): if not spider.item_cache[gid]: await spider.get_update(gid) sv.logger.info(f'群{gid}的{TAG}缓存为空,已加载至最新') return updates = await spider.get_update(gid) if not updates: sv.logger.info(f'群{gid}的{TAG}未检索到新视频') return sv.logger.info(f'群{gid}的{TAG}检索到{len(updates)}个新视频!') msg_list = spider.format_items(updates) for i in range(len(updates)): pic = MessageSegment.image('http:' + updates[i].pic) msg = f'{msg_list[0]}{pic}{msg_list[i+1]}' await bot.send_group_msg(group_id=int(gid), message=msg)
async def billing(session: CommandSession): bot = session.bot args = session.current_arg_text.split() try: for i in range(0, len(args), 2): args[i] = int(args[i]) assert re.fullmatch(r'\d{4}-\d{2}-\d{2}', args[i + 1]), f"{args[i + 1]}不是合法日期" except (ValueError, AssertionError) as e: await session.finish(str(e)) try: sid_group = {} for sid in hoshino.get_self_ids(): gs = await bot.get_group_list(self_id=sid) sid_group[sid] = [g['group_id'] for g in gs] except CQHttpError as e: await session.finish(str(e)) failed = [] not_found = [] for i in range(0, len(args), 2): gid = args[i] date = args[i + 1] bill_sent_flag = False for sid, groups in sid_group.items(): if gid in groups: msg = f"本群bot将于/已于{date}到期,请及时联系{hoshino.config.SUPERUSERS[0]}续费,以免影响使用!" oid = await get_group_owner_id(bot, sid, gid) if oid: msg = str(ms.at(oid)) + msg try: await bot.send_group_msg(self_id=sid, group_id=gid, message=msg) bill_sent_flag = True except CQHttpError: failed.append(gid) try: await session.send(f"bot{sid} 向 群{gid} 发送billing失败!") except CQHttpError: hoshino.logger.critical( (f"bot{sid} 向 群{gid} 发送billing失败!且回报SUPERUSER失败!")) if not bill_sent_flag and gid not in failed: not_found.append(gid) msg = f"发送bill完毕!\n失败{len(failed)}:{failed}\n未找到{len(not_found)}:{not_found}" await session.send(msg)
async def get_view(self, sauce) -> str: sauces = await self.get_sauce(sauce) repass = "" simimax = 0 for sauce in sauces['results']: try: url = sauce['data']['ext_urls'][0].replace( "\\", "").strip() if 'ext_urls' in sauce['data'] else "no link" similarity = sauce['header']['similarity'] if not similarity.replace(".", "").isdigit(): #print(sauce) similarity = 0 simimax = float( similarity) if float(similarity) > simimax else simimax thumbnail_url = sauce['header']['thumbnail'] if THUMB_ON: try: thumbnail_image = str( MessageSegment.image( pic2b64( ats_pic( Image.open( BytesIO( await get_pic(thumbnail_url))))))) except Exception as e: print(format_exc()) thumbnail_image = "[预览图下载失败]" else: thumbnail_image = "" service_name, info = sauces_info(sauce) putline = f"{thumbnail_image}\n[{service_name}][{url}] 相似度:{similarity}%\n{info}" if repass: repass = "******".join([repass, putline]) else: repass = putline except Exception as e: print(format_exc()) #print(sauce) pass return [repass, simimax]
def format_tweet(tweet): name = tweet.user.name if peony.events.retweet(tweet): return f"@{name} 转推了\n>>>>>\n{format_tweet(tweet.retweeted_status)}" time = format_time(tweet.created_at) text = tweet.text media = tweet.get("extended_entities", {}).get("media", []) imgs = " ".join([str(ms.image(m.media_url)) for m in media]) msg = f"@{name}\n{time}\n\n{text}" if imgs: msg = f"{msg}\n{imgs}" if "quoted_status" in tweet: quoted_msg = format_tweet(tweet.quoted_status) msg = f"{msg}\n\n>>>>>\n{quoted_msg}" return msg
async def on_input_image(bot, ev: CQEvent): if str(ev.group_id) not in gacha_threshold.threshold: return for seg in ev.message: if seg.type == 'image': img = seg.data['file'] need_ocr = await is_possible_gacha_image(bot, ev, img) if need_ocr: need_delete_msg, need_silence = await check_image(bot, ev, img) if need_delete_msg: #if need_silence: await bot.send(ev, '检测到海豹行为(╯‵□′)╯︵┻━┻') # await bot.delete_msg(self_id=ev.self_id, message_id=ev.message_id) # await util.silence(ev, 10*60, skip_su=False) await bot.send( ev, botname + '提醒您:\n' + str( MessageSegment.image( f'file:///{os.path.abspath(PIC_PATH)}')) + '\n拒绝海豹,从我做起')
async def migang_reply_help(bot, ev): msg = """ [添加群自定义回复] [基础] .migangreply add 关键词 自定义回复 [进阶] .migangreply add 关键词 自定义回复 0 (在回复时不at对方, 最后参数默认为0) .migangreply add 关键词 自定义回复 1 (在回复时at对方) [删除群自定义回复] .migangreply del 关键词 [查看自定义回复] 米缸查看自定义回复 [Tips] 图片请不要直接使用粘贴方式设定自定义回复,否则未来会失效,建议采用图床上传图片 类似([CQ:image,file=https://image.cinte.cc/2021/01/24/886d904a65e51.png]) (群自定义回复优先级高于维护者设定的全局自定义回复, 仅在群聊中可使用自定义回复) """.strip() await bot.send(ev, MessageSegment.image(text2img(msg)))