Exemple #1
0
    async def getsauce(self, ctx, flag, *query):
        """ Fetches the first 25 nuke codes that match this query 

            [Sorting Flags]
            -a = Popular all-time 
            -y = Popular this year
            -w = Popular this week (default)
            -m = Popular this month
            -t = Popular today
            -r = Most Recent
        """
        category = {
            "-a": [Sort.Popular, "popular all-time"],
            "-y": [Sort.PopularYear, "popular this year"],
            "-w": [Sort.PopularWeek, "popular this week"],
            "-m": [Sort.PopularMonth, "popular this month"],
            "-t": [Sort.PopularToday, "popular today"],
            "-r": [Sort.Date, "most recent"]
        }
        default = [Sort.PopularWeek, "popular this week"]
        new_query = flag  # in case flag is a query
        flag = flag if flag in category else None
        try:
            sort_by = category.get(flag, default)
            if flag == None:
                new_query = new_query + " " + " ".join(query)
            else:
                new_query = " ".join(query)
            message = await ctx.send(f'Fetching *"{new_query}"*...')
            nukes = (str(doujin.id) for doujin in Utils.search_by_query(
                new_query, sort=sort_by[0]))
            await message.edit(content=f'Here you go ({sort_by[1]}): `{", ".join(nukes)}`')
        except HTTPError:
            await message.edit(content=f"Couldn't find the sauce you're looking for. 🤷‍♂️")
Exemple #2
0
    async def random(self, ctx):
        async with ctx.typing():
            doujin = Utils.get_random_hentai()
            embed, components = self.helpers.generate_list_hentai_embed(
                doujin, 1, 1, disable_components=True)

            await ctx.send(embed=embed, components=components)
Exemple #3
0
    async def search(self, ctx, *, query):
        async with ctx.typing():
            doujins = [doujin for doujin in Utils.search_by_query(query, sort=Sort.Popular)]
            shuffle(doujins)
            curr_index = 1
            max_index = len(doujins)
            embed, components = self.helpers.generate_list_hentai_embed(doujins[curr_index-1], curr_index, max_index)

            nhentai = await ctx.send(embed=embed, components=components)
        
        try:
            while True:
                btn = await nhentai.wait_for('button', self.bot, timeout=60)
                await btn.respond(ninja_mode=True)

                if btn.custom_id == 'hentai_first': curr_index = 1
                if btn.custom_id == 'hentai_prev': curr_index -= 1
                if btn.custom_id == 'hentai_next': curr_index += 1
                if btn.custom_id == 'hentai_last': curr_index = max_index

                embed, components = self.helpers.generate_list_hentai_embed(doujins[curr_index-1], curr_index, max_index)
                await nhentai.edit(embed=embed, components=components)
        except TimeoutError:
            _, components = self.helpers.generate_list_hentai_embed(doujins[curr_index-1], curr_index, max_index, disable_components=True)
            await nhentai.edit(components=components)
        except NotFound:
            pass
Exemple #4
0
    async def _search(self, ctx: commands.Context, tags: str, sort):
        res = Utils.search_by_query(tags, sort=sort)
        if res != []:
            msg = "Choose from `1-5`;\n"
            for i, dj in enumerate(res):
                if i < 5:
                    msg += f"{i+1}: {dj.title(Format.English)}\n"
            mes: discord.Message = await ctx.send(content=msg)
        else:
            await ctx.send('No results found!')
            return

        def check(inp: discord.Message):
            return inp.author == ctx.author

        try:
            msg: discord.Message = await self.bot.wait_for('message',
                                                           check=check,
                                                           timeout=30.0)
            djid = res[int(msg.content) - 1].id
            await self.nhentai(ctx, djid)
        except (ValueError, IndexError):
            await mes.delete()
            await ctx.send("Invalid input")
        except asyncio.TimeoutError:
            await mes.delete()
