Exemple #1
0
	async def getimage(self, ctx, *, image):
		"""Tests downloading - owner only"""
		# Only allow owner to modify the limits
		if not await Utils.is_owner_reply(ctx): return
		
		mess = await Message.Embed(title="Test", description="Downloading file...").send(ctx)
		file_path = await GetImage.download(image)
		mess = await Message.Embed(title="Test", description="Uploading file...").edit(ctx, mess)
		await Message.EmbedText(title="Image", file=file_path).edit(ctx, mess)
		GetImage.remove(file_path)
Exemple #2
0
    async def jpeg(self, ctx, *, url=None):
        """MOAR JPEG!  Accepts a url - or picks the first attachment."""
        if not self.canDisplay(ctx.guild):
            return
        if url == None and len(ctx.message.attachments) == 0:
            await ctx.send("Usage: `{}jpeg [url or attachment]`".format(
                ctx.prefix))
            return

        if url == None:
            url = ctx.message.attachments[0].url

        # Let's check if the "url" is actually a user
        test_user = DisplayName.memberForName(url, ctx.guild)
        if test_user:
            # Got a user!
            url = test_user.avatar_url if len(
                test_user.avatar_url) else test_user.default_avatar_url
            url = url.split("?size=")[0]

        message = await Message.Embed(description="Downloading...",
                                      color=ctx.author).send(ctx)

        path = await GetImage.download(url)
        if not path:
            await Message.Embed(
                title="An error occurred!",
                description=
                "I guess I couldn't jpeg that one...  Make sure you're passing a valid url or attachment."
            ).edit(ctx, message)
            return

        message = await Message.Embed(description="Jpegifying..."
                                      ).edit(ctx, message)
        # JPEEEEEEEEGGGGG
        if not self._jpeg(path):
            await Message.Embed(
                title="An error occurred!",
                description=
                "I couldn't jpegify that image...  Make sure you're pointing me to a valid image file."
            ).edit(ctx, message)
            if os.path.exists(path):
                GetImage.remove(path)
            return

        message = await Message.Embed(description="Uploading..."
                                      ).edit(ctx, message)
        message = await Message.Embed(file=path,
                                      title="Moar Jpeg!").edit(ctx, message)
        GetImage.remove(path)
Exemple #3
0
	async def print(self, ctx, *, url = None):
		"""DOT MATRIX.  Accepts a url - or picks the first attachment."""
		if not self.canDisplay(ctx.guild):
			return
		if url == None and len(ctx.message.attachments) == 0:
			await ctx.send("Usage: `{}print [url or attachment]`".format(ctx.prefix))
			return

		if url == None:
			url = ctx.message.attachments[0].url

		# Let's check if the "url" is actually a user
		test_user = DisplayName.memberForName(url, ctx.guild)
		if test_user:
			# Got a user!
			url = test_user.avatar_url
			if not len(url):
				url = test_user.default_avatar_url
			url = url.split("?size=")[0]

		message = await ctx.send("Downloading...")

		path = await GetImage.download(url)
		if not path:
			await message.edit(content="I guess I couldn't print that one...  Make sure you're passing a valid url or attachment.")
			return

		# Prant that shaz
		final = self._ascii(path)
		if os.path.exists(path):
			GetImage.remove(path)
		if not final:
			await message.edit(content="I couldn't print that image...  Make sure you're pointing me to a valid image file.")
			return
		if len(final) > 2000:
			# Too many bigs
			await message.edit(content="Whoops!  I ran out of ink - maybe try a different image.")
			return

		print_sounds = [ "ZZzzzzzt", "Bzzt", "Vvvvrrrr", "Chhhaakkakaka", "Errrttt", "Kkkkkkkktttt", "Eeehhhnnkkk" ]

		msg = "Printing..."
		await message.edit(content=msg)
		for i in range(5):
			await asyncio.sleep(1)
			msg += " " + random.choice(print_sounds) + "..."
			await message.edit(content=msg)

		await asyncio.sleep(1)
		await message.edit(content=final)
    async def poke(self, ctx, *, url=None):
        """Pokes the passed url/user/uploaded image."""

        if not self.canDisplay(ctx.guild):
            return
        if url == None and len(ctx.message.attachments) == 0:
            await ctx.send("Usage: `{}poke [url, user, or attachment]`".format(
                ctx.prefix))
            return
        if url == None:
            url = ctx.message.attachments[0].url
        # Let's check if the "url" is actually a user
        test_user = DisplayName.memberForName(url, ctx.guild)
        if test_user:
            # Got a user!
            url = test_user.avatar_url
            if not len(url):
                url = test_user.default_avatar_url
        image = self.image.copy()
        message = await ctx.send("Preparing to poke...")
        path = await GetImage.download(url)
        if not path:
            return await message.edit(
                content=
                "I guess I couldn't poke that...  Make sure you're passing a valid url, user, or attachment."
            )
        # We should have the image - let's open it and convert to a single frame
        try:
            img = Image.open(path)
            img = img.convert('RGBA')
            # Let's ensure it's the right size, and place it in the right spot
            t_max = int(image.width * .38)
            t_ratio = min(t_max / img.width, t_max / img.height)
            t_w = int(img.width * t_ratio)
            t_h = int(img.height * t_ratio)
            img = img.resize((t_w, t_h), resample=PIL.Image.LANCZOS)
            # Paste our other image on top
            image.paste(img,
                        (int(image.width * .6), int(image.height * .98) - t_h),
                        mask=img)
            image.save('images/dosomethingnow.png')
            await ctx.send(file=discord.File(fp='images/dosomethingnow.png'))
            await message.delete()
            os.remove('images/dosomethingnow.png')
        except Exception as e:
            print(e)
            pass
        if os.path.exists(path):
            GetImage.remove(path)
