def api_wrapper(): if api_closure: return api_closure[0] LOG.debug("Creating new AppPixivAPI instance and logging in.") api_closure.append(pixivpy3.AppPixivAPI()) username, _, password = netrc().authenticators("pixiv.net") api_closure[0].login(username, password) return api_closure[0]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.aapi = pixivpy3.AppPixivAPI() self.papi = pixivpy3.PixivAPI() saved_auth = self.get_param_cache() if saved_auth: self.log.info("Using cached auth") self.aapi.set_auth(access_token=saved_auth['a_access_token'], refresh_token=saved_auth['a_refresh_token']) self.papi.set_auth(access_token=saved_auth['p_access_token'], refresh_token=saved_auth['p_refresh_token'])
def apiLogin() -> pixivpy3.AppPixivAPI: logger.info("尝试登录gPixiv") api = pixivpy3.AppPixivAPI() # api.require_appapi_hosts() api.set_accept_language('en-us') if config.REFRESH_TOKEN: api.auth(refresh_token=refresh(api.hosts, config.REFRESH_TOKEN)) logger.info("Pixiv登录成功") else: raise Exception("请设置refresh_token") return api
def get_top_illusts(K): """ 获取日榜中前K名的信息 :param K: 要获取的图片信息数量 :return: 日榜中前K张图片的信息list """ api = pixivpy3.AppPixivAPI() json_result = api.illust_ranking("day_male") illusts = json_result.illusts while len(illusts) < K: next_qs = api.parse_qs(json_result.next_url) json_result = api.illust_ranking(**next_qs) illusts += json_result.illusts return illusts[:min(K, len(illusts))]
def get_illust_from_keywords(keywords): """ 根据关键词随机获取一张图片的信息 :param keywords: 关键词(字符串) :return: 一张图片的信息(可能为None) """ illust = None api = pixivpy3.AppPixivAPI() json_result = api.search_illust(keywords, search_target="partial_match_for_tags") illusts = json_result.illusts if len(illusts) > 0: illust = illusts[randint(0, len(illusts) - 1)] return illust
def save_illusts(self, artist_id): fpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'illusts', str(artist_id), '') if not os.path.exists(fpath): os.mkdir(fpath) aapi = pixivpy3.AppPixivAPI() illust_count = 0 for illust in self.generate_illust(artist_id): aapi.download(illust.image_urls.large, fpath) print('Saving {}'.format(illust.id)) illust_count += 1 time.sleep(self.DOWNLOAD_DELAY) print('Total {} illusts saved'.format(illust_count))
def main(): # parse args and initialize logging options, args = parse_args() init_logging(options.logging) # some important file paths root_dir = os.path.dirname(os.path.realpath(__file__)) history_fp = os.path.join(root_dir, 'history') # initialize Pixiv API try: api = pixiv.AppPixivAPI() # Pixiv has removed password authentication, below is a workaround # using refresh tokens refresh_auth(api, os.path.join(root_dir, 'refresh')) except Exception as ex: log.error("Failed to initialize Pixiv API: %s" % str(ex)) sys.exit(1) # load history history = load_history(history_fp) for config_fp in args: try: config = parse_config(config_fp) except ConfigException: # parse_config already logged an error message continue # everybody walk the dinosaur for sub_tag in config['sub_tags']: try: search_and_post(api, options, config, history, *sub_tag) except pixiv.utils.PixivError as ex: log.error("Pixiv error: %s" % str(ex)) # wildcard if config['wildcard']: try: search_and_post(api, options, config, history, config['main_tag'], "Today's wildcard is...", "") except pixiv.utils.PixivError as ex: log.error("Pixiv error: %s" % str(ex)) # save history save_history(history_fp, history)
async def _api(): # since pixiv no longer support account login, use refresh_token instead. if (AquaPicture.last_login_time+7200 < time.time()): login_fail_count = 0 while(login_fail_count < 5): try: api = pixiv.AppPixivAPI() api.set_accept_language('en-us') api.auth(refresh_token=Auth.refresh_token) AquaPicture.api = api AquaPicture.last_login_time = time.time() break except Exception: login_fail_count += 1 time.sleep(1) if (login_fail_count == 5): return "Authentication failed after 5 times, please try again later" return api else: return AquaPicture.api '''
def pixiv_tags(illust_id: int, conf: configparser.SectionProxy) -> str: """Fetch and return illustration tags from pixiv. Args: illust_id: The ID of the illustration conf: A configparser section containing user/password info Returns: A string containing tags for the illustration with given ID """ logger = logging.getLogger(__name__) logger.info(f"Beginning API call to get info on ID {illust_id}") api = pixivpy3.AppPixivAPI() logger.debug(f'Using username: {conf["username"]}, password: {conf["password"]}') api.login(conf["username"], conf["password"]) try: json_result = api.illust_detail(illust_id, req_auth=True) except pixivpy3.PixivError as inst: logger.error(inst) raise APIError(error=inst) illust = json_result.illust return " ".join(["[tags]", ", ".join([tag.name for tag in illust.tags])])
def get_pixiv_post_details(post_id): api = pixivpy3.AppPixivAPI() api.login(service_db['pix']['payload']['user'], service_db['pix']['payload']['pass']) req = api.illust_detail(int(post_id)) return req
# read info about which illust has already been download illust_existed = set() with open(target_folder + 'illust_data.csv', 'r', encoding='utf-8') as illust_log: csv_reader = csv.DictReader(illust_log, delimiter=',') for row in csv_reader: illust_existed.add(int(row['id'])) # open the log in write mode to append new informations illust_log = open(target_folder + 'illust_data.csv', 'a+', newline='', encoding='utf-8') # get pixiv api, source code: https://github.com/upbit/pixivpy aapi = pixivpy3.AppPixivAPI() # login your account, no premium needed aapi.login(account, password) # open the log in write mode to append new informations illust_log = open(target_folder + 'illust_data.csv', 'a+', newline='', encoding='utf-8') # search by the keyword for keyword in keywords: logging.info('Start scanning for %s' % (keyword)) page_index = 0 # get the first page of the search result search_result = aapi.search_illust( word=keyword,
output['text'] = '可接受指令:\n来份色图\n来n份色图\n来份图\n来n份图\ntag' # 未知输入 else: output['text'] = '你在做什么我不太懂呀~' # 报错 # except RuntimeError(): # output['text'] = '超时了,网络似乎不好呢' except: output['text'] = '人偶出现bug,请联系开发者进行维护' # tag输出为json文件 with open('tags_list.json', 'w', encoding="utf8") as fi: json.dump(tags_list, fi, ensure_ascii=False, indent=4) # 打印json print(json.dumps(output, ensure_ascii=False)) # 全局变量 # _tags_list = [] # tag列表 # 账号密码 _USERNAME = "******" _PASSWORD = "******" # 登录api api = p.AppPixivAPI() api.login(_USERNAME, _PASSWORD) main()
def get_pixiv_pic(url, filename): api = pixivpy3.AppPixivAPI() api.download(url, path='', name=filename)
def main(text): _USERNAME = "******" _PASSWORD = "******" # 登录api api = p.AppPixivAPI() api.login(_USERNAME, _PASSWORD) # 获得输入 可接受输入:来份色图/来n份色图/来份图/来n份图/tag... 其他输入会输出'你在做什么我不太懂呀~' # with open("pixivBot/out.txt", "r", encoding="UTF-8") as f: # text = f.read() # text = input() # text = input() # text = ' '.join(sys.argv[1:]) # print(text) # 初始化输出 tags_file = open('pixivBot/tags_list.json', 'r', encoding="utf8") tags_list = json.load(tags_file) output = { 'text': '', # 回复的消息内容 # 'qq': 'null', # @某qq回复 'img_list': [], # 要发送的图片列表 } try: # time_limit(1) # 寻找当天r18色图 donot_rush = [ "别冲了", "营养跟得上吗?", "你撸多了", "别撸了,伤身体", "再冲会暴毙信不", "求求你别冲了", "冲这么多你营养跟得上?", "求求你别冲了", "冲这么多你今晚biss", "天天看色图不去读书?", "再冲jb都给你剁了", "朋友少撸管多学习" ] img_lst = [] if text.startswith('来') and text.endswith('色图'): if text.endswith('三次元色图'): url = 'G:\\yasuo' if re.search('\d+', text) is None: num = '1' else: num = re.search('\d+', text).group() if int(num) >= 10: output['text'] = donot_rush[randint( 0, len(donot_rush) - 1)] else: for i in range(int(num)): for root, dirs, files in os.walk(url): img_url = "G:\yasuo\\" + files[randint( 0, files.__len__() - 1)] img_lst.append(img_url) output['img_list'] = img_lst elif text == '来份色图': output['img_list'], output['text'] = rank_by_time( api, mode="day_r18") else: num = re.search('\d+', text).group() if int(num) >= 10: output["text"] = donot_rush[randint( 0, len(donot_rush) - 1)] else: if num: output['img_list'], output['text'] = rank_by_time( api, mode="day_r18", num=int(num)) else: output['text'] = '输入有误!' # 当天热门榜随机 elif text.startswith('来') and text.endswith('份图'): if text == '来份图': output['img_list'], output['text'] = rank_by_time( api, mode='day_male') else: num = re.search('\d+', text).group() if int(num) >= 10: output["text"] = "图太多遭不住啊老哥" else: if num: output['img_list'], output['text'] = rank_by_time( api, mode='day_male', num=int(num)) else: output['text'] = '输入有误!' elif text.endswith("kkp") or text.endswith("看看批"): url = "G:\\kkp" n = randint(0, 10) if n < 8: output['text'] = "看你妈看" else: for root, dirs, files in os.walk(url): img_url = "G:\\kkp\\" + files[randint( 0, files.__len__() - 1)] img_lst.append(img_url) output['img_list'] = img_lst # 按tag搜寻: elif text.startswith('tag'): # tag搜寻帮助 if text == 'tag' or text.startswith('tag帮助'): output[ 'text'] += '用法:\n1 “tag 标签1 标签2 ……”\n2 tag查询后按序号检索\n3 tag? 代表随机一个tag' # 列出推荐tag列表 elif text == 'tag查询': tags_list = get_tags(api) for i in range(len(tags_list)): output['text'] += str(i + 1) + ' ' + tags_list[i] + '\n' elif text == 'tag?' or text == 'tag?': output['img_list'], output['text'] = search_by_tag_popular( api=api, word=tags_list[randint(0, 39)]) # 直接搜寻tag elif text.startswith('tag '): word = text[4:] output['img_list'], output['text'] = search_by_tag_popular( api=api, word=word) # 按tag列表索引 else: if not tags_list: output['text'] = '你还没查询过tag,不能使用tag索引!使用"tag查询"来获取tag' else: # print(int(text[3:]) - 1) output['img_list'], output['text'] = search_by_tag_popular( api=api, word=tags_list[int(text[3:]) - 1]) elif text == '帮助': output['text'] = '可接受指令:\n来(n)份色图\n来(n)份图\n来(n)份三次元色图\ntag' # 未知输入 else: output['text'] = '' # 报错 # except RuntimeError(): # output['text'] = '超时了,网络似乎不好呢' except Exception as e: output['text'] = '又你妈宕机了' raise e # tag输出为json文件 with open('pixivBot/tags_list.json', 'w', encoding="utf8") as fi: json.dump(tags_list, fi, ensure_ascii=False, indent=4) # 打印json print(json.dumps(output, ensure_ascii=False)) with open('pixivBot/output.json', 'w', encoding="utf8") as f: json.dump(output, f, ensure_ascii=False) return output
#Pixiv clipboard downloader by noku import clipboard import asyncio import validators import urllib.request import time import _thread import pixivpy3 import urllib.parse as urlparse import json import traceback import os LINKS = [] API = pixivpy3.AppPixivAPI() PAPI = pixivpy3.PixivAPI() #configuration USERNAME = "" PASSWORD = "" RETRIES = 5 PATH = "images" META_FILEEXT = "txt" META_PATH = "meta" FILENAME_PATTERN = "{user[account]} - {title}@{id}" #downloads LINKS async def main(): while True: time.sleep(0.05)
if __name__ == '__main__': start_date = datetime.datetime(2017, 1, 1) # 开始时间 end_date = datetime.datetime(2018, 1, 1) # 结束时间(不含) day_rank_limit = 1 # 每天的抓取数 thread_num = 4 # 线程数 username = '******' # pixiv用户名 password = '******' # pixiv密码 save_root = './download' # 保存路径 timeout = 10 # 超时时间 try_time = 5 # 超时后重试次数 try_interval = 1 # 超时后重试的时间间隔 api = pp.AppPixivAPI(timeout=timeout) resp = api.login(username, password) pixiv_image_url_extractor = PixivImageUrlExtractor(api) downloader = Downloader(save_root=save_root, api=api, try_time=try_time, try_interval=try_interval) try: with ThreadPoolExecutor(max_workers=thread_num) as e: e.map( downloader, pixiv_image_url_extractor.extract_urls(start_date, end_date, day_rank_limit)) except Exception as et: print(et)
def index() -> make_response: req = request.get_data() sdk = HTTPSDK.httpGet(req) msg = sdk.getMsg() QMsg = msg.Msg print(msg) print(QMsg) # 存数据库 if msg.Group == "600302544": text = QMsg qq = msg.QQ group = msg.Group timestamp = datetime.now() if "pic" in text: type = 'img' urls = re.findall(':pic=(.+?)\]', text) path = '' if urls is not []: for u in urls: try: req = requests.get(u).content img_path = './dog_img/{QQ}_{uuid}.jpg'.format( QQ=qq, uuid=str(uuid4())[:8]) path += img_path + '\n' print(path) with open(img_path, 'wb') as f: f.write(req) except Exception as e: raise e else: type = 'text' path = 'null' message = Message(type=type, text=QMsg, path=path, qq=qq, group=group, timestamp=timestamp) db.session.add(message) db.session.commit() if get_in(QMsg): sdk.sendGroupMsg(msg.Group, QMsg) dic.clear() return make_response(sdk.toJsonString()) print(dic) # 5%概率复读 # if randint(0, 100) > 95: # sdk.sendGroupMsg(msg.Group, QMsg) # return make_response(sdk.toJsonString()) QMsg = QMsg.replace("那", "") if QMsg == "来道题": pass # with open("leetcode.txt", "r", encoding="utf8") as f: # questions = f.read().split("\n------\n") # question = questions[randint(0, len(questions))] # sdk.sendGroupMsg(msg.Group, question) elif QMsg.startswith("来首"): index = QMsg.find("首") music_name = QMsg[index + 1:] sdk.sendGroupMsg(msg.Group, "[ksust,music:name={}]".format(music_name)) elif "天气" in QMsg and ("样" in QMsg or "如何" in QMsg): QMsg = QMsg.replace("那", "") index = QMsg.find("天气") status, send_msg = get_info(QMsg[:index]) print(status) if status == "ok": sdk.sendGroupMsg(msg.Group, send_msg) else: sdk.sendGroupMsg(msg.Group, "暂不支持此地的查询") elif "我去" in QMsg: index = QMsg.find("去") verb = QMsg[index + 1] for i in verbs: if i in verb: sdk.sendGroupMsg(msg.Group, "你" + i + "个[emoji=F09F94A8],就你还" + i) return make_response(sdk.toJsonString()) sdk.sendGroupMsg(msg.Group, "你" + verb + "个[emoji=F09F94A8],就你还" + verb) elif "去" in QMsg and "了" in QMsg: index1 = QMsg.find("去") index2 = QMsg.find("了") for i in verbs: if i in QMsg[index2:index1:-1]: sdk.sendGroupMsg(msg.Group, "你" + i + "个[emoji=F09F94A8]") break elif "让我康康" in QMsg: _USERNAME = "******" _PASSWORD = "******" api = p.AppPixivAPI() api.login(_USERNAME, _PASSWORD) json_result = api.illust_ranking(mode='week') ri = r.randint(0, len(json_result.illusts) - 1) illust = json_result.illusts[ri] id = illust.id title = illust.title uuid_name = uuid4().hex api.download(illust.image_urls['large'], path='img/', name=uuid_name + '.jpg') address = os.getcwd() + '\\img\\' + uuid_name + '.jpg' print(address) sdk.sendGroupMsg(msg.Group, "[ksust,image:pic={}]".format(address)) sdk.sendGroupMsg( msg.Group, "https://www.pixiv.net/member_illust.php?mode=medium&illust_id={} " "title : {}".format(id, title)) elif (QMsg.startswith("来") and QMsg.endswith("图")) or QMsg.startswith("tag") or QMsg == "帮助" or \ QMsg.endswith("kkp") or QMsg.endswith("看看批"): if randint(0, 100) > 80: sdk.sendGroupMsg(msg.Group, "来你妈来") if randint(0, 100) > 50: sdk.sendGroupMsg( msg.Group, SendWord.query.get(randint(1, SendWord.query.count())).word) return make_response(sdk.toJsonString()) resp = main(QMsg) # ---------------PRODUCT MODE--------------------------- if msg.Type == HTTPSDK.TYPE_GROUP: if resp["text"] != "": sdk.sendGroupMsg(msg.Group, resp["text"]) if resp["img_list"] is not None: length = len(resp["img_list"]) for i in range(length): addr = resp["img_list"][i] sdk.sendGroupMsg(msg.Group, "[ksust,image:pic={}]".format(addr)) # ---------------DEBUG MODE--------------------------- # if msg.Type == HTTPSDK.TYPE_FRIEND: # if resp["text"] != "": # sdk.sendPrivdteMsg(msg.QQ, resp["text"]) # if resp["img_list"] != None: # length = len(resp["img_list"]) # for i in range(length): # addr = resp["img_list"][i] # sdk.sendPrivdteMsg(msg.QQ, "[ksust,image:pic={}]".format(addr)) # ---------------DEBUG MODE--------------------------- elif "at=3254622926" in QMsg or "at=1045970957" in QMsg: pattern = "".join( re.findall( r"\[(?:QQ)?(?:IR)?:at=(?:3254622926)?(?:1045970957)?\] ", QMsg)) if pattern == QMsg: sdk.sendGroupMsg(msg.Group, "@我干啥") return make_response(sdk.toJsonString()) for record in SendWord.query.all(): if record.word in QMsg: sdk.sendGroupMsg( msg.Group, SendWord.query.get(randint(1, SendWord.query.count())).word) if randint(0, 100) > 60: sdk.sendGroupMsg( msg.Group, SendWord.query.get(randint( 1, SendWord.query.count())).word) if randint(0, 100) > 90: sdk.sendGroupMsg( msg.Group, SendWord.query.get(randint( 1, SendWord.query.count())).word) return make_response(sdk.toJsonString()) record = QMsg.replace(pattern, "").strip() word = SendWord(word=record) db.session.add(word) db.session.commit() sdk.sendGroupMsg(msg.Group, "学到了,下次就用这话骂你") return make_response(sdk.toJsonString())
def command_pixiv(update, context, pixiv_api): date_today = datetime.date.today().strftime("%Y%m%d") args = parsePixivArgs(update.message.text) if "help" in update.message.text: update.message.reply_text(parse_mode="MarkdownV2", text=get_help_msg("help pixiv")) return # QUERY command to query specified resource. if "query" in update.message.text: if "id" in args or args[args.index("query") + 1].isdigit(): img_id = args[args.index("id") + 1] if "id" in args else args[args.index("query") + 1] json_details = pixiv_api.illust_detail(img_id) update.message.reply_text(str(json_details.illust)) else: update.message.reply_text("Sorry, wrong usage, see /pixiv help") # _ RANKING command to interact with pixiv rankings. if "ranking" in update.message.text: # TODO: not fully implemented if "daily" in update.message.text: ranking_to_print = "" url_list = [] pixiv_url_list = [] title_list = [] current_loop = 0 is_r18 = "r18" in update.message.text # Query ranking json_ranking = pixiv_api.illust_ranking( mode='day_r18') if is_r18 else pixiv_api.illust_ranking( mode='day') loop_limit = len(json_ranking.illusts) if args[args.index("daily") + 1].isdigit(): loop_limit = int(args[args.index("daily") + 1]) for illust in json_ranking.illusts: if current_loop < loop_limit: current_loop += 1 ranking_to_print += str(illust.title + "\n" + illust.image_urls['large'] + "\n") url_list.append(illust.image_urls['large']) pixiv_url_list.append("https://pixiv.net/artworks/" + str(illust.id)) title_list.append(illust.title) else: break # Check if user wants to pull the images. if "pull" in update.message.text: update.message.reply_text("Please wait...\n" + "is_r18: " + str(is_r18) + "\nDate is: " + date_today) path_to_save = "img_pixiv/ranking/daily/" + date_today + "/r18/" if is_r18 else "img_pixiv/ranking/daily/" + date_today + "/" if not os.path.exists(path_to_save): os.makedirs(path_to_save) # Start "pulling" image files. for url in url_list: if not os.path.exists( os.path.join(path_to_save, os.path.basename(url))): print("!!!!!!!!!!!!! pulling: " + str(url)) pixiv_api.download(url=str(url), path=path_to_save) else: print("!!!!!!!!!!!!! skipping: " + str(url)) img_files = [ f for f in os.listdir(path_to_save) if os.path.isfile(os.path.join(path_to_save, f)) ] for index, img_file in enumerate(img_files): img_path = os.path.join(path_to_save, img_file) try: context.bot.send_photo( chat_id=update.effective_chat.id, caption=title_list[index] + "\n" + pixiv_url_list[index], photo=open(img_path, 'rb')) sleep(0.5) except: pass else: update.message.reply_text( "Printing daily ranking illustrations.\nUse pull to download them." + "\n" + ranking_to_print) elif "weekly" in update.message.text: update.message.reply_text("Not implemented yet!") else: update.message.reply_text("Sorry, wrong usage, see /pixiv help") # _ PULL command to download specified resource. elif "pull" in update.message.text: # Check ID. if "id" in args or args[args.index("pull") + 1].isdigit(): img_id = args[args.index("id") + 1] if "id" in update.message.text else args[ args.index("pull") + 1] json_details = pixiv_api.illust_detail(img_id) print( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Requested download link is:", json_details.illust.image_urls.large) pixiv_api.download(url=json_details.illust.image_urls.large, path="img_pixiv") context.bot.send_photo( chat_id=update.effective_chat.id, photo=open( "img_pixiv/" + os.path.basename(json_details.illust.image_urls.large), 'rb')) elif "artist-id" in args: artist_id = args[args.index("artist-id") + 1] else: update.message.reply_text("Sorry, wrong usage, see /pixiv help") # _ FIND command elif "find" in update.message.text: key_word = args[args.index("find") + 1] json_result = pixiv_api.search_illust(key_word) url_list = [] title_list = [] pixiv_url_list = [] for illust in json_result.illusts[:5]: url_list.append(illust.image_urls.large) title_list.append(illust.title) pixiv_url_list.append("https://pixiv.net/artworks/" + str(illust.id)) context.bot.send_photo( chat_id=update.effective_chat.id, photo=illust.image_urls.medium, caption=illust.title + "\n" + "https://pixiv.net/artworks/" + str(illust.id), ) elif "init" in update.message.text: update.message.reply_text("Re-initialising pixiv api...") APIS.pixiv_api = None APIS.pixiv_api = pixivpy3.AppPixivAPI() APIS.pixiv_api.login(GlobalConst.PIXIV_USER, GlobalConst.PIXIV_PASS) update.message.reply_text("Successfully re-initialised pixiv api.") # DO NOTHING else: pass