Exemple #5
0
    async def random(self, ctx: Context) -> None:

        """
        Get a random hentai from NHentai.
        """

        hnt = Utils.get_random_hentai()
        embed = self.make_embed(hnt)
        await ctx.send(embed=embed)
 async def nh_search(self, ctx, *, query: str):
     """
     search keyword in NHentai
     """
     result = Utils.search_by_query(query)
     embed  = self.process_search_result(result)
     embed.set_footer(text="Search report from Speedwagon Foundation")  
     embed.timestamp = datetime.datetime.utcnow()
     msg = await ctx.send(embed=embed)
Exemple #7
0
    async def randomnuke(self, ctx, items: int):
        """ Get random nuke codes for shits and giggles. (Max limit is configurable) """
        message = await ctx.send(f"Gathering [{items}] nuke code/s...")

        if 1 <= items <= self.config["max_limit"]:
            nukes = (str(Utils.get_random_id()) for i in range(items))
            await message.edit(content=f'Here you go: `{", ".join(nukes)}`')
        else:
            await message.edit(content=f'Cannot generate [{items}] amount of nuke codes.')
Exemple #8
0
async def nhr(message, *tags):
    if not tags:
        random = str(Utils.get_random_id())
        base_url = 'https://nhentai.net/g/'
        final_url = base_url + random + "/"
        await message.channel.send(final_url)
    else:
        print("Entered else statement")
        query_tags = ""
        fTags = ""
        n = 0
        language = "language:english"
        commandHelp = ""
        for tag in tags:
            if (tag == "-help") or (tag == "-h") or (tag
                                                     == "h") or (tag
                                                                 == "help"):
                commandHelp = "Use quaisquer combinação de tags. Ex: *%snhr yuri pantyhose*\nTambém pode usar - para remover uma tag. Ex: *%snhr glasses -netorare*" % (
                    prefix, prefix)
                await message.channel.send(commandHelp)
                break
            #enables multiple language support (to be defined in if statement)
            # if tag == "translated" or tag == "english":
            #     language = "language:" + tag
            # else:
            query_tags += tag + " "
            if query_tags != "":
                fTags = "tag:" + query_tags
        query = fTags + language
        doujins = Utils.search_by_query(query, sort=Sort.PopularToday)
        selected = randint(0, len(doujins))

        for doujin in doujins:
            if (commandHelp != ""):
                break
            if (n == selected):
                base_url = 'https://nhentai.net/g/'
                final_url = base_url + str(doujin.id) + "/"
                print(doujin.title(Format.Pretty))
                print(final_url)
                await message.channel.send(final_url)
            n += 1
Exemple #9
0
 def test_get_homepage(self):
     homepage = Utils.get_homepage()
     for doujin in homepage:
         self.assertIsNotNone(doujin.json, msg="Result should not be 'None'.")
         self.assertTrue(doujin.id, msg="ValueError: ID")
         self.assertTrue(doujin.title(), msg="ValueError: Title")
         self.assertTrue(doujin.media_id, msg="ValueError: MediaID")
         self.assertTrue(doujin.upload_date, msg="ValueError: UploadDate")
         self.assertTrue(doujin.cover, msg="ValueError: Cover")
         self.assertTrue(doujin.thumbnail, msg="ValueError: Thumbnail")
         self.assertTrue(doujin.image_urls, msg="ValueError: ImageURLs")
         self.assertTrue(doujin.num_pages, msg="ValueError: NumberOfPages")     
Exemple #10
0
 def test_search_all_by_query(self):
     popular_3d = Utils.search_all_by_query(query="tag:3d", sort=Sort.PopularWeek)
     for doujin in popular_3d:
         self.assertIsNotNone(doujin.json, msg="Result should not be 'None'.")
         self.assertTrue(doujin.id, msg="ValueError: ID")
         self.assertTrue(doujin.title(), msg="ValueError: Title")
         self.assertTrue(doujin.media_id, msg="ValueError: MediaID")
         self.assertTrue(doujin.upload_date, msg="ValueError: UploadDate")
         self.assertTrue(doujin.cover, msg="ValueError: Cover")
         self.assertTrue(doujin.thumbnail, msg="ValueError: Thumbnail")
         self.assertTrue(doujin.image_urls, msg="ValueError: ImageURLs")
         self.assertTrue(doujin.num_pages, msg="ValueError: NumberOfPages")               