Exemple #5
0
 async def emoji(self, ctx, emoji=None):
     '''Outputs the passed emoji... but bigger!'''
     if emoji is None:
         await ctx.send("Usage: `{}emoji [emoji]`".format(ctx.prefix))
         return
     # Get the emoji
     emoji_url = self._get_emoji_url(emoji)
     if not emoji_url:
         return await ctx.send("Usage: `{}emoji [emoji]`".format(ctx.prefix)
                               )
     f = await GetImage.download(emoji_url[0])
     if not f: return await ctx.send("I couldn't get that emoji :(")
     await ctx.send(file=discord.File(f))
     # Clean up
     GetImage.remove(f)
Exemple #6
0
 async def emoji(self, ctx, emoji=None):
     '''Menampilkan emoji, tapi dengan ukuran yang lebih BESAAAAAAR!'''
     if emoji is None:
         em = discord.Embed(
             color=0XFF8C00,
             description=
             "> Menampilkan Emoji, Dengan ukuran lebih BESAAAAAARRR!1!11!\n> \n"
             "> **Panduan pengunaan**\n"
             "> `{}emoji [emoji]`".format(ctx.prefix))
         em.set_author(
             name="Help command",
             url="https://acinonyxesports.com/",
             icon_url=
             "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
         )
         em.set_footer(
             text=
             f"Saat mengetik command, tanda [] tidak usah digunakan.\nRequest By : {ctx.author.name}",
             icon_url=f"{ctx.author.avatar_url}")
         await ctx.send(embed=em)
         return
     # Get the emoji
     emoji_url = self._get_emoji_url(emoji)
     em = discord.Embed(
         color=0XFF8C00,
         description=
         "> Menampilkan Emoji, Dengan ukuran lebih BESAAAAAARRR!1!11!\n> \n"
         "> **Panduan pengunaan**\n"
         f"> `{ctx.prefix}emoji [emoji]`")
     em.set_author(
         name="Help command",
         url="https://acinonyxesports.com/",
         icon_url=
         "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
     )
     em.set_footer(
         text=
         f"Saat mengetik command, tanda [] tidak usah digunakan.\nRequest By : {ctx.author.name}",
         icon_url=f"{ctx.author.avatar_url}")
     if not emoji_url: return await ctx.send(embed=em)
     f = await GetImage.download(emoji_url[0])
     if not f:
         return await ctx.send(
             "┐( ̄ヘ ̄;)┌\nAku tidak dapat menemukan emoji itu")
     await ctx.send(file=discord.File(f))
     # Clean up
     GetImage.remove(f)
