コード例 #1
0
def searchby_id(cmd):
	id = int(cmd.replace('nh', '').replace('search', '').strip())
	if len(str(id)) > 6:
		print(f'{id} is not a manga id! So... Zero Two.')
		id = 281415
	manga = Hentai(id)
	Hentai.exists(manga.id)
	print(f'#{manga.id} :: {manga.title(Format.Pretty)} exists!')
コード例 #2
0
 async def nhentai(self,
                   ctx: commands.Context,
                   djid=None,
                   *,
                   extra: str = ''):
     '''finds doujins on nhentai by id'''
     if ctx.invoked_subcommand is not None:
         return
     if djid is None:
         await ctx.send_help(ctx.command)
         return
     if not Hentai.exists(djid):
         return await self.search(ctx, tags=f'{djid} {extra}')
     result = Hentai(djid)
     tags = [_.name for _ in result.tag]
     e = discord.Embed(title=result.title(Format.Pretty),
                       description=f'#{result.id}',
                       url=result.url,
                       color=int(djid))
     e.set_image(url=result.cover)
     e.set_footer(text=result.upload_date)
     e.add_field(name="Tags", value=', '.join(tags))
     artists = ', '.join([_.name for _ in result.artist
                          ]) if result.artist != [] else 'None'
     e.add_field(name="Artist(s)", value=artists)
     await ctx.send(embed=e)
コード例 #3
0
ファイル: aigis.py プロジェクト: eduardo-neves/aigis.py
async def nh(message, sauce):
    try:
        doujin = Hentai(sauce)
        if (Hentai.exists(doujin.id) == True):
            base_url = 'https://nhentai.net/g/'
            final_url = base_url + sauce + "/"
            await message.channel.send(final_url)
    except:
        await message.channel.send("Esse sauce não existe parça.")
コード例 #4
0
def getby_id(cmd):
	id = int(cmd.replace('nh', '').replace('get', '').strip())
	if len(str(id)) > 6:
		print(f'{id} is not a manga id! So... Zero Two.')
		id = 281415
	manga = Hentai(id)
	Hentai.exists(manga.id)
	print(f'#{manga.id} :: {manga.title(Format.Pretty)}')
	
	if id != 281415:
		if confirm('proceed download'):
			print('Starting download...\n')
			manga.download(progressbar=True)
			print(f'Downloading {manga.title(Format.Pretty)} Success!\n')
		else:
			print(f'Downloading {manga.title(Format.Pretty)} aborted.\n')
	else:
		manga.download(progressbar=True)
		print('Enjoy.')
コード例 #5
0
ファイル: test_hentai.py プロジェクト: mousesama/hentai
 def test_exists(self):
     self.assertTrue(Hentai.exists(self.test_response1.id), msg=str(self.test_response1))
     self.assertTrue(Hentai.exists(self.test_response2.id), msg=str(self.test_response2))
     self.assertTrue(Hentai.exists(self.test_response3.id), msg=str(self.test_response3))
     self.assertTrue(Hentai.exists(self.test_response4.id), msg=str(self.test_response4))
     self.assertFalse(Hentai.exists(sys.maxsize), msg=f"Should have failed:{sys.maxsize}")
     self.assertFalse(Hentai.exists(-69), msg=f"Should have failed:{-69}")    
コード例 #6
0
def read_manga():
    code = request.args.get('code')
    if code:
        print(f"READER: {code}")

        if (Hentai.exists(code)):
            doujin = Hentai(code)
            return render_template('includes/reader.html',
                                   img_urls=enumerate(doujin.image_urls))
        else:
            return render_template('includes/reader.html', img_urls=[])

    return redirect('/')