Exemple #11
0
 async def rnd(self, ctx: commands.Context):
     """Random one"""
     doujin = Hentai(Utils.get_random_id())
     embed_list = []
     for i in doujin.image_urls:
         embed = Embed.default(ctx)
         embed.title = doujin.title(Format.Pretty)
         embed.set_image(url=i)
         embed_list.append(embed)
     await menus.MenuPages(
         source=EmbedListMenu(embed_list),
         clear_reactions_after=True,
     ).start(ctx=ctx, wait=False)
Exemple #12
0
    async def search(self, ctx: Context, *, query: str):
        """
        TODO: Make this function work
        :param ctx:
        :param query:
        :return:
        """
        result = Utils.search_by_query(query)
        embed  = self.process_search_result(result)
        msg = await ctx.send(embed=embed)

        def check(msg: discord.Message) -> bool:
            """
            Check if the function is
            :param msg:
            :return:
                        """
            if msg.author != ctx.author: return False
            content = msg.content
            try:
                n = int(content)
                if n < 1 or n > 10: return False

            except Exception:
                return content == 'x' or False
            else:
                return True

        try:
            response = await self.bot.wait_for('message',
                                               check=check,
                                               timeout=30)
        except asyncio.TimeoutError:
            await ctx.send(embed=WarningEmbed("OOPS! timeout"),
                           delete_after=10
            )
        else:
            await msg.delete()
            content = response.content
            if content == 'x':
                await msg.delete()
                await response.delete()
                return
            n = int(content)
            await response.delete()
            await ctx.send(
                embed=self.make_embed(result[n-1])
            )
Exemple #13
0
async def nh(menu):
    id = menu.extraProcVars['id']
    ctx = menu.extraProcVars['ctx']
    # No ID? Send random
    if id is None:
        await ctx.send('No ID passed, getting random doujin...')
        d = Utils.get_random_hentai()
    # ID not digits
    elif not id.isdigit():
        await ctx.send(
            'Invalid ID\nIDs are usually 6 digit numbers, although there are some 5 digin and even shorter or longer IDs\nIf you don\'t have an ID just don\'t write one and we will send you a random doujin or use the nhs command to search or nhh command to view the current home page'
        )
    # Does Doujin exist?
    elif Hentai.exists(id):
        d = Hentai(id)
    else:
        await ctx.send(
            f'No Doujin with id: {id} was found\n\nIf you don\'t have an ID just don\'t write one and we will send you a random doujin or use the nhs command to search or nhh command to view the current home page'
        )

    return d
