def pat(self, context, member: discord.Member):
"""Pat your senpai/waifu!"""
author = context.message.author.mention
mention = member.mention
pat = "**{0} got patted by {1}!**"
choices = ['http://i.imgur.com/10VrpFZ.gif', 'http://i.imgur.com/x0u35IU.gif', 'http://i.imgur.com/0gTbTNR.gif', 'http://i.imgur.com/hlLCiAt.gif', 'http://i.imgur.com/sAANBDj.gif']
image = random.choice(choices)
embed = discord.Embed(description=pat.format(mention, author), colour=discord.Colour.blue())
embed.set_image(url=image)
await self.bot.say(embed=embed)
python类Embed()的实例源码
def kiss(self, context, member: discord.Member):
"""Kiss your senpai/waifu!"""
author = context.message.author.mention
mention = member.mention
kiss = "**{0} gave {1} a kiss!**"
choices = ['http://i.imgur.com/0D0Mijk.gif', 'http://i.imgur.com/TNhivqs.gif', 'http://i.imgur.com/3wv088f.gif', 'http://i.imgur.com/7mkRzr1.gif', 'http://i.imgur.com/8fEyFHe.gif']
image = random.choice(choices)
embed = discord.Embed(description=kiss.format(author, mention), colour=discord.Colour.blue())
embed.set_image(url=image)
await self.bot.say(embed=embed)
def hug(self, context, member: discord.Member):
"""Hug your senpai/waifu!"""
author = context.message.author.mention
mention = member.mention
hug = "**{0} gave {1} a hug!**"
choices = ['http://i.imgur.com/sW3RvRN.gif', 'http://i.imgur.com/gdE2w1x.gif', 'http://i.imgur.com/zpbtWVE.gif', 'http://i.imgur.com/ZQivdm1.gif', 'http://i.imgur.com/MWZUMNX.gif']
image = random.choice(choices)
embed = discord.Embed(description=hug.format(author, mention), colour=discord.Colour.blue())
embed.set_image(url=image)
await self.bot.say(embed=embed)
def _status_lottery(self, ctx):
"""Check if a lottery is active"""
author = ctx.message.author
settings = self.check_server_settings(author.server)
if settings["Config"]["Active"]:
ld = settings["Config"]["Current Loadout"]
timer = settings["Loadouts"][ld]["Timer"]
if timer == 0:
remaining = "no time limit"
else:
counter = settings["Config"]["Tracker"]
seconds = timer - (datetime.utcnow() - parser.parse(counter)).seconds
remaining = "{} remaining".format(self.time_formatter(seconds))
winners = settings["Loadouts"][ld]["Winners"]
entry_limit = settings["Loadouts"][ld]["Limit"]
dos = settings["Loadouts"][ld]["DOS"]
role_req = settings["Loadouts"][ld]["Role"]
prize = settings["Loadouts"][ld]["Prize"]
footer = "There are currently {} users in the lottery.".format(len(settings["Players"]))
if author.id in settings["Players"]:
desc = "You are currently in the lottery."
else:
desc = "You have **not** entered into this lottery yet."
embed = discord.Embed(title="Loadout {}".format(ld), description=desc, color=0x50bdfe)
embed.set_author(name="Lottery System 3.0")
embed.add_field(name="Prize", value=prize, inline=True)
embed.add_field(name="Possible Winners", value=winners, inline=True)
embed.add_field(name="Role", value=role_req, inline=True)
embed.add_field(name="Limit", value=entry_limit, inline=True)
embed.add_field(name="Time Remaining", value=remaining, inline=True)
embed.add_field(name="Days on Server Required", value=dos, inline=True)
embed.set_footer(text=footer)
await self.bot.say(embed=embed)
else:
await self.bot.say("There aren't any lotteries running on this server right now.")
def _view_lottery(self, ctx, loadout: int):
"""View the parameters set for a loadout"""
if loadout not in [0, 1, 2, 3, 4, 5]:
return await self.bot.say("Invalid loadout. Must be 0-5.")
server = ctx.message.server
settings = self.check_server_settings(server)
loadout = str(loadout)
if not self.slot_checker(settings, loadout):
return await self.bot.say("The selected loadout is empty.")
timer = settings["Loadouts"][loadout]["Timer"]
if timer == 0:
time_fmt = "no time limit"
else:
time_fmt = self.time_formatter(timer)
winners = settings["Loadouts"][loadout]["Winners"]
entry_limit = settings["Loadouts"][loadout]["Limit"]
dos = settings["Loadouts"][loadout]["DOS"]
role_req = settings["Loadouts"][loadout]["Role"]
prize = settings["Loadouts"][loadout]["Prize"]
start_msg = settings["Loadouts"][loadout]["Start Message"]
end_msg = settings["Loadouts"][loadout]["End Message"]
embed = discord.Embed(title="Loadout {}".format(loadout), color=0x50bdfe)
embed.add_field(name="Prize", value=prize, inline=True)
embed.add_field(name="Number of Winners", value=winners, inline=True)
embed.add_field(name="Role", value=role_req, inline=True)
embed.add_field(name="Entry Limit", value=entry_limit, inline=True)
embed.add_field(name="Timer", value=time_fmt, inline=True)
embed.add_field(name="Days on Server Required", value=dos, inline=True)
embed.add_field(name="Start Message", value=start_msg, inline=True)
embed.add_field(name="End Message", value=end_msg, inline=True)
await self.bot.say(embed=embed)
def send_profile(self, user, author_col, user_col, user_data, user_name, url, cmd):
if author_col == "SELF":
share = ['Not Applicable']
different = ['Not Applicable']
elif author_col:
intersect = user_col.intersection(author_col)
difference = author_col.difference(user_col)
share = random.sample(intersect, len(intersect) if len(intersect) < 5 else 5)
if not share:
share = ["Nothing Mutual"]
different = random.sample(difference, len(difference) if len(difference) < 5 else 5)
if not different:
different = ["Nothing different"]
else:
share = ["Author's MAL not set"]
different = ["Author's MAL not set"]
if cmd == "anime":
medium = "Watching"
emojis = [":film_frames:", ":vhs:", ":octagonal_sign:"]
else:
medium = "Reading"
emojis = [":book:", ":books:", ":bookmark:"]
link = "https://myanimelist.net/animelist/{}".format(user_name)
description = ("**{}**\n[{}]({})\nTotal {}: "
"{}".format(user.name, user_name, link, cmd.title(), len(user_col)))
embed = discord.Embed(colour=0x0066FF, description=description)
embed.title = "My Anime List Profile"
embed.set_thumbnail(url="https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256."
"png")
embed.add_field(name=":calendar_spiral: Days Spent {}".format(medium), value=user_data[4],
inline=False)
embed.add_field(name="{} {}".format(emojis[0], medium), value=user_data[0])
embed.add_field(name="{} Completed".format(emojis[1]), value=user_data[1])
embed.add_field(name="{} On Hold".format(emojis[2]), value=user_data[2])
embed.add_field(name=":wastebasket: Dropped", value=user_data[3])
embed.add_field(name=":link: Five Shared", value='\n'.join(share), inline=False)
embed.add_field(name=":trident: Five Different", value='\n'.join(different))
await self.bot.say(embed=embed)
def _moves_pokemon(self, *, poke: str):
"""Search for a Pokémon's moveset
If the generation specified is not found, it will default to 7
Args:
poke: variable length string
Returns:
Tabular output of Pokémon data.
Raises:
AttributeError: Pokémon not found.
Examples:
Numbers: [p]pokemon moves charizard-4
Alolan: [p]pokemon moves geodude-alola
"""
moves = self.search_csv(poke.lower(), 'data/pokedex/Moves.csv', data_type='m')
try:
table = tabulate(moves.moves, headers=['Level', 'Moves', 'Type', 'Power', 'Accuracy'])
except AttributeError:
await self.bot.say('A Pokémon with that name could not be found.')
else:
embed = discord.Embed(title=moves.pokemon, colour=moves.color,
description="```{}```".format(table))
embed.add_field(name="Versions", value='\n'.join(moves.versions))
embed.set_footer(text="This moveset is based on generation {}.".format(moves.gen))
await self.bot.say(embed=embed)
def _item_pokemon(self, *, item_name: str):
"""Search for an item in the Pokémon universe
Args:
item_name: variable length string
Returns:
Discord embed
Raises:
AttributeError: Item not found
Examples:
pokemon item master ball
"""
item = self.search_csv(item_name.title(), 'data/pokedex/Items.csv', data_type='i')
try:
color = self.color_lookup(item.category)
except AttributeError:
await self.bot.say("An item with that name could not be found.")
else:
embed = discord.Embed(colour=color, title=item.name)
embed.set_thumbnail(url=item.image)
embed.add_field(name="Cost", value=item.cost)
embed.add_field(name="Category", value=item.category)
embed.add_field(name="Effect", value=item.effect)
await self.bot.say(embed=embed)
def _info_heist(self, ctx):
"""Shows the Heist settings for this server."""
server = ctx.message.server
settings = self.check_server_settings(server)
if settings["Config"]["Hardcore"]:
hardcore = "ON"
else:
hardcore = "OFF"
# Theme variables
theme = settings["Config"]["Theme"]
t_jail = settings["Theme"]["Jail"]
t_sentence = settings["Theme"]["Sentence"]
t_police = settings["Theme"]["Police"]
t_bail = settings["Theme"]["Bail"]
time_values = [settings["Config"]["Wait Time"], settings["Config"]["Police Alert"],
settings["Config"]["Sentence Base"], settings["Config"]["Death Timer"]]
timers = list(map(self.time_format, time_values))
description = ["Heist Version {}".format(self.version), "Theme: {}".format(theme)]
footer = "Heist was developed by Redjumpman for Red Bot."
embed = discord.Embed(colour=0x0066FF, description="\n".join(description))
embed.title = "{} Heist Settings".format(server.name)
embed.add_field(name="Heist Cost", value=settings["Config"]["Heist Cost"])
embed.add_field(name="Base {} Cost".format(t_bail), value=settings["Config"]["Bail Base"])
embed.add_field(name="Crew Gather Time", value=timers[0])
embed.add_field(name="{} Timer".format(t_police), value=timers[1])
embed.add_field(name="Base {} {}".format(t_jail, t_sentence), value=timers[2])
embed.add_field(name="Death Timer", value=timers[3])
embed.add_field(name="Hardcore Mode", value=hardcore)
embed.set_footer(text=footer)
await self.bot.say(embed=embed)
def _stats_heist(self, ctx):
"""Shows your Heist stats"""
author = ctx.message.author
avatar = ctx.message.author.avatar_url
settings = self.check_server_settings(author.server)
self.account_check(settings, author)
path = settings["Players"][author.id]
# Theme variables
sentencing = "{} {}".format(settings["Theme"]["Jail"], settings["Theme"]["Sentence"])
t_bail = "{} Cost".format(settings["Theme"]["Bail"])
# Sentence Time Remaining
sentence = path["Sentence"]
time_served = path["Time Served"]
jail_fmt = self.cooldown_calculator(time_served, sentence)
# Death Time Remaining
death_timer = path["Death Timer"]
base_death_timer = settings["Config"]["Death Timer"]
death_fmt = self.cooldown_calculator(death_timer, base_death_timer)
rank = self.criminal_level(path["Criminal Level"])
embed = discord.Embed(colour=0x0066FF, description=rank)
embed.title = author.name
embed.set_thumbnail(url=avatar)
embed.add_field(name="Status", value=path["Status"])
embed.add_field(name="Spree", value=path["Spree"])
embed.add_field(name=t_bail, value=path["Bail Cost"])
embed.add_field(name=settings["Theme"]["OOB"], value=path["OOB"])
embed.add_field(name=sentencing, value=jail_fmt)
embed.add_field(name="Apprehended", value=path["Jail Counter"])
embed.add_field(name="Death Timer", value=death_fmt)
embed.add_field(name="Total Deaths", value=path["Deaths"])
embed.add_field(name="Lifetime Apprehensions", value=path["Total Jail"])
await self.bot.say(embed=embed)
def send_message(self, name, channel, message):
em = discord.Embed(description=message, colour=self.get_color(name))
msg = await self.client.send_message(channel, embed=em)
return msg
def edit_message(self, name, old_message, new_message):
em = discord.Embed(description=new_message, colour=self.get_color(name))
msg = await self.client.edit_message(old_message, embed=em)
return msg
def server_info(self, message_object):
server = message_object.server
msg = "**Name:** " + server.name + " (" + server.id + ")\n"
msg += "**Total members:** " + str(server.member_count) + "\n"
msg += "**Server owner:** " + server.owner.name + "\n"
msg += "**Server region:** " + str(server.region) + "\n"
msg += "**Created at:** " + server.created_at.strftime("%B %d, %Y")
em = discord.Embed(description=msg, colour=self.pm.clientWrap.get_color(self.name))
em.set_image(url=server.icon_url)
await self.pm.client.send_message(message_object.channel, "", embed=em)
def post_avatar(self, message_object, user):
if user.avatar_url is None or user.avatar_url is "":
await self.pm.clientWrap.send_message(self.name, message_object.channel,
user.display_name + " has no avatar set!")
return
em = discord.Embed(description="Avatar for " + user.display_name,
colour=self.pm.clientWrap.get_color(self.name))
em.set_image(url=user.avatar_url)
await self.pm.client.send_message(message_object.channel, "", embed=em)
def on_status(self, status):
## print(status.text)
if not status.in_reply_to_status_id and status.user.id_str in set([id for feeds in self.feeds.values() for id in feeds]):
# TODO: Settings for including replies, retweets, etc.
for channel_id, channel_feeds in self.feeds.items():
if status.user.id_str in channel_feeds:
embed = discord.Embed(title = '@' + status.user.screen_name, url = "https://twitter.com/{}/status/{}".format(status.user.screen_name, status.id), description = status.text, timestamp = status.created_at, color = clients.twitter_color)
embed.set_author(name = status.user.name, icon_url = status.user.profile_image_url)
embed.set_footer(text = "Twitter", icon_url = clients.twitter_icon_url)
channel = self.bot.get_channel(channel_id)
if channel:
self.bot.loop.create_task(self.bot.send_message(channel, embed = embed))
def twitter_status(self, ctx, handle : str):
'''Get twitter status'''
tweet = clients.twitter_api.user_timeline(handle, count = 1)[0]
embed = discord.Embed(title = '@' + tweet.user.screen_name, url = "https://twitter.com/{}/status/{}".format(tweet.user.screen_name, tweet.id), description = tweet.text, timestamp = tweet.created_at, color = 0x00ACED)
avatar = ctx.message.author.default_avatar_url if not ctx.message.author.avatar else ctx.message.author.avatar_url
embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
embed.set_footer(text = tweet.user.name, icon_url = tweet.user.profile_image_url)
await self.bot.say(embed = embed)
def help_other(self, ctx):
'''Additional commands and information'''
# TODO: Update
# TODO: Add last updated date?
embed = discord.Embed(title = "Commands not in {}help".format(ctx.prefix), color = clients.bot_color)
avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url
embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
embed.description = "See `{}help` for the main commands".format(ctx.prefix)
embed.add_field(name = "Conversion Commands", value = "see `{}conversions`".format(ctx.prefix), inline = False)
embed.add_field(name = "In Progress", value = "gofish redditsearch roleposition rolepositions taboo userlimit webmtogif whatis", inline = False)
embed.add_field(name = "Misc", value = "invite randomgame test test_on_message", inline = False)
embed.add_field(name = "Owner Only", value = "allcommands changenickname deletetest cleargame clearstreaming echo eval exec load reload repl restart servers setgame setstreaming shutdown unload updateavatar", inline = False)
embed.add_field(name = "No Prefix", value = "@Harmonbot :8ball: (exactly: f|F) (anywhere in message: getprefix)", inline = False)
await self.bot.say(embed = embed)
def benchmark(self):
'''Benchmark'''
process = psutil.Process()
memory = process.memory_info().rss / 2 ** 20
process.cpu_percent()
embed = discord.Embed(color = clients.bot_color)
embed.add_field(name = "RAM", value = "{:.2f} MiB".format(memory))
embed.add_field(name = "CPU", value = "Calculating CPU usage..")
message, embed = await self.bot.say(embed = embed)
await asyncio.sleep(1)
cpu = process.cpu_percent() / psutil.cpu_count()
embed.set_field_at(1, name = "CPU", value = "{}%".format(cpu))
await self.bot.edit_message(message, embed = embed)
def playingr_processr(self, ctx, reaction, user):
if reaction.emoji in self.controls:
if self.controls[reaction.emoji] == "pause_resume":
if utilities.get_permission(ctx, "pause", id = user.id) or user == ctx.message.server.owner or user.id == clients.owner_id:
embed = discord.Embed(color = clients.bot_color).set_author(name = user.display_name, icon_url = user.avatar_url or user.default_avatar_url)
try:
self.bot.cogs["Audio"].players[ctx.message.server.id].pause()
except errors.AudioNotPlaying:
embed.description = ":no_entry: There is no song to pause"
except errors.AudioAlreadyDone:
self.bot.cogs["Audio"].players[ctx.message.server.id].resume()
embed.description = ":play_pause: Resumed song"
else:
embed.description = ":pause_button: Paused song"
await self.bot.send_message(ctx.message.channel, embed = embed)
await self.bot.attempt_delete_message(ctx.message)
elif self.controls[reaction.emoji] in ("skip", "replay", "shuffle", "radio"):
if utilities.get_permission(ctx, self.controls[reaction.emoji], id = user.id) or user.id in (ctx.message.server.owner.id, clients.owner_id):
message = copy.copy(ctx.message)
message.content = "{}{}".format(ctx.prefix, self.controls[reaction.emoji])
await self.bot.process_commands(message)
# Timestamp for radio
elif self.controls[reaction.emoji] in ("volume_down", "volume_up"):
if utilities.get_permission(ctx, "volume", id = user.id) or user.id in (ctx.message.server.owner, clients.owner_id):
try:
current_volume = self.bot.cogs["Audio"].players[ctx.message.server.id].get_volume()
except errors.AudioNotPlaying:
await self.bot.embed_reply(":no_entry: Couldn't change volume\nThere's nothing playing right now")
if self.controls[reaction.emoji] == "volume_down": set_volume = current_volume - 10
elif self.controls[reaction.emoji] == "volume_up": set_volume = current_volume + 10
message = copy.copy(ctx.message)
message.content = "{}volume {}".format(ctx.prefix, set_volume)
await self.bot.process_commands(message)
def serverinfo(self, ctx):
'''Information about a server'''
server = ctx.message.server
embed = discord.Embed(title = server.name, url = server.icon_url, timestamp = server.created_at, color = clients.bot_color)
avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url
embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
embed.set_thumbnail(url = server.icon_url)
embed.add_field(name = "Owner", value = server.owner.mention)
embed.add_field(name = "ID", value = server.id)
embed.add_field(name = "Region", value = str(server.region))
embed.add_field(name = "Roles", value = len(server.roles))
channel_types = [c.type for c in server.channels]
text_count = channel_types.count(discord.ChannelType.text)
voice_count = channel_types.count(discord.ChannelType.voice)
embed.add_field(name = "Channels", value = "{} text\n{} voice".format(text_count, voice_count))
embed.add_field(name = "Members", value = "{}\n({} bots)".format(server.member_count, sum(m.bot for m in server.members)))
embed.add_field(name = "AFK Timeout", value = "{:g} min.".format(server.afk_timeout / 60))
embed.add_field(name = "AFK Channel", value = str(server.afk_channel))
embed.add_field(name = "Verification Level", value = str(server.verification_level).capitalize())
embed.add_field(name = "2FA Requirement", value = bool(server.mfa_level))
embed.add_field(name = "Default Channel", value = server.default_channel.mention)
if server.emojis:
emojis = [str(emoji) for emoji in server.emojis]
if len(' '.join(emojis)) <= 1024:
embed.add_field(name = "Emojis", value = ' '.join(emojis), inline = False)
else:
embed.add_field(name = "Emojis", value = ' '.join(emojis[:len(emojis) // 2]), inline = False)
embed.add_field(name = "Emojis", value = ' '.join(emojis[len(emojis) // 2:]), inline = False)
embed.set_footer(text = "Created")
await self.bot.say(embed = embed)