Python discord.File() Examples

The following are 30 code examples of discord.File(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: wolfram.py    From bot with MIT License 1111 votes vote down vote up
def send_embed(
        ctx: Context,
        message_txt: str,
        colour: int = Colours.soft_red,
        footer: str = None,
        img_url: str = None,
        f: discord.File = None
) -> None:
    """Generate & send a response embed with Wolfram as the author."""
    embed = Embed(colour=colour)
    embed.description = message_txt
    embed.set_author(name="Wolfram Alpha",
                     icon_url=WOLF_IMAGE,
                     url="https://www.wolframalpha.com/")
    if footer:
        embed.set_footer(text=footer)

    if img_url:
        embed.set_image(url=img_url)

    await ctx.send(embed=embed, file=f) 
Example #2
Source File: core.py    From DiscordStorage with MIT License 6 votes vote down vote up
def async_upload(self,inp,code):
            urls = []
            f = open(inp,'rb')
            for i in range(0,self.splitFile(inp)):
                    o = io.BytesIO(f.read(8000000))
                    discord_file = discord.File(fp=o,filename=code+"." + str(i))
                    await self.session.getChannel().send(file=discord_file)
                    async for message in self.session.getChannel().history(limit=None):
                            if message.author == self.client.user:
                                    urls.append(message.attachments[0].url)
                                    break
            f.close()

            return [os.path.basename(inp),os.path.getsize(inp),urls]

    #Finds out how many file blocks are needed to upload a file.
    #Regular max upload size at a time: 8MB.
    #Discord NITRO max upload size at a time: 50MB.
    #Change accordingly if needed. 
Example #3
Source File: deepfry.py    From FlameCogs with MIT License 6 votes vote down vote up
def nuke(self, ctx, link: str=None):
		"""
		Demolishes images.
		
		Use the optional parameter "link" to use a **direct link** as the target.
		"""
		async with ctx.typing():
			try:
				img, isgif, duration = await self._get_image(ctx, link)
			except ImageFindError as e:	
				return await ctx.send(e)
			if isgif:
				task = functools.partial(self._videonuke, img, duration)
			else:
				task = functools.partial(self._nuke, img)	
			task = self.bot.loop.run_in_executor(None, task)
			try:
				image = await asyncio.wait_for(task, timeout=60)
			except asyncio.TimeoutError:
				return await ctx.send('The image took too long to process.')
			try:
				await ctx.send(file=discord.File(image))
			except discord.errors.HTTPException:
				return await ctx.send('That image is too large.') 
Example #4
Source File: dotastats.py    From MangoByte with MIT License 6 votes vote down vote up
def print_match_stats(self, ctx, match_id):
		match = await get_match(match_id)
		duration = get_pretty_duration(match['duration'], postfix=False)
		game_mode = self.dota_game_strings.get(f"game_mode_{match.get('game_mode')}", "Unknown")
		lobby_type = self.dota_game_strings.get(f"lobby_type_{match.get('lobby_type')}", "Unknown") + " "
		if lobby_type == "Normal ":
			lobby_type = ""

		description = (f"This {lobby_type}**{game_mode}** match ended in {duration} \n"
					f"More info at [DotaBuff](https://www.dotabuff.com/matches/{match_id}), "
					f"[OpenDota](https://www.opendota.com/matches/{match_id}), or "
					f"[STRATZ](https://www.stratz.com/match/{match_id})")

		embed = discord.Embed(description=description, 
							timestamp=datetime.datetime.utcfromtimestamp(match['start_time']), color=self.embed_color)
		embed.set_author(name="Match {}".format(match_id), url="https://www.opendota.com/matches/{}".format(match_id))

		embed.add_field(name="Game Mode", value=game_mode)
		embed.add_field(name="Lobby Type", value=game_mode)

		match_image = discord.File(await drawdota.create_match_image(match), filename="matchimage.png")

		embed.set_image(url=f"attachment://{match_image.filename}")
		embed.set_footer(text=str(match_id))
		await ctx.send(embed=embed, file=match_image) 
Example #5
Source File: dotabase.py    From MangoByte with MIT License 6 votes vote down vote up
def herotable(self, ctx, *, table_args : HeroStatsTableArgs):
		"""Displays a sorted table of heroes and their stats
		
		Displays a table with computed hero stats showing which heroes have the highest values for the specified stat. To see the list of possible stats, try the `{cmdpfx}leveledstats` command

		**Examples:**
		`{cmdpfx}herotable dps`
		`{cmdpfx}herotable health lvl 30`
		`{cmdpfx}herotable attack speed level 21 descending`
		"""
		if table_args.stat is None:
			raise UserError(f"Please select a stat to sort by. For a list of stats, see `{self.cmdpfx()}leveledstats`")
		if table_args.hero_level < 1 or table_args.hero_level > 30:
			raise UserError("Please select a hero level between 1 and 30")
		if table_args.hero_count < 2 or table_args.hero_count > 40:
			raise UserError("Please select a hero count between 2 and 40")

		embed = discord.Embed()

		image = discord.File(await drawdota.draw_herostatstable(table_args, self.hero_stat_categories, self.leveled_hero_stats), "herotable.png")
		embed.set_image(url=f"attachment://{image.filename}")
		embed.set_footer(text="The stats shown above do not account for talents, passives, or items")

		await ctx.send(embed=embed, file=image) 
Example #6
Source File: deepfry.py    From FlameCogs with MIT License 6 votes vote down vote up
def deepfry(self, ctx, link: str=None):
		"""
		Deepfries images.
		
		Use the optional parameter "link" to use a **direct link** as the target.
		"""
		async with ctx.typing():
			try:
				img, isgif, duration = await self._get_image(ctx, link)
			except ImageFindError as e:	
				return await ctx.send(e)
			if isgif:
				task = functools.partial(self._videofry, img, duration)
			else:
				task = functools.partial(self._fry, img)
			task = self.bot.loop.run_in_executor(None, task)
			try:
				image = await asyncio.wait_for(task, timeout=60)
			except asyncio.TimeoutError:
				return await ctx.send('The image took too long to process.')
			try:
				await ctx.send(file=discord.File(image))
			except discord.errors.HTTPException:
				return await ctx.send('That image is too large.') 
Example #7
Source File: dotastats.py    From MangoByte with MIT License 6 votes vote down vote up
def opendota(self, ctx, *, query):
		"""Queries the opendota api

		You can use this to get a json file with details about players or matches etc.
		Examples:
		`{cmdpfx}opendota /players/{steamid}`
		`{cmdpfx}opendota /matches/{match_id}`

		For more options and a better explanation, check out their [documentation](https://docs.opendota.com)"""
		query = query.replace("/", " ")
		query = query.strip()
		query = "/" + "/".join(query.split(" "))

		with ctx.channel.typing():
			data = await opendota_query(query)

		filename = re.search("/([/0-9a-zA-Z]+)", query).group(1).replace("/", "_")
		filename = settings.resource(f"temp/{filename}.json")
		write_json(filename, data)
		await ctx.send(file=discord.File(filename))
		os.remove(filename) 
Example #8
Source File: dotabase.py    From MangoByte with MIT License 6 votes vote down vote up
def emoticon(self, ctx, name):
		"""Gets the gif of a dota emoticon

		<a:pup:406270527766790145> <a:stunned:406274986769252353> <a:cocky:406274999951949835>

		**Examples:**
		`{cmdpfx}emoticon pup`
		`{cmdpfx}emoticon stunned`
		`{cmdpfx}emoticon naga_song`"""
		await ctx.channel.trigger_typing()

		emoticon = session.query(Emoticon).filter(Emoticon.name == name).first()

		if not emoticon:
			raise UserError(f"Couldn't find an emoticon with the name '{name}'")

		url = self.vpkurl + emoticon.url
		image = discord.File(await drawdota.create_dota_emoticon(emoticon, url), f"{name}.gif")

		await ctx.send(file=image) 
Example #9
Source File: utility.py    From Discord-Selfbot with GNU General Public License v3.0 6 votes vote down vote up
def getcolour(self, ctx, *, colour_codes):
        """Posts color of given hex"""
        await ctx.message.delete()
        colour_codes = colour_codes.split()
        size = (60, 80) if len(colour_codes) > 1 else (200, 200)
        if len(colour_codes) > 5:
            return await ctx.send(self.bot.bot_prefix + "Sorry, 5 colour codes maximum")
        for colour_code in colour_codes:
            if not colour_code.startswith("#"):
                colour_code = "#" + colour_code
            image = Image.new("RGB", size, colour_code)
            with io.BytesIO() as file:
                image.save(file, "PNG")
                file.seek(0)
                await ctx.send("Colour with hex code {}:".format(colour_code), file=discord.File(file, "colour_file.png"))
            await asyncio.sleep(1)  # Prevent spaminess 
Example #10
Source File: color.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def color(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    file = None
    if pld.args:
        color_tuple = get_color_tuple(pld.args)
        if color_tuple:
            image = Image.new('RGB', (128, 128), color_tuple)
            image = store_image(image)
            file = discord.File(image, f'{pld.msg.id}.png')
            response = discord.Embed(color=rgb_to_hex(color_tuple))
            response.set_image(url=f'attachment://{pld.msg.id}.png')
        else:
            response = error('Invalid input, HEX or RGB sequence, please.')
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(file=file, embed=response) 
Example #11
Source File: randomcolor.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def randomcolor(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    piece_r = secrets.randbelow(256)
    piece_g = secrets.randbelow(256)
    piece_b = secrets.randbelow(256)
    color_tupple = (piece_r, piece_g, piece_b)
    hexname = f'Color: `#{str(hex(piece_r))[2:]}{str(hex(piece_g))[2:]}{str(hex(piece_b))[2:]}`'
    image = Image.new('RGB', (128, 128), color_tupple)
    image.save(f'cache/{pld.msg.id}.png')
    img_file = discord.File(f'cache/{pld.msg.id}.png')
    await pld.msg.channel.send(hexname, file=img_file)
    os.remove(f'cache/{pld.msg.id}.png') 
Example #12
Source File: file_upload_hook.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
def upload_to_privatebin_if_too_long(original_send, content=None, **kwargs):
	if content is None:
		return True,

	content = str(content)
	if len(content) <= 2000:
		return True,

	out = io.StringIO(content)
	if utils.size(out) > FILE_SIZE_LIMIT:
		# translator's note: this is sent to the user when the bot tries to send a message larger than ~8MiB
		return False, await original_send(_('Way too long.'))

	file = discord.File(fp=io.StringIO(content), filename='message.txt')
	# translator's note: this is sent to the user when the bot tries to send a message >2000 characters
	# but less than 8MiB
	return False, await original_send(_('Way too long. Message attached.'), **kwargs, file=file) 
Example #13
Source File: sheetManager.py    From avrae with GNU General Public License v3.0 6 votes vote down vote up
def playertoken(self, ctx):
        """Generates and sends a token for use on VTTs."""

        char: Character = await Character.from_ctx(ctx)
        color_override = char.get_setting('color')
        if not char.image:
            return await ctx.send("This character has no image.")

        try:
            processed = await generate_token(char.image, color_override)
        except Exception as e:
            return await ctx.send(f"Error generating token: {e}")

        file = discord.File(processed, filename="image.png")
        embed = EmbedWithCharacter(char, image=False)
        embed.set_image(url="attachment://image.png")
        await ctx.send(file=file, embed=embed)
        processed.close() 
Example #14
Source File: imagegen.py    From bot with MIT License 6 votes vote down vote up
def df(self, ctx, image: typing.Union[Member, str] = None):
		if not image:
			if len(ctx.message.attachments) >= 1:
				image = ctx.message.attachments[0].url
			else:
				image = str(ctx.author.avatar_url_as(format='png'))
		if isinstance(image, discord.Member):
			image = str(image.avatar_url_as(format='png'))
		image = image.strip('<>')
		async with aiohttp.ClientSession(
			headers={'Authorization': self.bot.config["aeromeme"]}
		) as s:
			imgraw = await s.get(f'https://memes.aero.bot/api/deepfry?avatar1={image}')
			if imgraw.status != 200:
				return await ctx.error('Something went wrong...')
			imgraw = await imgraw.read()
			await s.close()
		file = discord.File(BytesIO(imgraw), f'deepfried.png')
		await ctx.send(file=file) 
Example #15
Source File: 8bitify.py    From seasonalbot with MIT License 6 votes vote down vote up
def eightbit_command(self, ctx: commands.Context) -> None:
        """Pixelates your avatar and changes the palette to an 8bit one."""
        async with ctx.typing():
            image_bytes = await ctx.author.avatar_url.read()
            avatar = Image.open(BytesIO(image_bytes))
            avatar = avatar.convert("RGBA").resize((1024, 1024))

            eightbit = self.pixelate(avatar)
            eightbit = self.quantize(eightbit)

            bufferedio = BytesIO()
            eightbit.save(bufferedio, format="PNG")
            bufferedio.seek(0)

            file = discord.File(bufferedio, filename="8bitavatar.png")

            embed = discord.Embed(
                title="Your 8-bit avatar",
                description='Here is your avatar. I think it looks all cool and "retro"'
            )

            embed.set_image(url="attachment://8bitavatar.png")
            embed.set_footer(text=f"Made by {ctx.author.display_name}", icon_url=ctx.author.avatar_url)

        await ctx.send(file=file, embed=embed) 
Example #16
Source File: spoiler.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def spoiler(ctx: MtgContext, *, args: str) -> None:
    """Request a card from an upcoming set."""
    if len(args) == 0:
        await ctx.send('{author}: Please specify a card name.'.format(author=ctx.author.mention))
        return
    sfcard = fetch_tools.fetch_json('https://api.scryfall.com/cards/named?fuzzy={name}'.format(name=args))
    if sfcard['object'] == 'error':
        await ctx.send('{author}: {details}'.format(author=ctx.author.mention, details=sfcard['details']))
        return
    imagename = '{set}_{number}'.format(
        set=sfcard['set'], number=sfcard['collector_number'])
    imagepath = '{image_dir}/{imagename}.jpg'.format(image_dir=configuration.get('image_dir'), imagename=imagename)
    if sfcard.get('card_faces') and sfcard.get('layout', '') != 'split':
        c = sfcard['card_faces'][0]
    else:
        c = sfcard
    fetch_tools.store(c['image_uris']['normal'], imagepath)
    text = emoji.replace_emoji('{name} {mana}'.format(name=sfcard['name'], mana=c['mana_cost']), ctx.bot)
    await ctx.send(file=File(imagepath), content=text)
    await oracle.scryfall_import_async(sfcard['name']) 
Example #17
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def boi(self, ctx):
        """BOI"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/boi.jpg")) 
Example #18
Source File: commands.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_board(self, context, message, board):
		if board.is_nsfw() and not getattr(context.channel, 'nsfw', True):
			raise BoardTooLewdError
		async with context.typing():
			f = discord.File(
				io.BytesIO(await bingo.render_in_subprocess(self.bot, board)),
				f'{context.author.id}_board.png')
		await context.send(message, file=f) 
Example #19
Source File: assist.py    From bot with MIT License 5 votes vote down vote up
def google(self, ctx, *, query):
		await ctx.channel.trigger_typing()
		try:
			await self.bot.loop.run_in_executor(None, func=functools.partial(self.assist, ctx.author.id, query))
		except Exception as e:
			if 'text_query too long.' in str(e):
				return await ctx.error(f'That query is too long. Try something shorter')
			return await ctx.error(f'Something went wrong.')
		if ctx.author.id not in self.responses:
			return await ctx.send(f'<a:okaygoogle:661951491082551306> Something went wrong. Try again later')
		async with get_session(self.service, self.browser) as session:
			await session.set_window_size(1920, 1080)
			sub = 'devapi' if self.bot.dev else 'api'
			await session.get(f'https://{sub}.gaminggeek.dev/assist/{ctx.author.id}')
			try:
				await session.execute_script('document.body.style.backgroundImage = \'url("https://picsum.photos/1920/1080")\';')
				namere = '<div class=\"show_text_content\">Your name is .*\.<\/div>'
				namesub = f'<div class=\'show_text_content\'>Your name is {ctx.author.name}.</div>'
				await session.execute_script(f'document.body.innerHTML = document.body.innerHTML.replace(/{namere}/gm, "{namesub}");')
			except Exception:
				pass
				# await ctx.error('script did an oopsie')
			await asyncio.sleep(1.5)
			await ctx.send(file=discord.File((await session.get_screenshot()), filename='google.png'))
			return await session.close()
		return await ctx.error('If you\'re seeing this, something went wrong I guess ¯\_(ツ)_/¯') 
Example #20
Source File: dbltools.py    From predacogs with MIT License 5 votes vote down vote up
def dblwidget(self, ctx: commands.Context, *, bot: discord.User):
        """
        Send the widget of a chosen bot on Top.gg.

        `bot`: Can be a mention or ID of a bot.
        """
        if bot is None:
            return await ctx.send(_("This is not a valid Discord user."))
        if not bot.bot:
            return await ctx.send(_("This is not a bot user, please try again with a bot."))

        async with ctx.typing():
            try:
                await self.dbl.get_guild_count(bot.id)
                url = await self.dbl.get_widget_large(bot.id)
            except dbl.NotFound:
                return await ctx.send(_("That bot isn't validated on Top.gg."))
            except dbl.errors.HTTPException as error:
                log.error("Failed to fetch Top.gg API.", exc_info=error)
                return await ctx.send(_("Failed to contact Top.gg API. Please try again later."))
            file = await download_widget(self.session, url)
            em = discord.Embed(
                color=discord.Color.blurple(),
                description=bold(_("[Top.gg Page]({})")).format(f"https://top.gg/bot/{bot.id}"),
            )
            if file:
                filename = f"{bot.id}_topggwidget_{int(time.time())}.png"
                em.set_image(url=f"attachment://{filename}")
                return await ctx.send(file=discord.File(file, filename=filename), embed=em)
            em.set_image(url=url)
            return await ctx.send(embed=em) 
Example #21
Source File: imagegen.py    From bot with MIT License 5 votes vote down vote up
def makeameme(self, ctx, image: typing.Union[Member, str] = None, *, text: str = None):
		if ctx.message.attachments:
			if isinstance(image, discord.Member):
				image = image.name
			text = f'{image} {text or ""}'
			image = ctx.message.attachments[0].url
		if not image:
			return await ctx.error('You need to provide an image')
		if isinstance(image, discord.Member):
			image = str(image.avatar_url_as(format='png'))
		image = urllib.parse.quote(image.strip('<>'))
		if 'cdn.discordapp.com' in image and ('gif' in image or 'webp' in image):
			image = image.replace('gif', 'png').replace('webp', 'png')
		if '.gif' in image:
			return await ctx.error('Animated images are not supported!')
		if not text:
			return await ctx.error('You must provide text seperated by **|**')
		if len(text.split('|')) != 2:
			return await ctx.error('You must provide text seperated by **|**')
		text = urllib.parse.quote(text).split('%7C')
		async with aiohttp.ClientSession(
			headers={'Authorization': self.bot.config["aeromeme"]}
		) as s:
			imgraw = await s.get(f'https://memes.aero.bot/api/meme?avatar1={image}&top_text={text[0]}&bottom_text={text[1]}')
			if imgraw.status != 200:
				return await ctx.error('Something went wrong...')
			imgraw = await imgraw.read()
			await s.close()
		file = discord.File(BytesIO(imgraw), f'spicymeme.png')
		await ctx.send(file=file) 
Example #22
Source File: dbltools.py    From predacogs with MIT License 5 votes vote down vote up
def dblwidget(self, ctx: commands.Context, *, bot: discord.User):
        """
        Send the widget of a chosen bot on Top.gg.

        `bot`: Can be a mention or ID of a bot.
        """
        if bot is None:
            return await ctx.send(_("This is not a valid Discord user."))
        if not bot.bot:
            return await ctx.send(_("This is not a bot user, please try again with a bot."))

        async with ctx.typing():
            try:
                await self.dbl.get_guild_count(bot.id)
                url = await self.dbl.get_widget_large(bot.id)
            except dbl.NotFound:
                return await ctx.send(_("That bot isn't validated on Top.gg."))
            except dbl.errors.HTTPException as error:
                log.error("Failed to fetch Top.gg API.", exc_info=error)
                return await ctx.send(_("Failed to contact Top.gg API. Please try again later."))
            file = await download_widget(self.session, url)
            em = discord.Embed(
                color=discord.Color.blurple(),
                description=bold(_("[Top.gg Page]({})")).format(f"https://top.gg/bot/{bot.id}"),
            )
            if file:
                filename = f"{bot.id}_topggwidget_{int(time.time())}.png"
                em.set_image(url=f"attachment://{filename}")
                return await ctx.send(file=discord.File(file, filename=filename), embed=em)
            em.set_image(url=url)
            return await ctx.send(embed=em) 
Example #23
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def facedesk(self, ctx):
        """when someone is REALLY retarded"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/facedesk.gif")) 
Example #24
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def facepalm(self, ctx):
        """when someone is retarded"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/facepalm.gif")) 
Example #25
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def weirdshit(self, ctx):
        """WHY ARE YOU POSTING WEIRD SHIT?!?!?!"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/weirdshit.jpg")) 
Example #26
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def repost(self, ctx):
        """It's just a repost smh"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/repost.gif")) 
Example #27
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def lewd(self, ctx):
        """WOAH THERE THAT'S LEWD!"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/lewd.gif")) 
Example #28
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def heckoff(self, ctx):
        """heck off fools"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/heckoff.png")) 
Example #29
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def filth(self, ctx):
        """THIS IS ABSOLUTELY FILTHY!"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/filth.gif")) 
Example #30
Source File: reactions.py    From RubyRoseBot with Mozilla Public License 2.0 5 votes vote down vote up
def unflip(self, ctx):
        # I hope this unicode doesn't break
        """┬─┬ ノ( ゜-゜ノ)"""
        await ctx.channel.trigger_typing()
        await ctx.send(file=discord.File("assets/imgs/reactions/unflip.gif"))