コード例 #7
0
ファイル: dev.py プロジェクト: fossabot/hentai
def update_ids(ctx, delay, delete_duplicates):
    global id
    filename = ctx.obj['FILENAME']
    is_file = os.path.isfile(filename)

    if is_file is False:
        click.secho(
            "Warning: file not found. Creating a new CSV file as replacement now.",
            fg='yellow')
        Path(filename).touch()

    if delete_duplicates:
        tmp_filename = './data/tmp.csv'
        with open(filename, mode='r') as in_file, open(tmp_filename,
                                                       mode='w') as out_file:
            unique_ids = set()
            for line in in_file:
                if line in unique_ids:
                    click.secho(f"Duplicate detected: id={line}", fg='yellow')
                    continue
                unique_ids.add(line)
                out_file.write(line)
        Path(tmp_filename).replace(filename)
        return

    with open(filename, mode='r', encoding='cp932') as file_handler:
        reader = csv.reader(file_handler)
        id = [int(row[0]) for row in reader][-1] if is_file is True else 0

    with open(filename,
              mode='a+',
              newline='',
              encoding='cp932',
              errors='replace') as file_handler:
        for i in range(id + 1, 400_000):
            try:
                if Hentai.exists(i):
                    writer = csv.writer(file_handler)
                    click.echo(
                        f"{str(i).zfill(6)}: Adding id={i} to file . . .")
                    writer.writerow([i])
                    time.sleep(delay)
                else:
                    click.echo(f"{str(i).zfill(6)}: ", nl=False)
                    click.secho("Does Not Exist", fg='yellow')
            except Exception:
                click.secho("The read operation timed out.", fg='red')
コード例 #8
0
 async def read(self, ctx: commands.Context, digits):
     """Read doujins."""
     if not digits.isdigit():
         return await ctx.send("Only digits allowed.")
     if not Hentai.exists(digits):
         return await ctx.send("Doesn't exist.")
     doujin = Hentai(digits)
     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)
コード例 #9
0
ファイル: nsfw.py プロジェクト: maoouu/Mashiro.py
    async def read(self, ctx, nuke_code):
        """ Read doujin here on Discord. """
        message = await ctx.send("Loading sauce...")

        if Hentai.exists(nuke_code):
            doujin = Hentai(nuke_code)
            buttons = ("⏪", "◀", "⏹", "▶", "⏩")
            current = 0
            images = tuple(doujin.image_urls)
            max_pages = doujin.num_pages
            await message.edit(content=f'Opening *{doujin.title(Format.Pretty)}*...')
            view = await ctx.send(images[current])
            page_info = await ctx.send(f'Page: {str(current + 1)}/{str(max_pages)}')

            for button in buttons:
                await view.add_reaction(button)

            while True:
                try:
                    reaction, user = await self.bot.wait_for('reaction_add', timeout=90.0, check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons)
                except asyncio.TimeoutError:
                    await view.edit(content="**Doujin has timed out.**")
                    del images
                    await page_info.delete()
                    break
                else:
                    previous_page = current
                    switcher = {
                        "⏪": 0,
                        "◀": current - 1 if current > 0 else current,
                        "⏹": -1,
                        "▶": current + 1 if current < max_pages - 1 else current,
                        "⏩": max_pages - 1
                    }
                    current = switcher[reaction.emoji]
                    if current != previous_page:
                        if current == -1:
                            await view.edit(content="**Doujin has been closed.**")
                            del images
                            await page_info.delete()
                            break
                        else:
                            await view.edit(content=images[current])
                            await page_info.edit(content=f'Page: {str(current + 1)}/{str(max_pages)}')
        else:
            await message.edit(content="The sauce you want to read does not exist. 🤷‍♂️")
コード例 #10
0
 async def lookup(self, ctx: commands.Context, doujin):
     """ Info about a doujin."""
     if not doujin.isdigit():
         return await ctx.send("Only digits allowed.")
     if not Hentai.exists(doujin):
         return await ctx.send("Doesn't exist.")
     doujin = Hentai(doujin)
     embed = Embed.default(ctx)
     embed.title = doujin.title(Format.Pretty)
     embed.add_field(name="Holy Digits", value=doujin.id, inline=True)
     embed.add_field(name="Languages",
                     value=Tag.get(doujin.language, "name"),
                     inline=True)
     embed.add_field(name="Uploaded", value=doujin.upload_date, inline=True)
     embed.add_field(name="Number of times liked",
                     value=doujin.num_favorites,
                     inline=True)
     embed.add_field(name="Tags", value=Tag.get(doujin.tag, "name"))
     embed.add_field(name="Number of pages", value=doujin.num_pages)
     embed.set_thumbnail(url=doujin.thumbnail)
     await ctx.send(embed=embed)