Exemple #7
0
    async def avatar(self, ctx, filename=None):
        """Set bot avatar (owner only)."""
        if not await Utils.is_owner_reply(ctx): return

        if filename is None and not len(ctx.message.attachments):
            msg = "Menghapus avatar..."
            em = discord.Embed(color=0XFF8C00, description=msg)
            em.set_footer(text="{}".format(ctx.author),
                          icon_url="{}".format(ctx.author.avatar_url))
            m = await ctx.send(embed=em)
            try:
                await self.bot.user.edit(avatar=None)
            except discord.errors.HTTPException as e:
                msg = "┐( ̄ヘ ̄;)┌\nSepertinya aku tidak bisa melakukannya sekarang\nSilahkan coba lagi nanti!"
                em = discord.Embed(color=0XFF8C00, description=msg)
                em.set_footer(text="{}".format(ctx.author),
                              icon_url="{}".format(ctx.author.avatar_url))
                return await m.edit(embed=em)
            msg = "Avatar dihapus!"
            em = discord.Embed(color=0XFF8C00, description=msg)
            em.set_footer(text="{}".format(ctx.author),
                          icon_url="{}".format(ctx.author.avatar_url))
            return await m.edit(embed=em)

        # Check if attachment
        if filename == None:
            filename = ctx.message.attachments[0].url

        # Let's check if the "url" is actually a user
        test_user = DisplayName.memberForName(filename, ctx.guild)
        if test_user:
            # Got a user!
            filename = test_user.avatar_url if len(
                test_user.avatar_url) else test_user.default_avatar_url
        # Ensure string
        filename = str(filename)

        # Check if we created a temp folder for this image
        isTemp = False
        msg = 'Memeriksa URL dan mengunduh jika valid...'
        em = discord.Embed(color=0XFF8C00, description=msg)
        em.set_footer(text="{}".format(ctx.author),
                      icon_url="{}".format(ctx.author.avatar_url))
        status = await ctx.send(embed=em)

        # File name is *something* - let's first check it as a url, then a file
        extList = ["jpg", "jpeg", "png", "gif", "tiff", "tif", "webp"]
        if GetImage.get_ext(filename).lower() in extList:
            # URL has an image extension
            f = await GetImage.download(filename)
            if f:
                # we got a download - let's reset and continue
                filename = f
                isTemp = True

        if not os.path.isfile(filename):
            if not os.path.isfile('./{}'.format(filename)):
                msg = '*{}* tidak dapat menemukan gambar dalam direktori.'.format(
                    filename)
                em = discord.Embed(color=0XFF8C00, description=msg)
                em.set_footer(text="{}".format(ctx.author),
                              icon_url="{}".format(ctx.author.avatar_url))
                return await status.edit(embed=em)
            else:
                # Local file name
                filename = './{}'.format(filename)

        # File exists - check if image
        img = Image.open(filename)
        ext = img.format

        if not ext:
            # File isn't a valid image
            msg = '*{}* File bukan format gambar, silahkan coba lagi!'.format(
                filename)
            em = discord.Embed(color=0XFF8C00, description=msg)
            em.set_footer(text="{}".format(ctx.author),
                          icon_url="{}".format(ctx.author.avatar_url))
            return await status.edit(embed=em)

        wasConverted = False
        # Is an image PIL understands
        if not ext.lower == "png":
            # Not a PNG - let's convert
            msg = 'Convert ke png...'
            em = discord.Embed(color=0XFF8C00, description=msg)
            em.set_footer(text="{}".format(ctx.author),
                          icon_url="{}".format(ctx.author.avatar_url))
            await status.edit(embed=em)
            filename = '{}.png'.format(filename)
            img.save(filename)
            wasConverted = True

        # We got it - crop and go from there
        w, h = img.size
        dw = dh = 0
        if w > h:
            # Wide
            dw = int((w - h) / 2)
        elif h > w:
            # Tall
            dh = int((h - w) / 2)
        # Run the crop
        img.crop((dw, dh, w - dw, h - dh)).save(filename)
        msg = 'Upload dan memasang avatar...'
        em = discord.Embed(color=0XFF8C00, description=msg)
        em.set_footer(text="{}".format(ctx.author),
                      icon_url="{}".format(ctx.author.avatar_url))
        await status.edit(embed=em)
        with open(filename, 'rb') as f:
            newAvatar = f.read()
            try:
                await self.bot.user.edit(avatar=newAvatar)
            except discord.errors.HTTPException as e:
                msg = "┐( ̄ヘ ̄;)┌\nSepertinya aku tidak bisa melakukannya sekarang. Coba lagi nanti!"
                em = discord.Embed(color=0XFF8C00, description=msg)
                em.set_footer(text="{}".format(ctx.author),
                              icon_url="{}".format(ctx.author.avatar_url))
                return await status.edit(embed=em)
        # Cleanup - try removing with shutil.rmtree, then with os.remove()
        msg = 'Cleaning up...'
        em = discord.Embed(color=0XFF8C00, description=msg)
        em.set_footer(text="{}".format(ctx.author),
                      icon_url="{}".format(ctx.author.avatar_url))
        await status.edit(embed=em)
        if isTemp:
            GetImage.remove(filename)
        else:
            if wasConverted:
                os.remove(filename)
        msg = "Avatar telah diset!"
        em = discord.Embed(color=0XFF8C00, description=msg)
        em.set_footer(text="{}".format(ctx.author),
                      icon_url="{}".format(ctx.author.avatar_url))
        await status.edit(embed=em)
    async def stardew(self, ctx, *, user=None):
        """Test your luck with another user."""

        # Set some defaults
        name_max_w = 92
        name_max_h = 15
        if not self.canDisplay(ctx.guild):
            return
        # Let's check if the "url" is actually a user
        test_user = DisplayName.memberForName(user, ctx.guild)
        if not test_user:
            return await ctx.send("Usage: `{}stardew [user]`".format(
                ctx.prefix))
        # Got a user!
        user = test_user.avatar_url
        if not len(user):
            user = test_user.default_avatar_url
        # User profile pic needs to be formatted to 64x65 pixels - and the top left corner is at
        # (221,15)
        image = self.s_image.copy()
        if not image.width == 319 or not image.height == 111:
            image = image.resize((319, 111), resample=PIL.Image.LANCZOS)
        item = random.choice(self.stardew_gifts)
        message = await ctx.send("Gifting *{}* to {}...".format(
            item, DisplayName.name(test_user)))
        path = await GetImage.download(user)
        if not path:
            return await message.edit(
                content=
                "I guess I couldn't gift that...  Make sure you're passing a valid user."
            )
        # We should have the image - let's open it and convert to a single frame
        try:
            img = Image.open(path)
            img = img.convert('RGBA')
            # Let's ensure it's the right size, and place it in the right spot
            img = img.resize((64, 65))
            # Paste our other image on top
            image.paste(img, (221, 15), mask=img)
            # Write the user's name in the name box - starts at (209,99)
            d = ImageDraw.Draw(image)
            name_text = test_user.display_name
            name_size = name_max_h  # max size for the name to fit
            t_w, t_h = d.textsize(name_text,
                                  font=ImageFont.truetype(
                                      "fonts/stardew.ttf", name_size))
            if t_w > name_max_w:
                name_size = int(t_h * (name_max_w / t_w))
                t_w, t_h = d.textsize(name_text,
                                      font=ImageFont.truetype(
                                          "fonts/stardew.ttf", name_size))
            d.text((210 + (88 - t_w) / 2, 88 + (12 - t_h) / 2),
                   test_user.display_name,
                   font=ImageFont.truetype("fonts/stardew.ttf", name_size),
                   fill=(86, 22, 12))
            # Get the response - origin is (10,10), each row height is 14
            rows = textwrap.wrap(random.choice(self.stardew_responses),
                                 30,
                                 break_long_words=True,
                                 replace_whitespace=False)
            for index, row in enumerate(rows[:6]):
                d.text((11 + 2, 10 + 14 * index),
                       row,
                       font=ImageFont.truetype("fonts/stardew.ttf", 15),
                       fill=(86, 22, 12))
            # Resize to triple and save
            image = image.resize((319 * 3, 111 * 3), PIL.Image.NEAREST)
            image.save('images/Stardewnow.png')
            await ctx.send(file=discord.File(fp='images/Stardewnow.png'))
            # await message.delete(delay=2)
            await message.edit(content="Gifted *{}* to {}.".format(
                item, DisplayName.name(test_user)))
            os.remove('images/Stardewnow.png')
        except Exception as e:
            print(e)
            pass
        if os.path.exists(path):
            GetImage.remove(path)