Exemple #14
0
async def _(event):
    if event.fwd_from:
        return
    await event.edit("`Searching for doujin...`")
    input_str = event.pattern_match.group(1)
    code = input_str
    if "nhentai" in input_str:
        link_regex = r"(?:https?://)?(?:www\.)?nhentai\.net/g/(\d+)"
        match = re.match(link_regex, input_str)
        code = match.group(1)
    if input_str == "random":
        code = Utils.get_random_id()
    try:
        doujin = Hentai(code)
    except BaseException as n_e:
        if "404" in str(n_e):
            return await event.edit(f"No doujin found for `{code}`")
        return await event.edit(f"**ERROR :** `{n_e}`")
    msg = ""
    imgs = ""
    for url in doujin.image_urls:
        imgs += f"<img src='{url}'/>"
    imgs = f"&#8205; {imgs}"
    title = doujin.title()
    graph_link = post_to_telegraph(title, imgs)
    msg += f"[{title}]({graph_link})"
    msg += f"\n**Source :**\n[{code}]({doujin.url})"
    if doujin.parody:
        msg += "\n**Parodies :**"
        parodies = []
        for parody in doujin.parody:
            parodies.append("#" +
                            parody.name.replace(" ", "_").replace("-", "_"))
        msg += "\n" + " ".join(natsorted(parodies))
    if doujin.character:
        msg += "\n**Characters :**"
        charas = []
        for chara in doujin.character:
            charas.append("#" + chara.name.replace(" ", "_").replace("-", "_"))
        msg += "\n" + " ".join(natsorted(charas))
    if doujin.tag:
        msg += "\n**Tags :**"
        tags = []
        for tag in doujin.tag:
            tags.append("#" + tag.name.replace(" ", "_").replace("-", "_"))
        msg += "\n" + " ".join(natsorted(tags))
    if doujin.artist:
        msg += "\n**Artists :**"
        artists = []
        for artist in doujin.artist:
            artists.append("#" +
                           artist.name.replace(" ", "_").replace("-", "_"))
        msg += "\n" + " ".join(natsorted(artists))
    if doujin.language:
        msg += "\n**Languages :**"
        languages = []
        for language in doujin.language:
            languages.append("#" +
                             language.name.replace(" ", "_").replace("-", "_"))
        msg += "\n" + " ".join(natsorted(languages))
    if doujin.category:
        msg += "\n**Categories :**"
        categories = []
        for category in doujin.category:
            categories.append(
                "#" + category.name.replace(" ", "_").replace("-", "_"))
        msg += "\n" + " ".join(natsorted(categories))
    msg += f"\n**Pages :**\n{doujin.num_pages}"
    await event.edit(msg, link_preview=True)
Exemple #15
0
 def test_random_hentai(self):
     print("Setting make_request flag to 'False'")
     random_hentai = Utils.get_random_hentai(make_request=False)
     response = requests.get(random_hentai.url)
     self.assertTrue(response.ok, msg=f"Failing ID: {random_hentai.id}. Failing URL: {response.url}")
Exemple #16
0
 async def random(self, ctx: commands.Context):
     '''finds random doujin'''
     await self.nhentai(ctx, Utils.get_random_id())
 async def nh_random(self, ctx):
     """Ger a random manga from NHentai"""
     hnt = Utils.get_random_hentai()
     embed = self.make_embed(hnt)
     await ctx.send(embed=embed)
Exemple #18
0
 async def randomsauce(self, ctx):
     """ Get a random sauce for shits and giggles """
     await ctx.send("Getting a random sauce...")
     await self.sauce(ctx, nuke_code=str(Utils.get_random_id()))
Exemple #19
0
 def test_random_id(self):
     random_id = Utils.get_random_id()
     response = requests.get(urljoin(Hentai._URL, str(random_id)))
     self.assertTrue(
         response.ok,
         msg=f"Failing ID: {random_id}. Failing URL: {response.url}")
Exemple #20
0
 async def random_id(self, ctx):
     await self.lookup_id(ctx, id=Utils.get_random_id(make_request=True))
Exemple #21
0
 def test_random_hentai(self):
     random_hentai = Utils.get_random_hentai()
     response = requests.get(random_hentai.url)
     self.assertTrue(
         response.ok,
         msg=f"Failing ID: {random_hentai.id}. Failing URL: {response.url}")
Exemple #22
0
 def test_download_queue(self):
     Utils.download([self.tiny_evil.id])
     self.assertTrue(self.tiny_evil_dir.is_dir())
Exemple #23
0
 def test_random_id(self):
     print("Setting make_request flag to 'False'")
     random_id = Utils.get_random_id(make_request=False)
     response = requests.get(urljoin(Hentai._URL, str(random_id)))
     self.assertTrue(response.ok, msg=f"Failing ID: {random_id}. Failing URL: {response.url}")