本文整理汇总了Python中discord.Client.send_file方法的典型用法代码示例。如果您正苦于以下问题:Python Client.send_file方法的具体用法?Python Client.send_file怎么用?Python Client.send_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord.Client
的用法示例。
在下文中一共展示了Client.send_file方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prank
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def prank(client: discord.Client, message: discord.Message, phrase: Annotate.CleanContent="IT'S A"):
""" Prank! """
phrase = phrase.upper()
# Initialize the image and font
image_text = Image.new("RGBA", image_base.size, (255, 255, 255, 0))
image_font = ImageFont.truetype(prank_path + "American Captain.ttf", 50)
image_context = ImageDraw.Draw(image_text)
# Set width and height and scale down when necessary
width, height = image_context.textsize(phrase, image_font)
font_size = 50
if width > image_width:
scaled_font = None
while width > image_width:
scaled_font = ImageFont.truetype(prank_path + "American Captain.ttf", font_size)
width, height = image_context.textsize(phrase, scaled_font)
font_size -= 1
image_font = scaled_font
# Set x and y coordinates for centered text
x = (image_width - width) / 2
y = (image_height - height / 2) - image_height / 1.3
# Draw border
shadow_offset = font_size // 25
image_context.text((x - shadow_offset, y), phrase, font=image_font, fill=(0, 0, 0, 255))
image_context.text((x + shadow_offset, y), phrase, font=image_font, fill=(0, 0, 0, 255))
image_context.text((x, y - shadow_offset), phrase, font=image_font, fill=(0, 0, 0, 255))
image_context.text((x, y + shadow_offset), phrase, font=image_font, fill=(0, 0, 0, 255))
# Draw text
image_context.text((x, y), phrase, font=image_font, fill=(255, 255, 255, 255))
# Combine the base image with the font image
image = Image.alpha_composite(image_base, image_text)
# Upload the image
buffer = BytesIO()
image.save(buffer, "PNG")
buffer.seek(0)
yield from client.send_file(message.channel, buffer, filename="pranked.png")
示例2: on_ready
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def on_ready(client: discord.Client):
while not client.is_closed:
try:
yield from asyncio.sleep(update_interval)
# Go through all set channels (if they're online on discord) and update their status
for member_id, channel in twitch_channels.data["channels"].items():
member = discord.utils.find(lambda m: m.status is not discord.Status.offline and m.id == member_id,
client.get_all_members())
if member:
with aiohttp.ClientSession() as session:
response = yield from session.get(twitch_api + "/streams/" + channel)
if response:
json = yield from response.json() if response.status == 200 else {}
else:
json = {}
stream = json.get("stream")
if member_id in live_channels:
if not stream:
live_channels.pop(member_id)
else:
if stream:
live_channels[member_id] = stream
# Tell every mutual channel between the streamer and the bot that streamer started streaming
for server in client.servers:
if member in server.members:
m = "{0} went live at {1[channel][url]}.\n" \
"**{1[channel][display_name]}**: {1[channel][status]}\n" \
"*Playing {1[game]}*".format(member.mention, stream)
asyncio.async(client.send_message(server, m))
preview = yield from download_file(stream["preview"]["medium"])
yield from client.send_file(server, preview, filename="preview.jpg")
# Wait a second before sending a new server request
yield from asyncio.sleep(1)
except:
print_exc()
示例3: resize
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def resize(client: discord.Client, message: discord.Message,
url: str, resolution: parse_resolution, *options, extension: str=None):
""" Resize an image with the given resolution formatted as `<width>x<height>`
with an optional extension. """
# Make sure the URL is valid
try:
image_bytes, headers = yield from utils.download_file(url)
except ValueError:
yield from client.say(message, "The given URL is invalid.")
return
match = extension_regex.search(headers["CONTENT-TYPE"])
assert match, "The given url is not an image."
# Create some metadata
image_format = extension or match.group("ext")
# Set the image upload extension
extension = image_format.lower()
if extension.lower() == "jpeg":
extension = "jpg"
if image_format.lower() == "jpg":
image_format = "JPEG"
filename = "{}.{}".format(message.author.display_name, extension)
# Open the image in Pillow
image = Image.open(BytesIO(image_bytes))
image = image.resize(resolution, Image.NEAREST if "-nearest" in options else Image.ANTIALIAS)
# Upload the image
buffer = BytesIO()
try:
image.save(buffer, image_format)
except KeyError as e:
yield from client.say(message, "Image format `{}` is unsupported.".format(e))
return
except Exception as e:
yield from client.say(message, str(e) + ".")
return
buffer.seek(0)
yield from client.send_file(message.channel, buffer, filename=filename)
示例4: osu
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def osu(client: discord.Client, message: discord.Message, member: Annotate.Member=Annotate.Self):
""" Handle osu! commands.
When your user is linked, this plugin will check if you are playing osu!
(your profile would have `playing osu!`), and send updates whenever you set a
new top score. """
# Make sure the member is assigned
assert member.id in osu_config.data["profiles"], "No osu! profile assigned to **{}**!".format(member.name)
user_id = osu_config.data["profiles"][member.id]
# Set the signature color to that of the role color
color = "pink" if member.color == discord.Color.default() \
else "#{0:02x}{1:02x}{2:02x}".format(*member.color.to_tuple())
# Download and upload the signature
signature, _ = yield from utils.download_file("http://lemmmy.pw/osusig/sig.php",
colour=color, uname=user_id, pp=True,
countryrank=True, xpbar=True, mode=get_mode(member.id).value)
yield from client.send_file(message.channel, signature, filename="sig.png")
yield from client.say(message, "<https://osu.ppy.sh/u/{}>".format(user_id))
示例5: on_command
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def on_command(client: discord.Client, message: discord.Message, args: list):
if args[0] == "!prank":
name = "IT'S A"
# Set the name and convert any mention to name (this ignores punctuation and converts "@PC," to "PC")
if len(args) > 1 and len(message.clean_content) < 200:
name_list = []
for arg in args[1:]:
steps = 3 if len(args) == 2 else 1
member = client.find_member(message.server, arg, steps=steps)
if member:
name_list.append(member.name)
else:
channel = client.find_channel(message.server, arg, steps=0)
if channel:
name_list.append(channel.name)
else:
name_list.append(arg)
name = " ".join(name_list)
name = name.upper()
# Initialize the image anhd font
image_text = Image.new("RGBA", image_base.size, (255, 255, 255, 0))
image_font = ImageFont.truetype(prank_path + "American Captain.ttf", 50)
image_context = ImageDraw.Draw(image_text)
# Set width and height and scale down when necessary
width, height = image_context.textsize(name, image_font)
font_size = 50
if width > image_width:
scaled_font = None
while width > image_width:
scaled_font = ImageFont.truetype(prank_path + "American Captain.ttf", font_size)
width, height = image_context.textsize(name, scaled_font)
font_size -= 1
image_font = scaled_font
# Set x and y coordinates for centered text
x = (image_width - width) / 2
y = (image_height - height / 2) - image_height / 1.3
# Draw border
shadow_offset = font_size // 25
image_context.text((x - shadow_offset, y), name, font=image_font, fill=(0, 0, 0, 255))
image_context.text((x + shadow_offset, y), name, font=image_font, fill=(0, 0, 0, 255))
image_context.text((x, y - shadow_offset), name, font=image_font, fill=(0, 0, 0, 255))
image_context.text((x, y + shadow_offset), name, font=image_font, fill=(0, 0, 0, 255))
# Draw text
image_context.text((x, y), name, font=image_font, fill=(255, 255, 255, 255))
# Combine the base image with the font image
image = Image.alpha_composite(image_base, image_text)
# Save and send the image
image.save(prank_path + "pranked.png")
yield from client.send_file(message.channel, prank_path + "pranked.png")
示例6: greater
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def greater(client: discord.Client, message: discord.Message, text: Annotate.CleanContent):
""" Gives a **huge** version of emojies. """
# Convert the given text to characters
unicode = [hex(ord(c))[2:] for c in text]
# Parse all unicode and load the emojies
parsed_emoji = []
combined = False
for i, char in enumerate(unicode):
if len(parsed_emoji) > max_emoji:
break
if combined:
combined = False
continue
# Some emojies use two unicode characters, so we try to parse these first
if len(unicode) > (i + 1):
name = "{}-{}".format(char, unicode[i + 1])
if name in emoji:
if name not in emoji_cache:
converted = cairosvg.svg2png(emoji[name])
emoji_cache[name] = converted
else:
converted = emoji_cache[name]
parsed_emoji.append(converted)
combined = True
continue
# At this point we only need one character, and we pretty much do the entire process over again
# (I know, this code is pretty lame)
if char in emoji:
if char not in emoji_cache:
converted = cairosvg.svg2png(emoji[char])
emoji_cache[char] = converted
else:
converted = emoji_cache[char]
parsed_emoji.append(converted)
assert parsed_emoji, "I couldn't find any emoji in that text of yours."
# We now want to combine the images if there are multiples
# If there is no need to combine the images, send just the one
if len(parsed_emoji) == 1:
yield from client.send_file(message.channel, parsed_emoji[0], filename="emoji.png")
return
image_objects = [Image.open(BytesIO(b)) for b in parsed_emoji]
width, height = size * len(image_objects), size
# Stitch all the images together
image = Image.new("RGBA", (width, height))
for i, image_object in enumerate(image_objects):
image.paste(image_object, box=(i * size, 0))
# Resize the image so that the width is no higher than 2048, but only for each factor
# we go higher than the max_width
if width > max_width:
scale = 1 / ((width - 1) // max_width + 1)
image = image.resize((int(width * scale), int(height * scale)), Image.ANTIALIAS)
# Upload the stitched image
buffer = BytesIO()
image.save(buffer, "PNG")
buffer.seek(0)
yield from client.send_file(message.channel, buffer, filename="emojies.png")
示例7: pokedex_
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def pokedex_(client: discord.Client, message: discord.Message, name_or_id: Annotate.LowerCleanContent):
""" Display some information of the given pokémon. """
# Do some quick replacements for flexible parsing
name_or_id = name_or_id.strip()
if name_or_id.startswith("#"):
name_or_id = name_or_id.replace("#", "")
if " " in name_or_id:
if "♀" in name_or_id or "♀" in name_or_id or name_or_id.endswith("f") or name_or_id.endswith("m"):
name_or_id = name_or_id.replace(" ", "-").replace("♂", "m").replace("♀", "f")
else:
name_or_id = name_or_id.replace(" ", "")
# Get the requested pokemon name
name = name_or_id
try:
pokemon_id = int(name_or_id)
except ValueError:
# See if there's a pokemon with the locale name formatted like the given name
for pokemon in pokedex.values():
if pokemon["locale_name"].lower() == name:
name = pokemon["name"]
break
# Correct the name if it is very close to an existing pokemon and there's only one close match
matches = get_close_matches(name, pokedex.keys(), n=2, cutoff=0.8)
if matches and len(matches) == 1:
name = matches[0]
assert name in pokedex, "There is no pokémon called **{}** in my pokédex!\nPerhaps you meant: `{}`?".format(
name, ", ".join(get_close_matches(name, pokedex.keys(), cutoff=0.5)))
else:
name = id_to_name(pokemon_id)
assert name is not None, "There is no pokémon with ID **#{:03}** in my pokédex!".format(pokemon_id)
# Get the server's scale factor
if not message.channel.is_private \
and message.server.id in pokedex_config.data and "scale-factor" in pokedex_config.data[message.server.id]:
scale_factor = pokedex_config.data[message.server.id]["scale-factor"]
else:
scale_factor = default_scale_factor
# Assign our pokemon
pokemon = pokedex[name]
# Assign the sprite to use
if pokemon["id"] in sprites:
sprite = sprites[pokemon["id"]]
else:
sprite = sprites[0]
# Resize (if PIL is enabled) and upload the sprite
if resize and not round(scale_factor, 2) == 1:
sprite = resize_sprite(sprite, scale_factor)
yield from client.send_file(message.channel, sprite, filename="{}.png".format(name))
# Format Pokemon GO specific info
pokemon_go_info = ""
if "evolution_cost" in pokemon:
pokemon_go_info += "Evolution cost: `{} {} Candy` ".format(
pokemon["evolution_cost"], egg_name(pokemon["evolution"]))
if "hatches_from" in pokemon:
if pokemon_go_info:
pokemon_go_info += "\n"
pokemon_go_info += "Hatches from: `{}km Egg` ".format(pokemon["hatches_from"])
# Format the message
formatted_message = (
"**#{id:03} {upper_name} - GEN {generation}**\n"
"Weight: `{weight}kg` Height: `{height}m`\n"
"Type: `{type}`\n"
"**{genus} Pokémon**\n"
"{pokemon_go}"
"```\n{description}```"
"**EVOLUTION**: {formatted_evolution}"
).format(
upper_name=pokemon["locale_name"].upper(),
type=format_type(pokemon["types"]),
formatted_evolution=" **->** ".join(" **/** ".join(pokedex[name]["locale_name"].upper() for name in names)
for names in pokemon["evolution"]),
pokemon_go=pokemon_go_info,
**pokemon
)
yield from client.say(message, formatted_message)
示例8: on_command
# 需要导入模块: from discord import Client [as 别名]
# 或者: from discord.Client import send_file [as 别名]
def on_command(client: discord.Client, message: discord.Message, args: list):
if args[0] == "!osu":
m = "Please see `!help osu`."
if len(args) > 1:
# Assign an osu! profile to your name or remove it
if args[1] == "set":
if len(args) > 2:
profile = " ".join(args[2:])
params = {
"k": osu.data["key"],
"u": profile
}
with aiohttp.ClientSession() as session:
response = yield from session.get(osu_api + "get_user", params=params)
user = yield from response.json() if response.status == 200 else []
if user:
# Clear the scores when changing user
if message.author.id in osu_tracking:
osu_tracking.pop(message.author.id)
osu.data["profiles"][message.author.id] = user[0]["user_id"]
osu.save()
m = "Set your osu! profile to `{}`.".format(user[0]["username"])
else:
m = "User {} does not exist.".format(profile)
else:
if message.author.id in osu.data["profiles"]:
osu.data["profiles"].pop(message.author.id)
osu.save()
m = "osu! profile unlinked."
# Return the member's or another member's osu! profile as a link and upload a signature
elif args[1] == "get":
if len(args) > 2:
member = client.find_member(message.server, " ".join(args[2:]))
else:
member = message.author
if member:
if member.id in osu.data["profiles"]:
user_id = osu.data["profiles"][member.id]
# Set the signature color to that of the role color
color = "pink" if member.color is discord.Color.default() else member.color
# Download and upload the signature
params = {
"colour": color,
"uname": user_id,
"pp": 1,
"countryrank": True,
"xpbar": True
}
signature = yield from download_file("http://lemmmy.pw/osusig/sig.php", **params)
yield from client.send_file(message.channel, signature, filename="sig.png")
m = "https://osu.ppy.sh/u/{}".format(user_id)
else:
m = "No osu! profile assigned to {}!".format(member.name)
else:
m = "Found no such member."
elif args[1] == "test":
beatmap_search = yield from get_beatmaps(b=713442)
beatmap = get_beatmap(beatmap_search)
m = "```" + beatmap + "```"
# # Set or get the osu! notify channel
# elif args[1] == "notify-channel":
# if message.author.permissions_in(message.channel).manage_server:
# if len(args) > 2:
# channel = client.find_channel(message.server, args[2])
#
# if channel:
# osu.data["notify-channel"][message.server.id] = channel.id
# osu.save()
# m = "Notify channel set to {}.".format(channel.mention)
# else:
# if "notify-channel" in osu.data:
# twitch_channel = client.get_channel(osu.data["notify-channel"])
# if twitch_channel:
# m = "Twitch notify channel is {}.".format(twitch_channel)
# else:
# m = "The twitch notify channel no longer exists!"
# else:
# m = "A twitch notify channel has not been set."
# else:
# m = "You need `Manage Server` to use this command."
yield from client.send_message(message.channel, m)