当前位置: 首页>>代码示例>>Python>>正文


Python discord.File方法代码示例

本文整理汇总了Python中discord.File方法的典型用法代码示例。如果您正苦于以下问题:Python discord.File方法的具体用法?Python discord.File怎么用?Python discord.File使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord的用法示例。


在下文中一共展示了discord.File方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: send_embed

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:python-discord,项目名称:bot,代码行数:23,代码来源:wolfram.py

示例2: spoiler

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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']) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:22,代码来源:spoiler.py

示例3: playertoken

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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() 
开发者ID:avrae,项目名称:avrae,代码行数:20,代码来源:sheetManager.py

示例4: print_match_stats

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:mdiller,项目名称:MangoByte,代码行数:27,代码来源:dotastats.py

示例5: opendota

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:mdiller,项目名称:MangoByte,代码行数:23,代码来源:dotastats.py

示例6: emoticon

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:mdiller,项目名称:MangoByte,代码行数:22,代码来源:dotabase.py

示例7: herotable

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:mdiller,项目名称:MangoByte,代码行数:26,代码来源:dotabase.py

示例8: getcolour

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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 
开发者ID:appu1232,项目名称:Discord-Selfbot,代码行数:18,代码来源:utility.py

示例9: async_upload

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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. 
开发者ID:nigel,项目名称:DiscordStorage,代码行数:21,代码来源:core.py

示例10: deepfry

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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.') 
开发者ID:Flame442,项目名称:FlameCogs,代码行数:26,代码来源:deepfry.py

示例11: nuke

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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.') 
开发者ID:Flame442,项目名称:FlameCogs,代码行数:26,代码来源:deepfry.py

示例12: color

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:23,代码来源:color.py

示例13: randomcolor

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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') 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:19,代码来源:randomcolor.py

示例14: upload_to_privatebin_if_too_long

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:19,代码来源:file_upload_hook.py

示例15: df

# 需要导入模块: import discord [as 别名]
# 或者: from discord import File [as 别名]
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) 
开发者ID:FireDiscordBot,项目名称:bot,代码行数:21,代码来源:imagegen.py


注:本文中的discord.File方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。