def embedsayto(self, ctx, channel: discord.Channel, *, text: str):
"""Says Something as the bot in a embed"""
colour = ''.join([choice('0123456789ABCDEF') for x in range(6)])
colour = int(colour, 16)
randnum = randint(1, 10)
empty = u"\u2063"
emptyrand = empty * randnum
data = discord.Embed(description=str(
text), colour=discord.Colour(value=colour))
if ctx.message.author.avatar_url:
data.set_author(name=ctx.message.author.name,
url=ctx.message.author.avatar_url, icon_url=ctx.message.author.avatar_url)
else:
data.set_author(name=ctx.message.author.name)
try:
await self.bot.send_message(channel, emptyrand, embed=data)
except:
await self.bot.say("I need the `Embed links` permission to send this")
python类Colour()的实例源码
def embedsayadmin(self, ctx, *, text: str):
"""Says Something as the bot without any trace of the message author in a embed"""
if ctx.message.server.me.bot:
try:
await self.bot.delete_message(ctx.message)
except:
await self.bot.send_message(ctx.message.author, 'Could not delete your message on ' + ctx.message.server.name)
colour = ''.join([choice('0123456789ABCDEF') for x in range(6)])
colour = int(colour, 16)
randnum = randint(1, 10)
empty = u"\u2063"
emptyrand = empty * randnum
data = discord.Embed(description=str(
text), colour=discord.Colour(value=colour))
try:
await self.bot.say(emptyrand, embed=data)
except:
await self.bot.say("I need the `Embed links` permission "
"to send this")
def Nep(self):
"""Displays a random Nep."""
nep = choice(self.nep)
nepsay = choice(self.nepsay)
if not nep or not nepsay:
await self.bot.say('Something went wrong')
return
colour = ''.join([choice('0123456789ABCDEF') for x in range(6)])
colour = int(colour, 16)
data = discord.Embed(
title=nepsay, colour=discord.Colour(value=colour))
data.set_image(url=nep)
try:
await self.bot.say(embed=data)
except:
await self.bot.say("I need the `Embed links` permission "
"to send this")
def resolve_color(value):
"""Resolve a custom or pre-defined color.
This allows html style #123456.
"""
if value.startswith('#'):
value = value[1:] # assumes no named color starts with #
try:
intval = int(value, 16)
except ValueError:
pass
else:
if intval >= (1 << 24):
raise errors.BadArgument("Invalid color {} is too big!".format(value))
return discord.Colour(intval)
try:
return getattr(discord.Colour, value)()
except AttributeError:
raise errors.BadArgument("Invalid color {}".format(value))
def colorrole(self, ctx, color):
"""Creates a colored role for you!
Example
[p]colorrole #8C5200
Hex pls."""
if not color.startswith("#"):
await send_cmd_help(ctx)
return
colorhex = color[1:]
color_role = await self.bot.create_role(server=ctx.message.server, name=color, colour=discord.Colour(value=int(colorhex, 16)))
await self.bot.add_roles(ctx.message.author, color_role)
await self.bot.say("Done!")
def setcolour(self, ctx, colour:str, user:Member=None):
'''
Creates a new role with a given colour, and assigns it to a user
'''
# Fix up some variables
server = ctx.message.server
user = ctx.message.author if not user else user
# Fix the colour string
colour = colourFixer(colour)
colourObj = Colour(int(colour, 16))
# permissions=Permissions(permissions=0)
# Find the role
tempRoleFinder = [i for i in server.roles if user.id in i.name]
if len(tempRoleFinder) > 0:
role = tempRoleFinder[0]
await self.sparcli.edit_role(server, role, colour=colourObj)
created = False
else:
role = await self.sparcli.create_role(server, name='SPARCLI - {}'.format(user.id), colour=colourObj)
await self.sparcli.add_roles(user, role)
created = True
# Print out to user
await self.sparcli.say(
'This role has been successfully {}. \n'
'You may need to move the positions of other roles to make it work properly.'.format({True:'created',False:'edited'}[created])
)
def asetcolour(self, ctx, colour:str):
'''
Creates a new role with a given colour, and assigns it to yourself
Requires enabling
'''
# Fix up some variables
server = ctx.message.server
user = ctx.message.author
# Fix the colour string
colour = colourFixer(colour)
colourObj = Colour(int(colour, 16))
# permissions=Permissions(permissions=0)
# Find the role
tempRoleFinder = [i for i in server.roles if user.id in i.name]
if len(tempRoleFinder) > 0:
role = tempRoleFinder[0]
await self.sparcli.edit_role(server, role, colour=colourObj)
created = False
else:
role = await self.sparcli.create_role(server, name='SPARCLI - {}'.format(user.id), colour=colourObj)
await self.sparcli.add_roles(user, role)
created = True
# Print out to user
await self.sparcli.say(
'This role has been successfully {}. \n'
'You may need to move the positions of other roles to make it work properly.'.format({True:'created',False:'edited'}[created])
)
def randomColour(self):
co = ["A", "B", "C", "D", "E", "F", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
a = int(random.random() * len(co))
b = int(random.random() * len(co))
c = int(random.random() * len(co))
d = int(random.random() * len(co))
e = int(random.random() * len(co))
f = int(random.random() * len(co))
col = "{}{}{}{}{}{}".format(co[a], co[b], co[c], co[d], co[e], co[f])
return discord.Colour(int(col, 16))
def make_embed_message(title, datas, bot, message=None):
"""
Return an embed message for discord.
Datas must be a simple dict
"""
# embed properties
embed_title = title
embed_colour = discord.Colour(0x3c6d46)
embed_timestamp = datetime.datetime.utcnow()
embed = discord.Embed(title=embed_title, colour=embed_colour,
timestamp=embed_timestamp)
# author properties
if message is not None:
author = message.author.name
url = message.author.avatar_url
else:
author = datas.pop("author")
url = bot.user.avatar_url
author_name = author
author_icon_url = url
embed.set_author(name=author_name, icon_url=author_icon_url)
# footer properties
footer_text = bot.user.name
footer_icon_url = bot.user.avatar_url
embed.set_footer(text=footer_text, icon_url=footer_icon_url)
# content
inline = False
for key, data in datas.items():
if isinstance(data, bool):
data = states[data]
embed.add_field(name=key.title(), value=data, inline=inline)
return embed
def create_embed(xkcd):
comic = xkcd['comic']
embed_comic = discord.Embed \
(title = '{}: {}'.format(comic['num'], comic['title']), \
colour = discord.Colour(0x00ff00), url = comic['img'])
embed_comic.set_footer(text = '{}'.format(comic['alt']))
embed_comic.set_image(url = comic['img'])
embed_comic.set_author(name = 'xkcd', \
url = 'https://xkcd.com/{}'.format(comic['num']))
return embed_comic
def games(self, ctx):
"""Manages games for the roster."""
# Handle Database
try:
with db.cursor() as cursor:
sql = "SELECT `abv`, `name` FROM games ORDER BY `name`"
cursor.execute(sql)
result = cursor.fetchall()
cursor.close()
except Exception as e:
await self.bot.send_message(ctx.message.channel, "{0.mention}, there was an error getting the list of games"
" for you. I'm sorry! ".format(ctx.message.author) + str(
e))
return
# Create Variables for Embed Table
abvs = ''
names = ''
for row in result:
abvs += (row['abv'] + '\n')
names += (row['name'] + '\n')
# Create Embed Table
embed = discord.Embed(title="Games List", colour=discord.Colour(0x55ff),
description="*The list of available games for the roster commands, as well as their "
"abbreviations for use in those commands.*")
embed.set_author(name="Zealot Gaming", url="https://www.zealotgaming.com",
icon_url="http://www.zealotgaming.com/discord/logos/zg.png")
embed.set_thumbnail(url="http://www.zealotgaming.com/discord/logos/zg.png")
embed.add_field(name="Abbreviation", value=abvs, inline=True)
embed.add_field(name="Game Name", value=names, inline=True)
# Send Table to User Privately
await self.bot.send_message(ctx.message.channel, embed=embed)
# COMMAND: !games add
def _setcolor(self, *, color : discord.Colour):
"""Sets the default color of embeds."""
data = self.bot.config.get("meta", {})
data['default_color'] = str(color)
await self.bot.config.put('meta', data)
await self.bot.responses.basic(message="The default color has been updated.")
def color(self):
"""
:return: attr of discord.Colour for player's default avatar
"""
name = self.current_player.default_avatar.name
if name == "grey":
name = "light_grey"
return getattr(discord.Colour, name)()
# @property
# def valid_moves(self):
# """
# :return: List of position coords (list x, y) that are not full
# """
# return [[self.board[i][-1], i] for i in self.order if self.board[i][-1] != 6]
def __init__(self, bot):
self.bot = bot
self.db = bot.db
self.app_name = bot.app_name
self.sessions = {}
self.timeout = 120
self.timeout_incr = 5
self.message_icon = ["?", "?", "?"] # :information_source:, :warning:, :no_entry:
self.message_color = [discord.Colour.blue(), discord.Colour.orange(), discord.Colour.red()]
def send_board(self, ctx, init=False, win=None):
session = self.session(ctx)
session.ctx = ctx
if session.msg is not None:
await session.msg.delete()
if win:
if win == "Draw":
turn = f"Game ended in a Draw."
color = discord.Colour.dark_grey()
elif win == "Forfeit":
turn = f"Game Over. {ctx.author.name} Forfeits."
color = discord.Colour.dark_grey()
elif win == "Timeout":
turn = f"Time Out. {session.current_player.name} Forfeits."
color = discord.Colour.dark_grey()
else:
turn = f"Game Over!\n{win.name} wins! ??"
color = 0xFDFF00
else:
turn = "New game! Turn: 1" if init else f"Turn: {(session.turn + 2) // 2}"
color = session.color
em = discord.Embed(title=f"{session.player_chip(session.p1)}{session.p1.name} ?? "
f"{session.p2.name}{session.player_chip(session.p2)}",
description=f"{turn}\n\n:one::two::three::four::five::six::seven:\n{session.draw_board}",
color=color)
if win:
self.sessions.pop(ctx.channel.id)
await ctx.send(embed=em)
else:
em.set_footer(text=f"{session.current_player.name}'s turn: {session.current_player_chip}")
session.msg = await ctx.send(embed=em)
if not win == "Timeout" and session.current_player.member is not ctx.guild.me:
if ctx.channel.permissions_for(ctx.guild.me).manage_messages:
await ctx.message.delete()
def generate_discord_embed(self):
embed = discord.Embed(type="rich")
# TODO: change the icon
embed.set_author(name="League of Legends", url="http://euw.leagueoflegends.com/", icon_url="https://cdn.discordapp.com/attachments/152150752523976704/307558194824216578/icon.png")
embed.add_field(name="Summoner", value=str(self.summoner_name))
embed.add_field(name="Level", value=str(self.level))
if self.soloq_tier is not None:
embed.add_field(name="Solo/duo SR", value=f"{lol.tiers[self.soloq_tier].capitalize()} {lol.divisions[self.soloq_division]}", inline=False)
embed.set_thumbnail(url=f"https://royal.steffo.me/loltiers/{lol.tiers[self.soloq_tier].lower()}_{lol.divisions[self.soloq_division].lower()}.png")
if self.flexq_tier is not None:
embed.add_field(name="Flex SR", value=f"{lol.tiers[self.flexq_tier].capitalize()} {lol.divisions[self.flexq_division]}", inline=False)
if self.ttq_tier is not None:
embed.add_field(name="Twisted Treeline", value=f"{lol.tiers[self.ttq_tier].capitalize()} {lol.divisions[self.ttq_division]}", inline=False)
embed.colour = discord.Colour(0x09AEBB)
return embed
def inspect(self, ctx):
for role in ctx.message.author.roles:
if self.bot.Henry(ctx) or role.id == '321832268282855436': #bot devs
theObject = None
if len(ctx.message.mentions) > 0:
theObject = ctx.message.mentions[0]
elif len(ctx.message.channel_mentions) > 0:
theObject = ctx.message.channel_mentions[0]
elif len(ctx.message.role_mentions) > 0:
theObject = ctx.message.role_mentions[0]
else:
self.bot.say("I didn't understand what you are inspecting.")
if theObject is not None:
items = []
dictionary = [x for x in dir(theObject) if not x.startswith('_')]
for name in dictionary:
attr = getattr(theObject, name)
if 'object' not in str(attr) and 'method' not in str(attr):
items.append([str(name), str(attr), False])
p = Pages(self.bot, message=ctx.message, entries = items, per_page=10)
p.embed = discord.Embed(title="Inspection Results", colour=discord.Colour(0xdc4643))
p.embed.set_thumbnail(url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
p.embed.set_author(name="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
p.embed.set_footer(text="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
await p.paginate()
else:
self.bot.say("You not a dev, shoo!")
def levels(self, ctx):
self.cur.execute('SELECT * FROM (SELECT *, row_number() OVER(ORDER BY exp DESC) FROM experience) AS filter')
res = list(self.cur.fetchall())
# print(res)
items = []
for item in res:
items.append(['#{}. {}'.format(str(item[6]), str(item[1])), 'Level: {} \nExperience: {}'.format(str(item[4]), str(int(item[3])))])
p = Pages(self.bot, message=ctx.message, entries = items, per_page=10)
p.embed = discord.Embed(title="Server Level Rankings", colour=discord.Colour(0xdc4643))
p.embed.set_thumbnail(url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
p.embed.set_author(name="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
p.embed.set_footer(text="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
await p.paginate()
def __init__(self, bot):
self.bot = bot
# Voting done, command disabled
# @commands.command()
# async def vote():
# embed = discord.Embed(colour=discord.Colour(0xdc4643), timestamp=datetime.datetime.utcfromtimestamp(1490339531))
# embed.set_thumbnail(url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
# embed.set_author(name="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
# embed.set_footer(text="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
# embed.add_field(name="CSSS Voting Information", value="The voting period for the Computing Science Student Society General Elections for the 2017-2018 term begins on Monday March 20th, 2017 at 11:59 PM and closes on Monday March 27th, 2017 at 11:59 PM. \n\nVisit https://www.sfu.ca/~pjalali/speeches.html to view candidate speeches, and http://websurvey.sfu.ca/survey/273372327 to vote.")
# await bot.say(embed=embed)
# @commands.command(pass_context = True)
# async def voteresult(self, ctx):
# """Return the voting results from the previous CSSS election."""
# if ctx.invoked_subcommand is None:
# embed = discord.Embed(title="CSSS Exec Positions", colour=discord.Colour(0xdc4643), timestamp=datetime.datetime.utcfromtimestamp(1490339531))
# embed.set_thumbnail(url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
# embed.set_author(name="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
# embed.set_footer(text="CSSS-Minion", icon_url="https://cdn.discordapp.com/app-icons/293110345076047893/15e2a6722723827ff9bd53ca787df959.jpg")
# embed.add_field(name="President", value="David Miiller")
# embed.add_field(name="Vice President", value="Jon Loewen")
# embed.add_field(name="Treasurer", value="Dustin Cao")
# embed.add_field(name="Director of Resources", value="Kiarash Mirsalehi")
# embed.add_field(name="Director of Events", value="Brendan Chan")
# embed.add_field(name="Director of Communications", value="Henry Zhao")
# embed.add_field(name="Director of Archives", value="Josh Wu")
# embed.add_field(name="Source Code", value="https://github.com/henrymzhao/csss-minion/")
# await self.bot.say(embed=embed)
# the following several functions are inspired by formatterhelper and default_help command
def em(self, ctx, *desc):
"""Make an embedded message
Usage: em <body>
Restricted command
"""
author = ctx.message.author
if author.permissions_in(ctx.message.channel).manage_channels or author.server_permissions.manage_channels:
try:
color = author.colour
except Exception:
color = discord.Colour(r.randrange(0xffffff))
string = ""
for w in desc:
string += w + " "
string = string.strip()
embed = discord.Embed(description = string, color = color)
#embed.set_thumbnail(url=author.avatar_url)
embed.set_author(name=author.display_name, icon_url = author.avatar_url)
await self.bot.say(embed = embed)
try:
await self.bot.delete_message(ctx.message)
except Exception:
#thats ok
print("Not allowed to delete message")
#@commands.command(pass_context = True)
#async def allowedEmbed(self, ctx):
# #echoes permissions
# await self.bot.say(ctx.message.author.permissions_in(ctx.message.channel).manage_channels)