def _login(self): """ Logins to pixiv in the background, using credentials from config file. """ api = AppPixivAPI() api.login(self._credentials['Username'], self._credentials['Password']) self.api_queue.put(api)
def sen_gif(message): bool_ban = SendTrackMessage(message, 'ugoira') if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 pixiv_id = -1 try: pixiv_id = message.text.split(' ')[1] int(pixiv_id) api = AppPixivAPI() api.login("your username", "pswe") file, title, tags, artist, _type = PixivDownloadUgoiraZip( pixiv_id, api) if _type != 'ugoira': bot.send_message(message.chat.id, '该图片不是ugoira,请使用id命令') else: caption = 'title : ' + title + '\n' + 'url : pixiv.net/i/' + pixiv_id + '\n' + 'tags : ' for tag in tags: if len(caption) + len(tag) < 193: caption = caption + tag + ' ' bot.send_document(message.chat.id, file, caption) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /ugoira 75162826')
def pixiv(page_url, options): from pixivpy3 import AppPixivAPI parsed = urlparse(page_url) id = int(parsed.path.split("/")[-1]) api = AppPixivAPI() secrets = h.get_secrets()["pixiv"] api.login(secrets["username"], secrets["password"]) data = api.illust_detail(id)["illust"] if len(data["meta_pages"]) == 0: image_url = data["meta_single_page"]["original_image_url"] elif options["album"]: image_url = [ image["image_urls"]["original"] for image in data["meta_pages"] ] else: image_url = data["meta_pages"][ options["index"]]["image_urls"]["original"] return Work( data["title"], ( data["user"]["account" if options["username"] else "name"], data["user"]["name" if options["username"] else "account"], ), None, data["x_restrict"] > 0, image_url, page_url, )
def send_picture_to_channel(message): if int(message.chat.id) not in white_list: try: temp_text = message.chat.title + '使用id命令' + ' ' + str( message.chat.id) + ' ' + message.chat.username except: temp_text = 'A Null is captured' bot.send_message('your chat_id', temp_text) bool_ban = False if int(message.chat.id) in black_list: bool_ban = True if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 pixiv_id = -1 try: pixiv_id = message.text.split(' ')[1] int(pixiv_id) api = AppPixivAPI() api.login("your username", "pswe") file, title, tags, artist = PixivDownloadOrigin(pixiv_id, api) if file == -1: bot.send_message(message.chat.id, '该图片不存在|Picture does not exist') else: caption = 'title : ' + title + '\n' + 'artist : ' + artist + '\n' + 'url : pixiv.net/i/' + pixiv_id + '\n' + 'tags : ' for tag in tags: if len(caption) + len(tag) < 193: caption = caption + '#' + tag + ' ' bot.send_photo(message.chat.id, file, caption) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /id 43369925')
def __init__(self, **kwargs): super().__init__(**kwargs) # forces reauth() to trigger if any method is called: self.last_auth = datetime.datetime.fromtimestamp(0) self.refresh_token = "" self.aapi = AppPixivAPI(**kwargs) self.papi = PixivAPI(**kwargs)
def main(): aapi = AppPixivAPI() aapi.login(username, password) illust_ids = set() for illust in get_imageUrls(aapi): illust_ids.add(illust.id) print('Images Found:'+str(len(illust_ids)))
def __init__(self): self._api_thread = threading.Thread(target=self._login) self._login_started = False self._login_done = False self._api = AppPixivAPI() # Object to login and request on # Set in self.start() (because singleton is instantiated before config) self._credentials: 'dict[str, str]' self._response: 'Json'
def importUserJSON(self): #Non-authenticated API login aapi = AppPixivAPI() self.userJSON = aapi.user_detail(self.user_ID) self.webpage = self.userJSON['profile']['webpage'] self.twitter_name = self.userJSON['profile']['twitter_account'] self.twitter_URL = self.userJSON['profile']['twitter_url'] self.pawoo_URL = self.userJSON['profile']['pawoo_url'] self.userImported = True
def login_push(self): self.ID = self.lineEdit.text() self.PW = self.lineEdit_2.text() try: api = AppPixivAPI() api.login(self.ID, self.PW) print('connected') except pixivpy3.utils.PixivError: msgbox = QMessageBox msgbox.critical(self, "Error", "Invaild ID or Password", msgbox.Ok)
def __init__(self): self.enabled = config.getboolean('Pixiv', 'enabled', fallback=False) self._refresh_token = config.get('Pixiv', 'refresh_token', fallback=None) self._log = logging.getLogger(__name__) self._pixiv = AppPixivAPI() self._pixiv.set_accept_language(config.get('Pixiv', 'language', fallback='en-US')) self._re_twitter = re.compile(r'^https?://(www.)?twitter.com/(?P<username>.+)$') if self.enabled: self._login()
def __init__(self, auto_re_login=True, **requests_kwargs): self.auto_re_login = auto_re_login self._requests_kwargs = requests_kwargs self._papi = PixivAPI(**requests_kwargs) self._aapi = AppPixivAPI(**requests_kwargs) self._has_auth = False self._last_login = None self._check_auth_lock = Lock() self._username = None self._password = None
def get_image_info(url: str): if ('pixiv' in url): api = AppPixivAPI() api.login(PIXIV_USERNAME, PIXIV_PASSWORD) if '?' in url: pixiv_id = int( dict(i.split('=') for i in url.split('?')[-1].split('&'))['illust_id']) else: pixiv_id = int(url.split('/')[-1]) return pixiv_download(pixiv_id, api) else: return {}
def __init__(self, url, username, password, proxy=None): proxies = get_proxy(proxy) requests_kwargs = { "timeout": (3, 10), } requests_kwargs.update(proxies) self.api = AppPixivAPI(**requests_kwargs) self._fetcher = PixivFetcher(**proxies) self.api.login(username, password) self._user_id = int(url.split("/")[-1]) self._dir_name = None self._total_illustrations = 0 self._fetch_user_detail()
def login(): username = request.json['username'] password = request.json['password'] try: api = AppPixivAPI() api.login(username, password) pixivclients[username] = api return jsonify({'code': 0}) except Exception as err: print(err) return jsonify({'code': -1})
def login(): username = request.json['username'] token = request.json['token'] try: api = AppPixivAPI() api.auth(refresh_token=token) pixivclients[username] = api return jsonify({'code': 0}) except Exception as err: print(err) return jsonify({'code': -1})
def send_related(message): bool_ban = SendTrackMessage(message, 'related') if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 try: split_list = message.text.split(' ') if len(split_list) > 3 or len(split_list) < 2: bot.send_message(message.chat.id, '満身創痍|使用范例: /related 43369925 5') return -1 elif len(split_list) == 3: origin_id = split_list[1] num = split_list[2] elif len(split_list) == 2: origin_id = split_list[1] num = 5 int(origin_id) num = int(num) if num <= 0: bot.send_message(message.chat.id, '満身創痍|使用范例: /related 43369925 5') else: api = AppPixivAPI() api.login("your username", "pswe") id_list = PixivRelated(origin_id, num, api) if id_list == []: bot.send_message( message.chat.id, '该图片不存在或没有相关图片|Picture does not exist or has no related illustrations' ) elif len(id_list) < 6: for i in id_list: file, title, tags = PixivDownload(i, api) caption = 'url : pixiv.net/i/' + str( i) + '\n' + 'title : ' + title + '\n' + 'tags : ' for tag in tags: if len(caption) + len(tag) < 193: caption = caption + tag + ' ' bot.send_photo(message.chat.id, file, caption) else: file_list = [] for i in id_list: temp_file, temp1, temp2 = PixivDownload(i, api) file_list.append(InputMediaPhoto(temp_file)) bot.send_media_group(message.chat.id, file_list) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /related 43369925 5')
def apiRanking(api: pixivpy3.AppPixivAPI, t: str) -> list: logger.info("尝试获取 " + t + " 排行榜信息") json_result = api.illust_ranking(mode=t) rt = [] for json_item in json_result.illusts: if json_item.type != 'illust': continue illust = json_item.id title = json_item.title count = json_item.page_count if count == 1: url = [json_item.meta_single_page.original_image_url] else: url = [i.image_urls.original for i in json_item.meta_pages] tags = [i.name for i in json_item.tags] temp = { "illust": illust, "title": title, "count": count, "tags": tags, "url": url, "suffix": url[0].split('.')[-1] } logger.debug(temp) rt.append(temp) logger.info(t + " 排行榜信息获取完成") return rt
def send_top(message): bool_ban = SendTrackMessage(message, 'ranking') if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 support_freq = ['day', 'week', 'month', 'day_male', 'day_female'] try: split_list = message.text.split(' ') if len(split_list) > 3 or len(split_list) < 2: bot.send_message(message.chat.id, '満身創痍|使用范例: /ranking day 6') return -1 elif len(split_list) == 3: frequence = split_list[1] num = split_list[2] elif len(split_list) == 2: frequence = split_list[1] num = 6 num = int(num) if frequence not in support_freq: bot.send_message(message.chat.id, '不支持的关键词,请输入day,week,month,day_male或day_female') else: api = AppPixivAPI() api.login("your username", "pswe") pixiv_id = PixivRanking(frequence, num, api) if num < 6: for i in pixiv_id: file, title, tags = PixivDownload(i, api) caption = 'url : pixiv.net/i/' + str( i) + '\n' + 'title : ' + title + '\n' + 'tags : ' for tag in tags: if len(caption) + len(tag) < 193: caption = caption + tag + ' ' bot.send_photo(message.chat.id, file, caption) else: file_list = [] for i in pixiv_id: temp_file, temp1, temp2 = PixivDownload(i, api) file_list.append(InputMediaPhoto(temp_file)) bot.send_media_group(message.chat.id, file_list) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /ranking day 6')
def send_file(message): bool_ban = SendTrackMessage(message, 'file') if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 pixiv_id = -1 try: pixiv_id = message.text.split(' ')[1] int(pixiv_id) api = AppPixivAPI() api.login("your username", "pswe") file, title, tags, artist = PixivDownloadOrigin(pixiv_id, api) if file == -1: bot.send_message(message.chat.id, '该图片不存在|Picture does not exist') else: bot.send_document(message.chat.id, file) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /file 43369925')
def __init__(self): self.__ACCESS_INTERVAL: Final[float] = 1 # sec self.__GET_ILLUST_RETRY_NUM: Final[int] = 100 self.__NEXT_ILLUST_RETRY_NUM: Final[int] = 10 self.__api: AppPixivAPI = AppPixivAPI() try: self.__api.login(os.environ["PIXIV_ID"], os.environ["PIXIV_PASSWORD"]) except PixivError as e: print(e)
def __init__(self): """ Init PixivSpider """ self.api = AppPixivAPI() self.directory = 'download' if not os.path.exists('info.json'): self.data = {'illusts': []} self.count = 0 print("Create new info.json file") else: with open('info.json', 'r') as f: self.data = json.load(f) self.count = len(self.data['illusts']) print("Load existing info.json file") print("Existed illusts count: %d" % self.count) self.illusts_names = Set() for illust in self.data['illusts']: self.illusts_names.add(illust['name'])
def __init__(self, url, username, password, proxy=None): proxies = {} if proxy is not None: proxy = normalize_proxy_string(proxy) proxies = { 'proxies': { 'http': proxy, 'https': proxy, } } requests_kwargs = { "timeout": (3, 10), } requests_kwargs.update(proxies) self.api = AppPixivAPI(**requests_kwargs) self._fetcher = PixivFetcher(**proxies) self.api.login(username, password) self._user_id = int(re.findall('id=(\d+)', url)[0]) self._dir_name = None self._total_illustrations = 0 self._fetch_user_detail()
class Pixiv(commands.Cog): def __init__(self, bot): self.bot = bot conf = config.load_config() self.api = AppPixivAPI() self.api.login(conf["pixiv_username"], conf["pixiv_password"]) @commands.command(name="Pixiv", aliases=("pixiv", "PIXIV")) async def pixiv(self, ctx, option): mode = "" if option == "推荐": mode = "day" elif option == "色图" or option == "涩图" or option == "setu": mode = "day_r18" result = self.api.illust_ranking(mode) illusts = result.illusts[:10] for illust in illusts: await ctx.send( f"{illust.title} - https://www.pixiv.net/artworks/{illust.id}") else: await ctx.send(f"未知选项:{option}")
def __init__(self, client=None, username=None, password=None, log_level=logging.WARNING): if not client and (bool(username) != bool(password)): raise AttributeError( 'If no client is given both username and password must be given' ) if client: self.api = client else: self.api = AppPixivAPI() if not client and username and password: self.api.login(username, password) self.logger = logging.getLogger('PixivDownloader') stdout = logging.StreamHandler() self.logger.addHandler(stdout) self.logger.setLevel(log_level)
class Pixiv(DummySite): def __init__(self, url, username, password, proxy=None): proxies = get_proxy(proxy) requests_kwargs = { "timeout": (3, 10), } requests_kwargs.update(proxies) self.api = AppPixivAPI(**requests_kwargs) self._fetcher = PixivFetcher(**proxies) self.api.login(username, password) self._user_id = int(url.split("/")[-1]) self._dir_name = None self._total_illustrations = 0 self._fetch_user_detail() @property def fetcher(self): return self._fetcher @property def dir_name(self): assert self._dir_name is not None return self._dir_name def _fetch_user_detail(self): assert self._user_id is not None profile = self.api.user_detail(self._user_id) user = profile['user'] self._dir_name = "-".join([ user['name'], user['account'], str(user['id']), ]) self._dir_name = normalize_filename(self._dir_name) self._total_illustrations = profile['profile']['total_illusts'] return self.dir_name def _fetch_image_list(self, ): ret = self.api.user_illusts(self._user_id) while True: for illustration in ret.illusts: yield from parse_image_urls(illustration) if ret.next_url is None: break ret = self.api.user_illusts(**self.api.parse_qs(ret.next_url)) def _fetch_single_image_url(self, illustration_id): json_result = self.api.illust_detail(illustration_id) illustration_info = json_result.illust return illustration_info.image_urls['large'] @property def tasks(self): yield from self._fetch_image_list()
def send_picture(message): bool_ban = SendTrackMessage(message, 'id') if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 pixiv_id = -1 try: pixiv_id = message.text.split(' ')[1] int(pixiv_id) api = AppPixivAPI() api.login("your username", "pswe") file, title, tags, artist = PixivDownloadOrigin(pixiv_id, api) if file == -1: bot.send_message(message.chat.id, '该图片不存在|Picture does not exist') else: caption = 'title : ' + title + '\n' + 'url : pixiv.net/i/' + pixiv_id + '\n' + 'tags : ' for tag in tags: if len(caption) + len(tag) < 193: caption = caption + tag + ' ' bot.send_photo(message.chat.id, file, caption) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /id 43369925')
def send_ugoira_to_channel(message): if int(message.chat.id) not in white_list: try: temp_text = message.chat.title + '使用ugoira命令' + ' ' + str( message.chat.id) + ' ' + message.chat.username except: temp_text = 'A Null is captured' bot.send_message('your chat_id', temp_text) bool_ban = False if int(message.chat.id) in black_list: bool_ban = True if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 pixiv_id = -1 try: pixiv_id = message.text.split(' ')[1] int(pixiv_id) api = AppPixivAPI() api.login("your username", "pswe") file, title, tags, artist, _type = PixivDownloadUgoiraZip( pixiv_id, api) if _type != 'ugoira': bot.send_message(message.chat.id, '该图片不是ugoira,请使用id命令') else: caption = 'title : ' + title + '\n' + 'url : pixiv.net/i/' + pixiv_id + '\n' + 'tags : ' for tag in tags: if len(caption) + len(tag) < 193: caption = caption + tag + ' ' bot.send_document(message.chat.id, file, caption) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /ugoira 75162826')
async def picSearch(self, ctx, title: str = ""): g_config = ConfigManager.instance().get_global_config() pixivAPI = AppPixivAPI() # pixivAPI.login(config_dict.get("Pixiv")['ID'], config_dict.get("Pixiv")['Pass']) try: pixivAPI.auth(refresh_token=g_config.get("Pixiv")["TOKEN"]) except: return await ctx.send("MAID ERROR: F**K PIXIV! REQUEST FAILED, PLEASE TRY AGAIN!") if title == "": try: result = pixivAPI.illust_ranking('day_male') except: return await ctx.send("MAID ERROR: F**K PIXIV! REQUEST FAILED, PLEASE TRY AGAIN!") elif title == "r18": try: result = pixivAPI.illust_ranking('day_male_r18') except: return await ctx.send("MAID ERROR: F**K PIXIV! REQUEST FAILED, PLEASE TRY AGAIN!") else: try: result = pixivAPI.search_illust(title, sort="popular_desc", search_target='title_and_caption') except: return await ctx.send("MAID ERROR: F**K PIXIV! REQUEST FAILED, PLEASE TRY AGAIN!") embed = nextcord.Embed(color=nextcord.Color.dark_red()) if len(result.illusts) != 0: illust = result.illusts[random.randint(0, len(result.illusts) - 1)] imagePresent = os.path.isfile(f'illust.jpg') if (imagePresent): os.remove(f'illust.jpg') pixivAPI.download(illust.image_urls.large, fname=f'illust.jpg') embed.title = illust.title embed.url = f"https://www.pixiv.net/artworks/{illust.id}" embed.set_image(url="attachment://illust.jpg") embed.set_author(name=illust.user.name, url=f"https://www.pixiv.net/users/{illust.user.id}") await ctx.send(embed=embed, file=nextcord.File(f'illust.jpg')) else: embed.title = "Image can\'t be found! 无法找到图片!" await ctx.send(embed=embed)
def main(): aapi = AppPixivAPI() # aapi.set_additional_headers({'Accept-Language':'en-US'}) aapi.set_accept_language("en-us") # zh-cn aapi.auth(refresh_token=_REFRESH_TOKEN) json_result = aapi.illust_ranking( "day", date=(datetime.now() - timedelta(days=5)).strftime("%Y-%m-%d")) print( "Printing image titles and tags with English tag translations present when available" ) for illust in json_result.illusts[:3]: print('Illustration: "' + str(illust.title) + '"\nTags: ' + str(illust.tags) + "\n")
def pixiv_render(item, base_path, debug=False): global pixiv_api if pixiv_api is None: pixiv_api = AppPixivAPI() pixiv_api.login(pixiv_username, pixiv_password) illust_id = get_illust_id(item.get_remote()) detail = pixiv_api.illust_detail(illust_id) path = (str(detail['illust']['user']['name']) + '_' + str(detail['illust']['user']['id'])) cpath(base_path + path) urls = [] if detail['illust']['page_count'] > 1: for page in detail['illust']['meta_pages']: page_url = None try: page_url = page['image_urls']['original'] except (NameError, KeyError): try: page_url = list(page['image_urls'].values())[-1] except (NameError, KeyError): pass if page_url is not None: urls.append(page_url) if len(urls) <= 0: try: urls.append( detail['illust']['meta_single_page']['original_image_url']) except (NameError, KeyError): try: urls.append(detail['illust']['image_urls']['large']) except (NameError, KeyError): pass ret = [] for url in urls: name = str(detail['illust']['title']) + '_' + str( illust_id) + os.path.basename(url) ret.append(path + '/' + name) pixiv_api.download(url, name=name, path=os.path.abspath(base_path + path)) if debug: print('.', end='', flush=True) return ret, detail
def check_log(instance, **kwargs): log = instance title = 'test' if log.nick != 'maobot' and log.command == 'PRIVMSG' and log.nick != 'maobot_php': url_pat = re.compile(r"https?://[a-zA-Z0-9\-./?@&=:~_#]+") url_list = re.findall(url_pat, log.message) for url in url_list: r = requests.get(url) content_type_encoding = r.encoding if r.encoding != 'ISO-8859-1' else None soup = BeautifulSoup(r.content, 'html.parser', from_encoding=content_type_encoding) try: title = soup.title.string Log(command='NOTICE', channel=log.channel, nick='maobot', message=title, is_irc=False).save() except (AttributeError, TypeError, HTTPError): pass # image dl nicoseiga_pat = re.compile( 'http://seiga.nicovideo.jp/seiga/[a-zA-Z]+([0-9]+)') pixiv_pat = re.compile( 'https://www.pixiv.net/member_illust.php/?\?([a-zA-Z0-9\-./?@&=:~_#]+)') twitter_pat = re.compile( 'https://twitter.com/[a-zA-Z0-9_]+/status/\d+') image_format = ["jpg", "jpeg", "gif", "png"] if twitter_pat.match(url): try: images = soup.find("div", {"class": "permalink-tweet-container"}).find("div", {"class": "AdaptiveMedia-container"}).findAll("div", {"class": "AdaptiveMedia-photoContainer"}) except AttributeError: images = soup.findAll("div", {"class": "media"}) for image in images: try: image_url = image.find('img')['src'] img = image_from_response(requests.Session().get(image_url), Image(original_url=url, related_log=log, caption=title)) img.save() Log.objects.filter(id=log.id).update(attached_image=img.thumb) except: pass elif nicoseiga_pat.match(url): seiga_login = '******' seiga_id = nicoseiga_pat.search(url).group(1) seiga_source = 'http://seiga.nicovideo.jp/image/source/%s' % seiga_id login_post = {'mail_tel': SECRET_KEYS['nicouser'], 'password': SECRET_KEYS['nicopass']} session = requests.Session() session.post(seiga_login, data=login_post) soup = BeautifulSoup(session.get(seiga_source).text, 'lxml') image_url = 'http://lohas.nicoseiga.jp%s' % soup.find( 'div', {'class': 'illust_view_big'})['data-src'] img = image_from_response(requests.Session().get(image_url), Image(original_url=url, related_log=log)) img.save() Log.objects.filter(id=log.id).update(attached_image=img.thumb) elif pixiv_pat.match(url): from pixivpy3 import AppPixivAPI from urllib.parse import parse_qs api = AppPixivAPI() api.login(SECRET_KEYS['pixiuser'], SECRET_KEYS['pixipass']) pixiv_query = pixiv_pat.search(url).group(1) pixiv_dict = parse_qs(pixiv_query) pixiv_id = pixiv_dict['illust_id'] pixiv_illust = api.illust_detail(pixiv_id, req_auth=True).illust if 'meta_pages' in pixiv_illust and len(pixiv_illust.meta_pages) != 0: image_urls = [] if 'page' in pixiv_dict: image_urls.append(pixiv_illust.meta_pages[int(pixiv_dict['page'][0])].image_urls.large) else: for i in pixiv_illust.meta_pages: image_urls.append(i.image_urls.large) else: image_urls = [pixiv_illust.image_urls.large] for image_url in image_urls: response = api.requests_call('GET', image_url, headers={'Referer': 'https://app-api.pixiv.net/'}, stream=True) img = image_from_response(response, Image(original_url=url, related_log=log, caption=pixiv_illust.title)) img.save() Log.objects.filter(id=log.id).update(attached_image=img.thumb) elif url.split(".")[-1] in image_format: img = image_from_response(requests.Session().get(url), Image(original_url=url, related_log=log)) img.save() Log.objects.filter(id=log.id).update(attached_image=img.thumb)