How to use the discord.File function in discord

To help you get started, we’ve selected a few discord examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MaT1g3R / YasenBaka / core / api_consumer.py View on Github external
    async def wolke_image(self, type_: str) -> Union[str, File]:
        """
        Get a random image by type from wolke api.
        :param type_: the type of the image.
        :return: the url to the image.
        """
        url = 'https://staging-api.ram.moe/images/random?'
        header = {'Authorization': self.config.wolke_api}
        params = {'type': type_}
        js = await self.get_json(
            'Wolke', url, params,
            headers=header
        )
        if isinstance(js, dict):
            url = js.get('url', None)
            if not url:
                return self.sorry
github BlobEmoji / queuebot / queuebot / cogs / queue / __init__.py View on Github external
interval = emoji_image.info.get("duration")

        for _ in range(600):  # never render more than 600 frames
            frame_listing.append(self.generate_test_frame(emoji_image))

            try:
                emoji_image.seek(emoji_image.tell() + 1)
            except EOFError:
                break

        initial_frame = frame_listing.pop(0)

        if frame_listing:
            initial_frame.save(buffer, "gif", duration=interval, save_all=True, append_images=frame_listing, loop=0)
            buffer.seek(0)
            return discord.File(filename="test.gif", fp=buffer)
        else:
            initial_frame.save(buffer, "png")
            buffer.seek(0)
            return discord.File(filename="test.png", fp=buffer)
github sx4-discord-bot / Sx4-Python / Sx4 / cogs / owner.py View on Github external
with open("avatar.png", "wb") as f:
                    f.write(requests.get(member.avatar_url).content)
                image = Image.open("avatar.png").convert("RGBA")
                image = image.resize((pixels, pixels))
                background.paste(image, (x, y))
                x += pixels
                if x >= width:
                    y += pixels
                    x = 0
                print("Successful") 
            except Exception as e:
                print(e)
        background.save("collage.png")
        t2 = time.perf_counter()
        try:
            await ctx.send(content="Executed in **{}ms**".format(round((t2-t1)*1000)), file=discord.File("collage.png", "collage.png"))
        except:
            await ctx.send("Executed in **{}ms**\n\nImage saved in hosters files".format(round((t2-t1)*1000)))
            return os.remove("avatar.png")
        try:
            os.remove("collage.png")
            os.remove("avatar.png")
        except: 
            pass
github aikaterna / aikaterna-cogs / blurplefy / blurplefy.py View on Github external
# 1250x1250 = 1562500
        maxpixelcount = 1562500

        if impixels > maxpixelcount:
            downsizefraction = math.sqrt(maxpixelcount / impixels)
            im = resizeimage.resize_width(im, (imsize[0] * downsizefraction))
            imsize = list(im.size)
            impixels = imsize[0] * imsize[1]
            await ctx.send(
                "{}, image resized smaller for easier processing.".format(
                    ctx.message.author.display_name
                )
            )

        image = self.blurple_imager(im, imsize)
        image = discord.File(fp=image, filename="image.png")

        blurplenesspercentage = round(((nooftotalpixels / noofpixels) * 100), 2)
        percentblurple = round(((noofblurplepixels / noofpixels) * 100), 2)
        percentdblurple = round(((noofdarkblurplepixels / noofpixels) * 100), 2)
        percentwhite = round(((noofwhitepixels / noofpixels) * 100), 2)

        embed = discord.Embed(title="", colour=0x7289DA)
        embed.add_field(
            name="Total amount of Blurple", value="{}%".format(blurplenesspercentage), inline=False
        )
        embed.add_field(
            name="Blurple (rgb(114, 137, 218))", value="{}%".format(percentblurple), inline=True
        )
        embed.add_field(
            name="White (rgb(255, 255, 255))", value="{}\%".format(percentwhite), inline=True
        )
github FoglyOgly / Meowth / meowth / exts / dev / dev_cog.py View on Github external
async def exporttable(self, ctx, table_name):
        """Exports the current server's gyms to a CSV file."""
        f = await self.csv_from_table(table_name)
        if not f:
            return await ctx.send('Table not found')
        to_send = discord.File(f, filename=f'{table_name}.csv')
        await ctx.send(file=to_send)
github TrustyJAID / Trusty-cogs / crabrave / crabrave.py View on Github external
if not await self.check_font_file():
            return await ctx.send("I couldn't download the font file.")
        if len(t) != 2:
            return await ctx.send("You must submit exactly two strings split by comma")
        if (not t[0] and not t[0].strip()) or (not t[1] and not t[1].strip()):
            return await ctx.send("Cannot render empty text")
        fake_task = functools.partial(self.make_crab, t=t, u_id=ctx.message.id)
        task = self.bot.loop.run_in_executor(None, fake_task)
        async with ctx.typing():
            try:
                await asyncio.wait_for(task, timeout=300)
            except asyncio.TimeoutError:
                log.error("Error generating crabrave video", exc_info=True)
                return
        fp = cog_data_path(self) / f"{ctx.message.id}crabrave.mp4"
        file = discord.File(str(fp), filename="crabrave.mp4")
        try:
            await ctx.send(files=[file])
        except Exception:
            log.error("Error sending crabrave video", exc_info=True)
            pass
        try:
            os.remove(fp)
        except Exception:
            log.error("Error deleting crabrave video", exc_info=True)
github mdiller / MangoByte / cogs / dotastats.py View on Github external
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)
github reswitched / robocop-ng / cogs / admin.py View on Github external
async def fetchdata(self, ctx):
        """Returns data files"""
        data_files = [discord.File(fpath) for fpath in self.bot.wanted_jsons]
        await ctx.send("Here you go:", files=data_files)
github CarlGroth / Carl-Bot / cogs / ckc.py View on Github external
output_buffer = BytesIO(file)
        async with aiohttp.ClientSession() as session:
            async with session.post(URL + '/api/v2.3/photos', data={'file': output_buffer}, headers={'User-Agent': USER_AGENT, 'X-FaceApp-DeviceID': DEVICE_ID}) as r:
                code = await r.json()
                if "code" in code:
                    code = code['code']
                elif "err" in code:
                    return await ctx.send("Error: {}".format(code["err"]["code"]))
                else:
                    return await ctx.send("Is this what's causing 0 byte uploads? {}".format(code))
        async with aiohttp.ClientSession() as session:
            async with session.get(URL + '/api/v2.3/photos/{}/filters/{}?cropped=true'.format(code, face_filter),
                                   headers={'User-Agent': USER_AGENT, 'X-FaceApp-DeviceID': DEVICE_ID}) as r:
                face = await r.read()
        send_me = BytesIO(face)
        await ctx.send(file=discord.File(fp=send_me, filename="hehe.png"))
github Rapptz / RoboDanny / cogs / stats.py View on Github external
embed = discord.Embed(title='Summary', colour=discord.Colour.green())
        embed.set_footer(text='Since').timestamp = datetime.datetime.utcnow() - datetime.timedelta(days=days)

        top_ten = '\n'.join(f'{command}: {uses}' for command, uses in records[:10])
        bottom_ten = '\n'.join(f'{command}: {uses}' for command, uses in records[-10:])
        embed.add_field(name='Top 10', value=top_ten)
        embed.add_field(name='Bottom 10', value=bottom_ten)

        unused = ', '.join(name for name, uses in as_data if uses == 0)
        if len(unused) > 1024:
            unused = 'Way too many...'

        embed.add_field(name='Unused', value=unused, inline=False)

        await ctx.send(embed=embed, file=discord.File(io.BytesIO(render.encode()), filename='full_results.txt'))