Exemple #9
0
 async def addemoji(self, ctx, *, emoji=None, name=None):
     '''Adds the passed emoji, url, or attachment as a custom emoji with the passed name (bot-admin only, max of 10).'''
     if not await Utils.is_bot_admin_reply(ctx): return
     if not len(ctx.message.attachments) and emoji == name == None:
         return await ctx.send(
             "Usage: `{}addemoji [emoji, url, attachment] [name]`".format(
                 ctx.prefix))
     # Let's find out if we have an attachment, emoji, or a url
     # Check attachments first - as they'll have priority
     if len(ctx.message.attachments):
         name = emoji
         emoji = " ".join([x.url for x in ctx.message.attachments])
         if name:  # Add the name separated by a space
             emoji += " " + name
     # Now we split the emoji string, and walk it, looking for urls, emojis, and names
     emojis_to_add = []
     last_name = []
     for x in emoji.split():
         # Check for a url
         urls = Utils.get_urls(x)
         if len(urls):
             url = (urls[0], os.path.basename(urls[0]).split(".")[0])
         else:
             # Check for an emoji
             url = self._get_emoji_url(x)
             if not url:
                 # Gotta be a part of the name - add it
                 last_name.append(x)
                 continue
         if len(emojis_to_add) and last_name:
             # Update the previous name if need be
             emojis_to_add[-1][1] = "".join([
                 z for z in "_".join(last_name) if z.isalnum() or z == "_"
             ])
         # We have a valid url or emoji here - let's make sure it's unique
         if not url[0] in [x[0] for x in emojis_to_add]:
             emojis_to_add.append([url[0], url[1]])
         # Reset last_name
         last_name = []
     if len(emojis_to_add) and last_name:
         # Update the final name if need be
         emojis_to_add[-1][1] = "".join(
             [z for z in "_".join(last_name) if z.isalnum() or z == "_"])
     if not emojis_to_add:
         return await ctx.send(
             "Usage: `{}addemoji [emoji, url, attachment] [name]`".format(
                 ctx.prefix))
     # Now we have a list of emojis and names
     added_emojis = []
     allowed = len(emojis_to_add) if len(
         emojis_to_add) <= self.max_emojis else self.max_emojis
     omitted = " ({} omitted, beyond the limit of {})".format(
         len(emojis_to_add) - self.max_emojis,
         self.max_emojis) if len(emojis_to_add) > self.max_emojis else ""
     message = await ctx.send("Adding {} emoji{}{}...".format(
         allowed, "" if allowed == 1 else "s", omitted))
     for emoji_to_add in emojis_to_add[:self.max_emojis]:
         # Let's try to download it
         emoji, e_name = emoji_to_add  # Expand into the parts
         f = await GetImage.download(emoji)
         if not f: continue
         # Open the image file
         with open(f, "rb") as e:
             image = e.read()
         # Clean up
         GetImage.remove(f)
         if not e_name.replace("_", ""): continue
         # Create the emoji and save it
         try:
             new_emoji = await ctx.guild.create_custom_emoji(
                 name=e_name,
                 image=image,
                 roles=None,
                 reason="Added by {}#{}".format(ctx.author.name,
                                                ctx.author.discriminator))
         except:
             continue
         added_emojis.append(new_emoji)
     msg = "Created {} of {} emoji{}{}.".format(len(added_emojis), allowed,
                                                "" if allowed == 1 else "s",
                                                omitted)
     if len(added_emojis):
         msg += "\n\n"
         emoji_text = [
             "{} - `:{}:`".format(self._get_emoji_mention(x), x.name)
             for x in added_emojis
         ]
         msg += "\n".join(emoji_text)
     await message.edit(content=msg)