コード例 #11
0
ファイル: nhentai.py プロジェクト: Vawlpe/vawBOT
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
コード例 #12
0
 async def lookup_id(self, ctx, id: int):
     if not Hentai.exists(id):
         await ctx.send("Error: Invalid ID.")
     else:
         doujin = Hentai(id)
         embed = discord.Embed(
             title=doujin.title(Format.Pretty),
             description=f"🌍 {', '.join(Tag.get_names(doujin.language))}",
             url=doujin.url,
             color=discord.Color.red())
         embed.add_field(name="Author", value=Tag.get_names(doujin.artist))
         embed.add_field(name="Favorites",
                         value=f"❤ {doujin.num_favorites}")
         embed.add_field(name="Pages", value=f"📕 {doujin.num_pages}")
         embed.set_thumbnail(url=doujin.thumbnail)
         embed.set_footer(
             text=f"Tags: {', '.join(Tag.get_names(doujin.tag))}")
         await self.client.change_presence(
             status=discord.Status.online,
             activity=discord.Game(
                 f"Now reading {doujin.title(Format.Pretty)}🥰"))
         await ctx.send(embed=embed)
コード例 #13
0
def nuke_codes():
    if request.method == 'POST':
        data = request.get_json()
        code = data['code']
        print(data)
        if (Hentai.exists(code)):
            doujin = Hentai(code)

            print(f"\n#{code} : success")
            print(f"title : {doujin.title()}")
            print(f"tags : {[tag.name for tag in doujin.tag]}")
            print(f"poster url : {doujin.image_urls[0]}\n")

            return {
                'id':
                doujin.id,
                'title_release':
                doujin.title(),
                'title_pretty':
                doujin.title(Format.Pretty),
                'tags': [tag.name for tag in doujin.tag],
                'poster_link':
                doujin.image_urls[0],
                # 'poster_blob' : poster_blob,
                'artist': [{
                    'name': artist.name,
                    'url': artist.url,
                    'count': artist.count
                } for artist in doujin.artist],
                'languages': [lang.name for lang in doujin.language],
                'categories': [cat.name for cat in doujin.category],
                'pages':
                doujin.num_pages,
                'uploaded':
                doujin.upload_date
            }
        else:
            return None
    return None
コード例 #14
0
ファイル: dumbooruamirite.py プロジェクト: EggY0lk/kiyobot
 async def nhentai(self, ctx: commands.Context, djid: int = None):
     '''finds doujins on nhentai by id'''
     if ctx.invoked_subcommand is not None:
         return
     if djid is None:
         await ctx.send_help(ctx.command)
         return
     if not Hentai.exists(djid):
         await ctx.send(content="Doujin does not exist!")
         return
     result = Hentai(djid)
     tags = [_.name for _ in result.tag]
     e = discord.Embed(title=result.title(Format.Pretty),
                       description=f'#{result.id}',
                       url=result.url,
                       color=0x177013)
     e.set_image(url=result.cover)
     e.set_footer(text=result.upload_date)
     e.add_field(name="Tags", value=', '.join(tags))
     e.add_field(name="Artist(s)",
                 value=', '.join([_.name for _ in result.artist]))
     await ctx.send(embed=e)
コード例 #15
0
    async def read_id(self, ctx, id: int):
        if not Hentai.exists(id):
            await ctx.send("Error: Invalid ID.")
        else:
            doujin = Hentai(id)
            reactions = {
                'prev': Emoji[':arrow_left:'],
                'next': Emoji[':arrow_right:']
            }

            embed = discord.Embed(title=doujin.title(Format.Pretty),
                                  description=f"Page 1 of {doujin.num_pages}",
                                  color=discord.Color.red())
            embed.set_image(url=doujin.cover)

            # TODO: implement emoji reaction event handler for pagination
            message = await ctx.send(embed=embed)
            self.reader_id = message.id
            print(type(message))
            print(self.reader_id)

            for emoji in reactions.values():
                await message.add_reaction(emoji)
