當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。