Exemple #10
0
    async def avatar(self,
                     ctx,
                     filename: str = None,
                     sizeLimit: int = 8000000):
        """Sets the bot's avatar (owner only)."""

        channel = ctx.message.channel
        author = ctx.message.author
        server = ctx.message.server

        # Only allow owner to change server stats
        serverDict = self.settings.serverDict

        try:
            owner = serverDict['Owner']
        except KeyError:
            owner = None

        if owner == None:
            # No owner set
            msg = 'I have not been claimed, *yet*.'
            await self.bot.send_message(channel, msg)
            return
        else:
            if not author.id == owner:
                msg = 'You are not the *true* owner of me.  Only the rightful owner can change my avatar.'
                await self.bot.send_message(channel, msg)
                return
        if filename is None:
            await self.bot.edit_profile(avatar=None)
            return

        # Check if we created a temp folder for this image
        isTemp = False

        status = await self.bot.send_message(
            channel, 'Checking if url (and downloading if valid)...')

        # File name is *something* - let's first check it as a url, then a file
        extList = ["jpg", "jpeg", "png", "gif", "tiff", "tif"]
        if GetImage.get_ext(filename) in extList:
            # URL has an image extension
            file = GetImage.download(filename)
            if file:
                # we got a download - let's reset and continue
                filename = file
                isTemp = True

        if not os.path.isfile(filename):
            if not os.path.isfile('./{}'.format(filename)):
                await self.bot.edit_message(
                    status,
                    '*{}* doesn\'t exist absolutely, or in my working directory.'
                    .format(filename))
                # File doesn't exist
                return
            else:
                # Local file name
                filename = './{}'.format(filename)

        # File exists - check if image
        img = Image.open(filename)
        ext = img.format

        if not ext:
            # File isn't a valid image
            await self.bot.edit_message(
                status, '*{}* isn\'t a valid image format.'.format(filename))
            return

        wasConverted = False
        # Is an image PIL understands
        if not ext.lower == "png":
            # Not a PNG - let's convert
            await self.bot.edit_message(status, 'Converting to png...')
            filename = '{}.png'.format(filename)
            img.save(filename)
            wasConverted = True

        # We got it - crop and go from there
        w, h = img.size
        dw = dh = 0
        if w > h:
            # Wide
            dw = int((w - h) / 2)
        elif h > w:
            # Tall
            dh = int((h - w) / 2)
        # Run the crop
        await self.bot.edit_message(status, 'Cropping (if needed)...')
        img.crop((dw, dh, w - dw, h - dh)).save(filename)

        # Should be a square png here - let's check size
        # Let's make sure it's less than the passed limit

        imageSize = os.stat(filename)
        await self.bot.edit_message(status, 'Resizing (if needed)...')
        while int(imageSize.st_size) > sizeLimit:
            # Image is too big - resize
            myimage = Image.open(filename)
            xsize, ysize = myimage.size
            ratio = sizeLimit / int(imageSize.st_size)
            xsize *= ratio
            ysize *= ratio
            myimage = myimage.resize((int(xsize), int(ysize)), Image.ANTIALIAS)
            myimage.save(filename)
            imageSize = os.stat(filename)
        # Image is resized - let's save it
        img = Image.open(filename)
        ext = img.format
        img.close()

        await self.bot.edit_message(status, 'Uploading and applying avatar...')
        with open(filename, 'rb') as f:
            newAvatar = f.read()
            await self.bot.edit_profile(avatar=newAvatar)
        # Cleanup - try removing with shutil.rmtree, then with os.remove()
        await self.bot.edit_message(status, 'Cleaning up...')
        if isTemp:
            GetImage.remove(filename)
        else:
            if wasConverted:
                os.remove(filename)
        await self.bot.edit_message(status, 'Avatar set!')
