Beispiel #1
0
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
Beispiel #2
0
 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)
Beispiel #3
0
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")
Beispiel #4
0
def main():
    sni = False
    if not sni:
        api = AppPixivAPI()
    else:
        api = ByPassSniApi()  # Same as AppPixivAPI, but bypass the GFW
        api.require_appapi_hosts()
    api.auth(refresh_token=_REFRESH_TOKEN)

    # get rankings
    json_result = api.illust_ranking("day", date="2019-01-01")

    directory = "illusts"
    if not os.path.exists(directory):
        os.makedirs(directory)

    # download top3 day rankings to 'illusts' dir
    for idx, illust in enumerate(json_result.illusts[:4]):
        image_url = illust.meta_single_page.get("original_image_url",
                                                illust.image_urls.large)
        print("%s: %s" % (illust.title, image_url))

        # try four args in MR#102
        if idx == 0:
            api.download(image_url, path=directory, name=None)
        elif idx == 1:
            url_basename = os.path.basename(image_url)
            extension = os.path.splitext(url_basename)[1]
            name = "illust_id_%d_%s%s" % (illust.id, illust.title, extension)
            api.download(image_url, path=directory, name=name)
        elif idx == 2:
            api.download(image_url,
                         path=directory,
                         fname="illust_%s.jpg" % (illust.id))
        else:
            # path will not work due to fname is a handler
            api.download(
                image_url,
                path="/foo/bar",
                fname=open("%s/illust_%s.jpg" % (directory, illust.id), "wb"),
            )
Beispiel #5
0
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}")
Beispiel #6
0
class PixivSpider:
    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 login(self):
        """
        Login pixiv.net
        """
        with open('login.json') as f:
            login = json.load(f)
            self.api.login(login["username"], login["password"])
            print("Login pixiv.net with user %s.", login["username"])

    def exit(self):
        """
        Stop spider and print logs
        """
        with open('info.json', 'w') as f:
            json.dump(self.data, f, indent=2)
        print("Finish! Total downloaded illusts number: %d" % self.count)

    def create_download_folder(self):
        """
        Setup image download directory
        """
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

    def download_illusts(self, illusts=None):
        """
        Download illusts
        """
        for illust in illusts:
            image_url = illust.meta_single_page.get('original_image_url',
                                                    illust.image_urls.large)
            print(u"👀  Found illust: %s (%s)" % (illust.title, image_url))
            url_basename = os.path.basename(image_url)
            extension = os.path.splitext(url_basename)[1]
            name = "%d_%s%s" % (illust.id, illust.title, extension)
            name = name.replace('/', ':')
            if name not in self.illusts_names:
                self.count += 1
                self.data['illusts'].append({
                    'id': self.count,
                    'name': name,
                    'illust_id': illust.id,
                    'illustrator_id': illust.user.id,
                    'source_url': image_url
                })
                self.illusts_names.add(name)
                name = "%d_" % self.count + name
                try:
                    self.api.download(image_url,
                                      path=self.directory,
                                      name=name)
                except PixivError:
                    print(u"😢  PixivError!!! Skip this illust")
                    continue
                print(u"✅  Download illust: %s (%s)" %
                      (illust.title, image_url))
            else:
                print(u"✨  Already download: %s: %s" %
                      (illust.title, image_url))

    def get_user_ids_from_illusts(self, illusts):
        """
        Get user ids by illusts
        """
        user_ids = []
        for illust in illusts:
            user_ids.append(illust.user.id)
        return user_ids

    def get_top_ranking_illusts(self,
                                count=DEFAULT_DOWNLOAD_TOP_RANKING_COUNT,
                                ranking_type=RankingType.DAY,
                                date=datetime.today().strftime("%Y-%m-%d"),
                                download=False):
        """
        Get top ranking illusts
        :count: the number of illusts that we want to download
        :ranking_type: ranking type
        :date: date
        :download: download flag
        """
        json_result = self.api.illust_ranking(ranking_type, date=date)
        illusts = self.get_illusts_from_all_pages(json_result,
                                                  json_result.illusts, count,
                                                  download)
        return illusts[:count]

    def get_recommended_illusts(self,
                                count=DEFAULT_DOWNLOAD_RECOMMENDED_COUNT,
                                content_type=ContentType.ILLUST,
                                download=False):
        """
        Get recommended illusts
        :count: the number of illusts that we want to download
        :content_type: content type
        :download: download flag
        """
        json_result = self.api.illust_recommended(content_type)
        illusts = self.get_illusts_from_all_pages(json_result,
                                                  json_result.illusts, count,
                                                  download)
        return illusts[:count]

    def get_illusts_by_user_ids(self,
                                user_ids,
                                count=DEFAULT_DOWNLOAD_EACH_USER_COUNT,
                                content_type=ContentType.ILLUST,
                                download=False):
        """
        Get illusts by user id
        """
        ret = {}
        for user_id in user_ids:
            json_result = self.api.user_illusts(user_id=user_id,
                                                type=content_type)
            illusts = self.get_illusts_from_all_pages(json_result,
                                                      json_result.illusts,
                                                      count, download)
            ret[user_id] = illusts[:count]
        return ret

    def get_illusts_from_all_pages(self,
                                   json_result,
                                   illusts,
                                   count,
                                   download=False):
        """
        Get illusts from all pages
        """
        while len(json_result) != 0 and len(illusts) < count:
            next_qs = self.api.parse_qs(json_result.next_url)
            if next_qs is None:
                break
            try:
                json_result = self.api.illust_ranking(**next_qs)
            except TypeError:
                break
            illusts += json_result.illusts

        if download:
            count = min(count, len(illusts))
            self.download_illusts(illusts=illusts[:count])

        return illusts