def get_setu_native(r18=0, uid=0): image = generate_image_struct() path = f'setu/lolicon' if r18 == 1: path = f'setu/lolicon_r18' elif r18 == 2: if random.randint(1, 100) > 50: path = f'setu/lolicon_r18' res = R.img(path) if not os.path.exists(res.path): return image if uid == 0: fn = random.choice(os.listdir(res.path)) if fn.split('.')[0].isdigit(): uid = int(fn.split('.')[0]) if not uid: return image image['id'] = int(uid) image['native'] = True path += f'/{uid}' res = R.img(path) try: image['data'] = res.path + '.jpg' with open(res.path + '.json', encoding='utf8') as f: d = json.load(f) if 'title' in d: image['title'] = d['title'] if 'author' in d: image['author'] = d['author'] if 'url' in d: image['url'] = d['url'] except: pass return image
async def chat_waifu(bot: Bot, event: CQEvent): if not priv.check_priv(event, priv.SUPERUSER): if random.random() < 0.50: await bot.send(event, Message(R.img('laopo.jpg').cqcode)) else: await bot.send(event, Message(R.img('喊谁老婆呢.jpg').cqcode)) else: await bot.send(event, 'mua~')
async def update_seeker(): ''' 轮询官方四格漫画更新 若有更新则推送至订阅群 ''' index_api = 'https://comic.priconne-redive.jp/api/index' index = load_index() # 获取最新漫画信息 resp = await aiohttpx.get(index_api, timeout=10) data = resp.json() id_ = data['latest_cartoon']['id'] episode = data['latest_cartoon']['episode_num'] title = data['latest_cartoon']['title'] # 检查是否已在目录中 # 同一episode可能会被更新为另一张图片(官方修正),此时episode不变而id改变 # 所以需要两步判断 if episode in index: qs = urlparse(index[episode]['link']).query old_id = parse_qs(qs)['id'][0] if id_ == old_id: salmon.logger.info('未检测到官漫更新') return # 确定已有更新,下载图片 salmon.logger.info(f'发现更新 id={id_}') await download_comic(id_) # 推送至各个订阅群 pic = R.img('priconne/comic', get_pic_name(episode)).cqcode msg = Message(f'プリンセスコネクト!Re:Dive公式4コマ更新!\n第{episode}話 {title}\n{pic}') await sv.broadcast(msg, 'PCR官方四格', 0.5)
async def get_setu_online(num, r18=0, keyword=None): image_list = await query_setu(r18=r18, keyword=keyword) if image_list == None: return valid_list = [] while len(image_list) > 0: image = image_list.pop(random.randint(0, len(image_list) - 1)) # 检查本地是否存在该图片 path = f'setu/lolicon/{image["id"]}.jpg' if image['r18']: path = f'setu/lolicon_r18/{image["id"]}.jpg' res = R.img(path) if os.path.exists(res.path): image['data'] = res.path image['native'] = True else: if get_config('lolicon', 'pixiv_direct'): image['data'] = await download_pixiv_image( image['url'], image['id']) else: image['data'] = await download_image(image['url']) image['native'] = False if image['data'] and get_config('lolicon', 'mode') == 2: save_image(image) image['data'] = res.path if image['data']: valid_list.append(image) if len(valid_list) >= num: break return valid_list
def setu_gener(): while True: filelist = os.listdir(setu_folder) random.shuffle(filelist) for filename in filelist: if os.path.isfile(os.path.join(setu_folder, filename)): yield R.img('setu/', filename)
def save_image(image): path = f'setu/lolicon/{image["id"]}' if image['r18']: path = f'setu/lolicon_r18/{image["id"]}' res = R.img(path + '.jpg') with open(res.path, 'wb') as f: f.write(image['data']) res = R.img(path + '.json') info = { 'title': image['title'], 'author': image['author'], 'url': image['url'], 'tags': image['tags'], } with open(res.path, 'w', encoding='utf8') as f: json.dump(info, f, ensure_ascii=False, indent=2)
async def download_comic(id_): ''' 下载指定id的官方四格漫画,同时更新漫画目录index.json episode_num可能会小于id ''' base = 'https://comic.priconne-redive.jp/api/detail/' save_dir = R.img('priconne/comic/').path index = load_index() # 先从api获取detail,其中包含图片真正的链接 salmon.logger.info(f'getting comic {id_} ...') url = base + id_ salmon.logger.info(f'url={url}') resp = await aiohttpx.get(url) salmon.logger.info(f'status_code={resp.status_code}') if 200 != resp.status_code: return data = resp.json() data = data[0] episode = data['episode_num'] title = data['title'] link = data['cartoon'] index[episode] = {'title': title, 'link': link} salmon.logger.info(f'episode={index[episode]}') # 下载图片并保存 await download_img(os.path.join(save_dir, get_pic_name(episode)), link) # 保存官漫目录信息 with open(os.path.join(save_dir, 'index.json'), 'w', encoding='utf8') as f: json.dump(index, f, ensure_ascii=False)
def check_path(): state = {} sub_dirs = ['lolicon', 'lolicon_r18'] for item in sub_dirs: res = R.img('setu/' + item) if not os.path.exists(res.path): os.makedirs(res.path) state[item] = len(os.listdir(res.path)) // 2 return state
async def ban_word(bot: Bot, event: CQEvent): user_id = event.user_id user_info = await bot.get_stranger_info(user_id=user_id) nickname = user_info.get('nickname', '未知用户') salmon.logger.critical( f'Self: {event.self_id}, Message {event.message_id} from {user_id}: {event.message}' ) priv.set_block_user(user_id, timedelta(hours=8)) pic = R.img(f"chieri{random.randint(1, 4)}.jpg").cqcode if isinstance(event, GroupMessageEvent): await bot.send(event, Message(f">{nickname}\n不理你啦!バーカー\n{pic}")) await util.silence(bot, event, 8 * 60 * 60) elif isinstance(event, PrivateMessageEvent): await bot.send(event, Message(f"不理你啦!バーカー\n{pic}"))
def download_chara_icon(id_, star): url = f'https://redive.estertion.win/icon/unit/{id_}{star}1.webp' save_path = R.img(f'priconne/unit/icon_unit_{id_}{star}1.png').path salmon.logger.info(f'Downloading chara icon from {url}') try: rsp = requests.get(url, stream=True, timeout=5) except Exception as e: salmon.logger.error(f'Failed to download {url}. {type(e)}') salmon.logger.exception(e) if 200 == rsp.status_code: img = Image.open(BytesIO(rsp.content)) img.save(save_path) salmon.logger.info(f'Saved to {save_path}') else: salmon.logger.error( f'Failed to download {url}. HTTP {rsp.status_code}')
async def give_okodokai(bot: Bot, event: CQEvent): uid = event.user_id user_info = await bot.get_stranger_info(user_id=uid) nickname = user_info.get('nickname', '未知用户') if not lmt.check(uid): if isinstance(event, GroupMessageEvent): await login.finish(f'>{nickname}\n明日はもう一つプレゼントをご用意してお待ちしますね') elif isinstance(event, PrivateMessageEvent): await login.finish('明日はもう一つプレゼントをご用意してお待ちしますね') lmt.increase(uid) present = random.choice(login_presents) todo = random.choice(todo_list) pic = Message(R.img("priconne/kokkoro_stamp.png").cqcode) if isinstance(event, GroupMessageEvent): msg = f'>{nickname}\nおかえりなさいませ、主さま' + pic + f'\n{present}を獲得しました\n私からのプレゼントです\n主人今天要{todo}吗?' elif isinstance(event, PrivateMessageEvent): msg = 'おかえりなさいませ、主さま' + pic + f'\n{present}を獲得しました\n私からのプレゼントです\n主人今天要{todo}吗?' await login.finish(msg)
def icon(self): star = '3' if 1 <= self.star <= 5 else '6' res = R.img(f'priconne/unit/icon_unit_{self.id}{star}1.png') if not res.exist: res = R.img(f'priconne/unit/icon_unit_{self.id}31.png') if not res.exist: res = R.img(f'priconne/unit/icon_unit_{self.id}11.png') if not res.exist: # FIXME: 不方便改成异步请求 download_chara_icon(self.id, 6) download_chara_icon(self.id, 3) download_chara_icon(self.id, 1) res = R.img(f'priconne/unit/icon_unit_{self.id}{star}1.png') if not res.exist: res = R.img(f'priconne/unit/icon_unit_{self.id}31.png') if not res.exist: res = R.img(f'priconne/unit/icon_unit_{self.id}11.png') if not res.exist: res = R.img(f'priconne/unit/icon_unit_{UNKNOWN}31.png') return res
def load_native_info(sub_dir): info = {} path = f'setu/' + sub_dir res = R.img(path) if not os.path.exists(res.path): return info fnlist = os.listdir(res.path) for fn in fnlist: s = fn.split('.') if len(s) != 2 or s[1] != 'json' or not s[0].isdigit(): continue uid = int(s[0]) try: with open(res.path + '/' + fn, encoding='utf8') as f: d = json.load(f) d['tags'].append(d['title']) d['tags'].append(d['author']) info[uid] = ','.join(d['tags']) except: pass salmon.logger.info(f'reading {len(info)} setu from {sub_dir}') return info
async def read_comic(bot: Bot, event: CQEvent, state: T_State): episode = state['episode'] user_info = await bot.get_stranger_info(user_id=event.user_id) nickname = user_info.get('nickname', '未知用户') if not re.fullmatch(r'\d{0,3}', episode): raise FinishedException episode = episode.lstrip('0') index = load_index() if episode not in index: if isinstance(event, GroupMessageEvent): await comic.finish(f'>{nickname}\n未查找到第{episode}话,敬请期待官方更新') elif isinstance(event, PrivateMessageEvent): await comic.finish(f'未查找到第{episode}话,敬请期待官方更新') title = index[episode]['title'] pic = R.img('priconne/comic/', get_pic_name(episode)).cqcode if isinstance(event, GroupMessageEvent): await comic.finish( Message( f'>{nickname}\nプリンセスコネクト!Re:Dive公式4コマ\n第{episode}話 {title}\n{pic}' )) elif isinstance(event, PrivateMessageEvent): await comic.finish( Message(f'プリンセスコネクト!Re:Dive公式4コマ\n第{episode}話 {title}\n{pic}'))
async def chat_queshi(bot: Bot, event: CQEvent): if random.random() < 0.05: await bot.send(event, Message(R.img('确实.jpg').cqcode))
async def send_seina(bot: Bot, event: CQEvent): await bot.send(event, Message(R.img('星奏.png').cqcode))
async def do_like(qkey, user_id, action): true_id = get_true_id(qkey, user_id) if true_id is None: raise KeyError add_like(true_id, user_id) if action > 0 else add_dislike(true_id, user_id) dump_db() # TODO: upload to website aliases = ('怎么拆', '怎么解', '怎么打', '如何拆', '如何解', '如何打', 'jjc查询') aliases_b = tuple('b' + a for a in aliases) + tuple('B' + a for a in aliases) aliases_tw = tuple('台' + a for a in aliases) aliases_jp = tuple('日' + a for a in aliases) try: thumb_up_i = R.img('priconne/gadget/thumb-up-i.png').open().resize((16, 16), Image.LANCZOS) thumb_up_a = R.img('priconne/gadget/thumb-up-a.png').open().resize((16, 16), Image.LANCZOS) thumb_down_i = R.img('priconne/gadget/thumb-down-i.png').open().resize((16, 16), Image.LANCZOS) thumb_down_a = R.img('priconne/gadget/thumb-down-a.png').open().resize((16, 16), Image.LANCZOS) except Exception as e: salmon.logger.exception(e) arena_query = sv.on_fullmatch('查竞技场', aliases=aliases, only_group=False) arena_query_b = sv.on_fullmatch('b竞技场', aliases=aliases_b, only_group=False) arena_query_tw = sv.on_fullmatch('台竞技场', aliases=aliases_tw, only_group=False) arena_query_jp = sv.on_fullmatch('日竞技场', aliases=aliases_jp, only_group=False) @arena_query.handle() @arena_query_b.handle() @arena_query_tw.handle() @arena_query_jp.handle()
import random from nonebot.adapters.cqhttp.exception import NetworkError from salmon import priv, Service, R, Bot import salmon from salmon.util import DailyNumberLimiter, FreqLimiter from salmon.typing import CQEvent, T_State, GroupMessageEvent, PrivateMessageEvent, Message _max = 5 EXCEED_NOTICE = f'您今天已经冲过{_max}次了,请明早5点后再来!' CD_NOTICE = '您冲得太快了,请稍候再冲' _nlmt = DailyNumberLimiter(_max) _flmt = FreqLimiter(5) sv = Service('setu', manage_priv=priv.SUPERUSER, enable_on_default=False, visible=False) setu_folder = R.img('setu/').path if not setu_folder: os.makedirs(os.path.expanduser(setu_folder), exist_ok=True) def setu_gener(): while True: filelist = os.listdir(setu_folder) random.shuffle(filelist) for filename in filelist: if os.path.isfile(os.path.join(setu_folder, filename)): yield R.img('setu/', filename) setu_gener = setu_gener()
all_season[1:11] = 500 all_season[11:101] = 50 all_season[101:201] = 30 all_season[201:501] = 10 all_season[501:1001] = 5 all_season[1001:2001] = 3 all_season[2001:4001] = 2 all_season[4001:7999] = 1 all_season[8100:15001:100] = 30 rank_jp = '20-4' rank_tw = '19-3' rank_cn = '12-5' ptw = ' '.join(map(str, [ R.img(f'priconne/quick/{rank_tw}_1.png').cqcode, R.img(f'priconne/quick/{rank_tw}_2.png').cqcode, R.img(f'priconne/quick/{rank_tw}_3.png').cqcode, ])) pjp = ' '.join(map(str, [ R.img(f'priconne/quick/{rank_jp}_1.png').cqcode, R.img(f'priconne/quick/{rank_jp}_2.png').cqcode, R.img(f'priconne/quick/{rank_jp}_3.png').cqcode, ])) pcn = ' '.join(map(str, [ R.img(f'priconne/quick/{rank_cn}_1.png').cqcode, R.img(f'priconne/quick/{rank_cn}_2.png').cqcode, ])) YUKARI_SHEET = Message(f'''
async def chat_clanba(bot: Bot, event: CQEvent): if random.random() < 0.02: await bot.send(event, Message(R.img('我的天啊你看看都几点了.jpg').cqcode))
async def chat_neigui(bot: Bot, event: CQEvent): if random.random() < 0.10: await bot.send(event, Message(R.img('内鬼.png').cqcode))
from salmon import R, util, Bot from salmon.typing import CQEvent, FinishedException from salmon.modules.priconne.pcr_data import _pcr_data UNKNOWN = 1000 UnavailableChara = { 1000, # 未知角色 1067, # 穗希 1069, # 霸瞳 1072, # 可萝爹 1073, # 拉基拉基 1102, # 泳装大眼 } try: gadget_equip = R.img('priconne/gadget/equip.png').open() gadget_star = R.img('priconne/gadget/star.png').open() gadget_star_dis = R.img('priconne/gadget/star_disabled.png').open() gadget_star_pink = R.img('priconne/gadget/star_pink.png').open() unknown_chara_icon = R.img( f'priconne/unit/icon_unit_{UNKNOWN}31.png').open() except Exception as e: salmon.logger.exception(e) class Roster: def __init__(self): self._roster = pygtrie.CharTrie() self.update() def update(self):