Exemple #11
0
    async def avatar(self, ctx, filename=None):
        """Sets the bot's avatar (owner only)."""
        if not await Utils.is_owner_reply(ctx): return

        if filename is None and not len(ctx.message.attachments):
            m = await ctx.send("Removing avatar...")
            try:
                await self.bot.user.edit(avatar=None)
            except discord.errors.HTTPException as e:
                return await m.edit(
                    content=
                    "Looks like I can't do that right now.  Try again later!")
            return await m.edit(content='Avatar removed!')

        # Check if attachment
        if filename == None:
            filename = ctx.message.attachments[0].url

        # Let's check if the "url" is actually a user
        test_user = DisplayName.memberForName(filename, ctx.guild)
        if test_user:
            # Got a user!
            filename = test_user.avatar_url if len(
                test_user.avatar_url) else test_user.default_avatar_url
        # Ensure string
        filename = str(filename)

        # Check if we created a temp folder for this image
        isTemp = False
        status = await ctx.send('Checking if url (and downloading if valid)...'
                                )

        # File name is *something* - let's first check it as a url, then a file
        extList = ["jpg", "jpeg", "png", "gif", "tiff", "tif", "webp"]
        if GetImage.get_ext(filename).lower() in extList:
            # URL has an image extension
            f = await GetImage.download(filename)
            if f:
                # we got a download - let's reset and continue
                filename = f
                isTemp = True

        if not os.path.isfile(filename):
            if not os.path.isfile('./{}'.format(filename)):
                return await status.edit(
                    content=
                    '*{}* doesn\'t exist absolutely, or in my working directory.'
                    .format(filename))
            else:
                # Local file name
                filename = './{}'.format(filename)

        # File exists - check if image
        img = Image.open(filename)
        ext = img.format

        if not ext:
            # File isn't a valid image
            return await status.edit(
                content='*{}* isn\'t a valid image format.'.format(filename))

        wasConverted = False
        # Is an image PIL understands
        if not ext.lower == "png":
            # Not a PNG - let's convert
            await status.edit(content='Converting to png...')
            filename = '{}.png'.format(filename)
            img.save(filename)
            wasConverted = True

        # We got it - crop and go from there
        w, h = img.size
        dw = dh = 0
        if w > h:
            # Wide
            dw = int((w - h) / 2)
        elif h > w:
            # Tall
            dh = int((h - w) / 2)
        # Run the crop
        img.crop((dw, dh, w - dw, h - dh)).save(filename)

        await status.edit(content='Uploading and applying avatar...')
        with open(filename, 'rb') as f:
            newAvatar = f.read()
            try:
                await self.bot.user.edit(avatar=newAvatar)
            except discord.errors.HTTPException as e:
                return await status.edit(
                    content=
                    "Looks like I can't do that right now.  Try again later!")
        # Cleanup - try removing with shutil.rmtree, then with os.remove()
        await status.edit(content='Cleaning up...')
        if isTemp:
            GetImage.remove(filename)
        else:
            if wasConverted:
                os.remove(filename)
        await status.edit(content='Avatar set!')
