def getTitle(self, url, answer: bool = False, image: bool = False): # Load url - with self.posts number of posts r = requests.get(url, headers={'User-agent': self.ua}) # If we need an image - make sure we have a valid one gotLink = False while not gotLink: if image: gotImage = False while not gotImage: randnum = random.randint(0, self.posts) try: theJSON = r.json()["data"]["children"][randnum]["data"] except IndexError: # Failed - set to none theJSON = {"url": ""} if GetImage.get_ext(theJSON["url"]) in self.extList: gotImage = True gotLink = True else: randnum = random.randint(0, self.posts) try: theJSON = r.json()["data"]["children"][randnum]["data"] gotLink = True except IndexError: theJSON = {"url": ""} if not (answer or image): # Just return the title return '{}'.format(theJSON["title"]) if answer or image: # We need the image or the answer return {'title': theJSON['title'], 'url': theJSON["url"]}
async def getInfo(self, url): # Let's try using reddit's json info to get our images try: r = await DL.async_json(url, {'User-agent': self.ua}) numPosts = len(r['data']['children']) except Exception: numPosts = 0 if numPosts <= 0: # No links return None gotLink = False returnDict = None for i in range(0, 10): randnum = random.randint(0, numPosts - 1) try: theJSON = r["data"]["children"][randnum]["data"] theURL = None if 'preview' in theJSON: # We've got images right in the json theURL = theJSON['preview']['images'][0]['source']['url'] else: # No images - let's check the url imageURL = theJSON['url'] if 'imgur.com/a/' in imageURL.lower(): # It's an imgur album response = await DL.async_text(imageURL) dom = pq(response.text) # Get the first image image = dom('.image-list-link')[0] image = pq(image).attr('href').split('/')[2] theURL = 'http://i.imgur.com/{}.jpg'.format(image) else: # Not an imgur album - let's try for a single image if GetImage.get_ext(imageURL).lower() in self.extList: theURL = imageURL elif await self.getImageHEAD( imageURL).lower() in self.headList: # Check header as a last resort theURL = imageURL if not theURL: continue returnDict = { 'title': theJSON['title'], 'url': HTMLParser().unescape(theURL), 'over_18': theJSON['over_18'], 'permalink': theJSON['permalink'], 'score': theJSON['score'], 'num_comments': theJSON['num_comments'] } break except Exception: continue return returnDict
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 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!')
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!')