コード例 #16
0
ファイル: nsfw.py プロジェクト: maoouu/Mashiro.py
    async def sauce(self, ctx, nuke_code):
        """ What's behind that nuke code? """
        message = await ctx.send("Extracting sauce from nuke code... 👨‍💻")

        if Hentai.exists(nuke_code):
            doujin = Hentai(nuke_code)
            english = doujin.title()
            japanese = doujin.title(Format.Japanese)
            pages = str(doujin.num_pages)
            hentai_id = str(doujin.id)
            link = "||" + doujin.url + "||"
            tag = (getattr(i, 'name') for i in doujin.tag)
            content_list = (
                f'**Hentai ID**: {hentai_id}',
                f'**Thumbnail**: {doujin.thumbnail}',
                f'** English Title**: {english if english else "none"}',
                f'**Japanese Title**: {japanese if japanese else "none"}',
                f'**Pages**: {pages}',
                f'**Tags**: {", ".join(tag)}',
                f'**Link**: {link}'
            )
            await message.edit(content="\n".join(content_list))
        else:
            await message.edit(content="The sauce you are looking for does not exist. 🤷‍♂️")
コード例 #17
0
 def test_exists(self):
     self.assertTrue(Hentai.exists(self.test_response.id), msg=str(self.test_response))
     self.assertTrue(Hentai.exists(self.test_response.id, make_request=False), msg=f"{str(self.test_response)}: make_request=False")
     self.assertFalse(Hentai.exists(sys.maxsize), msg=f"Should have failed:{sys.maxsize}")
     self.assertFalse(Hentai.exists(-69), msg=f"Should have failed:{-69}")    
コード例 #18
0
def sauce(update: Update, context: CallbackContext) -> None:
    """
    Fetch the doujin for all the sauces given by user, make telegraph article and send it to user for easy reading
    :param update: object representing the incoming update.
    :param context: object containing data about the command call.
    """
    # check if any args were given
    if not context.args:
        update.effective_message.reply_text(
            "Please give some codes to fetch, this cat can't read your mind..."
        )
        return

    # check if exception for sauce is added in current chat
    exception = update.effective_chat.id in get_command_exception_chats(
        "sauce")

    # iterate over each given sauce and fetch the doujin
    for digits in context.args:
        try:
            code = int(digits)
        except ValueError:
            update.effective_message.reply_markdown(
                f"If you don't know that sauce codes must be only digits, you shouldn't be using this command. "
                f"`{digits}` is not a sauce, just a sign of your ignorance.")
            continue

        # check if doujin exists
        if not Hentai.exists(code):
            update.effective_message.reply_markdown(
                f"Doujin for `{code}` doesn't exist, Donald... Please don't use your nuclear launch codes here 😿"
            )
            continue

        # Fetch doujin data
        doujin = Hentai(code)

        # make dict with data to be displayed for the doujin
        data = {
            "Title":
            f'<a href="{doujin.url}">{doujin.title(Format.Pretty)}</a>',
            "Tags": _generate_anchor_tags(doujin.tag),
            "Characters": _generate_anchor_tags(doujin.character),
            "Parodies": _generate_anchor_tags(doujin.parody),
            "Artists": _generate_anchor_tags(doujin.artist),
            "Groups": _generate_anchor_tags(doujin.group),
            "Languages": _generate_anchor_tags(doujin.language),
            "Categories": _generate_anchor_tags(doujin.category),
        }

        # add details to the reply to be sent to the user
        text_blob = "\n\n".join(f"{key}\n{value}"
                                for key, value in data.items())

        # button with nhentai link
        markup = InlineKeyboardMarkup.from_button(
            InlineKeyboardButton(text="Link to nHentai", url=doujin.url))

        # send message
        if exception:
            update.message.reply_photo(
                photo=doujin.image_urls[0],
                caption=text_blob,
                parse_mode=ParseMode.HTML,
                reply_markup=markup,
            )
        else:
            context.bot.send_photo(
                chat_id=update.effective_user.id,
                photo=doujin.image_urls[0],
                caption=text_blob,
                parse_mode=ParseMode.HTML,
                reply_markup=markup,
            )

    # if called from a chat without exception in it, then send him a reminder to check it
    if not exception and update.effective_chat.type != "private":
        update.message.reply_text(
            "Let's enjoy this together, without anybody else distracting us...",
            reply_markup=InlineKeyboardMarkup.from_button(
                InlineKeyboardButton(
                    text="Go to Private Chat",
                    url=context.bot.link,
                )),
        )