Exemple #12
0
 async def addemoji(self, ctx, *, emoji=None, name=None):
     '''Menambahkan emoji (bot-admin only, maksimal 10 dalam 1 command)
     Dengan format berupa:
     • Attachment Gambar (Upload gambar)
     • Link URL
     • Atau emoji dari server lain (lebih mudah untuk pengguna nitro)'''
     if not await Utils.is_bot_admin_reply(ctx): return
     if not len(ctx.message.attachments) and emoji == name == None:
         em = discord.Embed(
             color=0XFF8C00,
             description="> Upload emoji gak usak pake ribet\n> \n"
             "> **Panduan pengunaan**\n"
             "> `{}addemoji [emoji server lain, url, attachment] [name]`".
             format(ctx.prefix))
         em.set_author(
             name="Help command",
             url="https://acinonyxesports.com/",
             icon_url=
             "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
         )
         em.set_footer(
             text=
             f"Saat mengetik command, tanda [] tidak usah digunakan.\nRequest By : {ctx.author.name}",
             icon_url=f"{ctx.author.avatar_url}")
         return await ctx.send(embed=em)
     # Let's find out if we have an attachment, emoji, or a url
     # Check attachments first - as they'll have priority
     if len(ctx.message.attachments):
         name = emoji
         emoji = " ".join([x.url for x in ctx.message.attachments])
         if name:  # Add the name separated by a space
             emoji += " " + name
     # Now we split the emoji string, and walk it, looking for urls, emojis, and names
     emojis_to_add = []
     last_name = []
     for x in emoji.split():
         # Check for a url
         urls = Utils.get_urls(x)
         if len(urls):
             url = (urls[0], os.path.basename(urls[0]).split(".")[0])
         else:
             # Check for an emoji
             url = self._get_emoji_url(x)
             if not url:
                 # Gotta be a part of the name - add it
                 last_name.append(x)
                 continue
         if len(emojis_to_add) and last_name:
             # Update the previous name if need be
             emojis_to_add[-1][1] = "".join([
                 z for z in "_".join(last_name) if z.isalnum() or z == "_"
             ])
         # We have a valid url or emoji here - let's make sure it's unique
         if not url[0] in [x[0] for x in emojis_to_add]:
             emojis_to_add.append([url[0], url[1]])
         # Reset last_name
         last_name = []
     if len(emojis_to_add) and last_name:
         # Update the final name if need be
         emojis_to_add[-1][1] = "".join(
             [z for z in "_".join(last_name) if z.isalnum() or z == "_"])
     em = discord.Embed(
         color=0XFF8C00,
         description="> Upload emoji gak usak pake ribet\n> \n"
         "> **Panduan pengunaan**\n"
         "> `{}addemoji [emoji server lain, url, attachment] [nama]`".
         format(ctx.prefix))
     em.set_author(
         name="Help command",
         url="https://acinonyxesports.com/",
         icon_url=
         "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
     )
     em.set_footer(
         text=
         f"Saat mengetik command, tanda [] tidak usah digunakan.\nRequest By : {ctx.author.name}",
         icon_url=f"{ctx.author.avatar_url}")
     if not emojis_to_add: return await ctx.send(embed=em)
     # Now we have a list of emojis and names
     added_emojis = []
     allowed = len(emojis_to_add) if len(
         emojis_to_add) <= self.max_emojis else self.max_emojis
     omitted = " ({} gambar dihilangkan, karena melebihi batas maksimal {})".format(
         len(emojis_to_add) - self.max_emojis,
         self.max_emojis) if len(emojis_to_add) > self.max_emojis else ""
     message = await ctx.send("Menambahkan {} emoji{}{}...".format(
         allowed, "" if allowed == 1 else "", omitted))
     for emoji_to_add in emojis_to_add[:self.max_emojis]:
         # Let's try to download it
         emoji, e_name = emoji_to_add  # Expand into the parts
         f = await GetImage.download(emoji)
         if not f: continue
         # Open the image file
         with open(f, "rb") as e:
             image = e.read()
         # Clean up
         GetImage.remove(f)
         if not e_name.replace("_", ""): continue
         # Create the emoji and save it
         try:
             new_emoji = await ctx.guild.create_custom_emoji(
                 name=e_name,
                 image=image,
                 roles=None,
                 reason="Added by {}#{}".format(ctx.author.name,
                                                ctx.author.discriminator))
         except:
             continue
         added_emojis.append(new_emoji)
     msg = "Membuat {} dari {} emoji{}{}.".format(
         len(added_emojis), allowed, "" if allowed == 1 else "", omitted)
     if len(added_emojis):
         msg += "\n\n"
         emoji_text = [
             "{} - `:{}:`".format(self._get_emoji_mention(x), x.name)
             for x in added_emojis
         ]
         msg += "\n".join(emoji_text)
     em = discord.Embed(color=0XFF8C00, description=msg)
     em.set_author(
         name="Berhasil menambahkan emoji",
         url="https://acinonyxesports.com/",
         icon_url=
         "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
     )
     em.set_footer(text=f"Request By : {ctx.author.name}",
                   icon_url=f"{ctx.author.avatar_url}")
     await message.edit(embed=em)
Exemple #13
0
    async def stardew(self, ctx, *, user=None):
        """Test keberuntungan mu dengan user lain."""

        # Set some defaults
        name_max_w = 92
        name_max_h = 15
        if not self.canDisplay(ctx.guild):
            return
        # Let's check if the "url" is actually a user
        test_user = DisplayName.memberForName(user, ctx.guild)
        if not test_user:
            em = discord.Embed(color=0XFF8C00,
                               description="> **Panduan**\n"
                               "> `{}stardew [user/member]`".format(
                                   ctx.prefix))
            em.set_author(
                name="Stardew",
                url="https://acinonyxesports.com",
                icon_url=
                "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
            )
            em.set_footer(
                text=
                "Saat mengetik command, tanda [] tidak usah digunakan\nRequest by : {}"
                .format(ctx.author.name),
                icon_url="{}".format(ctx.author.avatar_url))
            return await ctx.send(embed=em)
        # Got a user!
        user = test_user.avatar_url
        if not len(user):
            user = test_user.default_avatar_url
        # User profile pic needs to be formatted to 64x65 pixels - and the top left corner is at
        # (221,15)
        image = self.s_image.copy()
        if not image.width == 319 or not image.height == 111:
            image = image.resize((319, 111), resample=PIL.Image.LANCZOS)
        message = await ctx.send("Gifting *{}* to {}...".format(
            random.choice(self.stardew_gifts),
            Nullify.clean(DisplayName.name(test_user))))
        path = await GetImage.download(user)
        if not path:
            return await message.edit(
                content=
                "Aku tidak dapat melakukannya sekarang...\nPastikan kamu memasukan user/member dengan benar."
            )
        # We should have the image - let's open it and convert to a single frame
        try:
            img = Image.open(path)
            img = img.convert('RGBA')
            # Let's ensure it's the right size, and place it in the right spot
            img = img.resize((64, 65))
            # Paste our other image on top
            image.paste(img, (221, 15), mask=img)
            # Write the user's name in the name box - starts at (209,99)
            d = ImageDraw.Draw(image)
            name_text = DisplayName.name(test_user)
            name_size = name_max_h  # max size for the name to fit
            t_w, t_h = d.textsize(name_text,
                                  font=ImageFont.truetype(
                                      "fonts/stardew.ttf", name_size))
            if t_w > name_max_w:
                name_size = int(t_h * (name_max_w / t_w))
                t_w, t_h = d.textsize(name_text,
                                      font=ImageFont.truetype(
                                          "fonts/stardew.ttf", name_size))
            d.text((210 + (88 - t_w) / 2, 88 + (12 - t_h) / 2),
                   DisplayName.name(test_user),
                   font=ImageFont.truetype("fonts/stardew.ttf", name_size),
                   fill=(86, 22, 12))
            # Get the response - origin is (10,10), each row height is 14
            rows = textwrap.wrap(random.choice(self.stardew_responses),
                                 30,
                                 break_long_words=True,
                                 replace_whitespace=False)
            for index, row in enumerate(rows[:6]):
                d.text((11 + 2, 10 + 14 * index),
                       row,
                       font=ImageFont.truetype("fonts/stardew.ttf", 15),
                       fill=(86, 22, 12))
            # Resize to triple and save
            image = image.resize((319 * 3, 111 * 3), PIL.Image.NEAREST)
            image.save('images/Stardewnow.png')
            await ctx.send(file=discord.File(fp='images/Stardewnow.png'))
            await message.delete(delay=2)
            os.remove('images/Stardewnow.png')
        except Exception as e:
            print(e)
            pass
        if os.path.exists(path):
            GetImage.remove(path)
Exemple #14
0
    async def poke(self, ctx, *, url=None):
        """Poke url/user/attachment gambar."""

        if not self.canDisplay(ctx.guild):
            return
        if url == None and len(ctx.message.attachments) == 0:
            em = discord.Embed(
                color=0XFF8C00,
                description="> **Panduan**\n"
                "> `{}poke [url, user, atau attachment]`".format(ctx.prefix))
            em.set_author(
                name="Poke",
                url="https://acinonyxesports.com",
                icon_url=
                "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
            )
            em.set_footer(
                text=
                "Saat mengetik command, tanda [] tidak usah digunakan\nRequest by : {}"
                .format(ctx.author.name),
                icon_url="{}".format(ctx.author.avatar_url))
            await ctx.send(embed=em)
            return
        if url == None:
            url = ctx.message.attachments[0].url
        # Let's check if the "url" is actually a user
        test_user = DisplayName.memberForName(url, ctx.guild)
        if test_user:
            # Got a user!
            url = test_user.avatar_url
            if not len(url):
                url = test_user.default_avatar_url
        image = self.image.copy()
        message = await ctx.send("Mempersiapkan gambar...")
        path = await GetImage.download(url)
        if not path:
            return await message.edit(
                content=
                "Aku tidak dapat melakukannya sekarang...\npastikan kamu memasukan user, url, atau attachment dengan benar."
            )
        # We should have the image - let's open it and convert to a single frame
        try:
            img = Image.open(path)
            img = img.convert('RGBA')
            # Let's ensure it's the right size, and place it in the right spot
            t_max = int(image.width * .38)
            t_ratio = min(t_max / img.width, t_max / img.height)
            t_w = int(img.width * t_ratio)
            t_h = int(img.height * t_ratio)
            img = img.resize((t_w, t_h), resample=PIL.Image.LANCZOS)
            # Paste our other image on top
            image.paste(img,
                        (int(image.width * .6), int(image.height * .98) - t_h),
                        mask=img)
            image.save('images/dosomethingnow.png')
            await ctx.send(file=discord.File(fp='images/dosomethingnow.png'))
            await message.delete()
            os.remove('images/dosomethingnow.png')
        except Exception as e:
            print(e)
            pass
        if os.path.exists(path):
            GetImage.remove(path)