async def em_tb(error: Tuple, ctx: Context = None, event: str = None) -> Embed: """Creates an embed from the given traceback.""" title = f"Exception ignored in event `{event}`" if event else None description = f"**{type(error[1]).__name__}**: {str(error[1])}" stack = extract_tb(error[2]) # stack = extract_tb(error.__traceback__) tb_fields = [ { "name": f"{ZWSP}\n__{fn}__", "value": f"Line `{ln}` in `{func}`:\n```py\n{txt}\n```", "inline": False } for fn, ln, func, txt in stack ] em = Embed(color=Colour.red(), title=title, description=f"{description}") if hasattr(ctx, "author"): em.add_field( name="Context", inline=False, value=f"User: `{ctx.author}` ({ctx.author.id})\n" f"Guild: `{ctx.guild if ctx.guild else 'Unavailable'}` ({ctx.guild.id if ctx.guild else '0'})\n" f"Channel: `{ctx.channel}` ({ctx.channel.id})\n" f"Message: `{ctx.message.content if ctx.message.content else 'No Content'}`\n" f"**Copy this message ID and access `bot.error_contexts[<id>]` for Context.**") else: em.set_footer(text=f"This event was caused by an element in the source code.") for field in tb_fields: em.add_field(**field) return em
async def em_tb(error: Union[Exception, DiscordException], ctx: Context = None, event: str = None) -> Embed: if ctx: prefix = await ctx.bot.get_prefix(ctx.message) title = f"In {prefix}{ctx.command.qualified_name}" description = f"**{error.__class__.__name__}**: {error}" else: title = f"Exception ignored in event `{event}`" if event else None description = f"**{type(error).__name__}**: {str(error)}" stack = extract_tb(error.__traceback__) tb_fields = [{ "name": f"{ZWSP}\n__{fn}__", "value": f"Line `{ln}` in `{func}`:\n```py\n{txt}\n```", "inline": False } for fn, ln, func, txt in stack] em = Embed(color=Colour.red(), title=title, description=f"{description}") for field in tb_fields: em.add_field(**field) return em
def get_server_status_embed(region, realm): r = requests.get('https://%s.api.battle.net/wow/realm/status' % region, params={"realms": realm, "apikey": os.getenv("US_KEY")}) json = r.json() if "realms" in json and json['realms']: realm_json = json['realms'][0] embed = { "color": Colour.green().value if realm_json['status'] else Colour.red().value, "title": "%s - %s" % (realm_json['name'], region.upper()), "fields": [ { "name": "Status", "value": "Online" if realm_json['status'] else "Offline", "inline": True }, { "name": "Population", "value": realm_json['population'], "inline": True }, { "name": "Currently a Queue?", "value": "Yes" if realm_json['queue'] else "No", "inline": True } ] } return embed
async def uptime(self, ctx: Context): em = Embed( title=f"⏲ {self.bot.APP_NAME} Uptime", description= f"Shop's been open for: `{str(timedelta(seconds=self.bot.secs))}`", colour=Colour.red()) await ctx.send(embed=em)
async def get_responses_list(self, final: bool = False) -> Embed: """Returns an embed containing the responses of the people.""" channel = await self.get_channel() embed = Embed(color=Colour.red()) if await self.messages.items(): if final: embed.title = "Spooky Name Rate is about to end!" embed.description = ( "This Spooky Name Rate round is about to end in 2 hours! You can review " "the entries below! Have you rated other's names?") else: embed.title = "All the spookified names!" embed.description = "See a list of all the entries entered by everyone!" else: embed.title = "No one has added an entry yet..." for message_id, data in await self.messages.items(): data = json.loads(data) embed.add_field( name=(self.bot.get_user(data["author"]) or await self.bot.fetch_user(data["author"])).name, value= f"[{(data)['name']}](https://discord.com/channels/{Client.guild}/{channel.id}/{message_id})", ) return embed
def __init__(self, text, *args, **kwargs) -> None: super().__init__( colour=Colour.red(), title="ERREUR : ", description=f"**{text}**", *args, **kwargs, )
class ErrorEmbedFormatter(EmbedFormatter): """ An embed used for error messages. """ icon = "🛑" colour = Colour.red() title = "An error has occurred!"
async def _remove(self, ctx: Context, name: str): if name: v = self._env_store.pop(name, None) else: v = None name = 'You must enter a name' if v: emb = Embed(title='Environment Item Removed', color=Colour.green()) emb.add_field(name=name, value=repr(v)) else: emb = Embed(title='Environment Item Not Found', description=name, color=Colour.red()) await ctx.send(embed=emb)
async def _update(self, ctx: Context, name: str): """Add `ret` as a new object to custom REPL environment""" if name: self._env_store[name] = self.ret em = Embed(title='Environment Updated', color=Colour.green()) em.add_field(name=name, value=repr(self.ret)) else: em = Embed(title='Environment Update', description='You must enter a name', color=Colour.red()) await ctx.send(embed=em)
class EventColors(Enum): ban = Colour.dark_red() unban = Colour.teal() kick = Colour.red() join = Colour.dark_green() leave = Colour.blue() delete = Colour.magenta() bulk_delete = Colour.dark_magenta() edit = Colour.gold() name_change = Colour.purple() nickname_change = Colour.blurple() role_added = Colour.dark_teal() role_removed = Colour.orange() verified = Colour.light_grey()
async def user(self, ctx: Context, *, user: str = None): """User Selects a GitHub user account and shows a brief of the profile. `[p]gh user <username>` will select a user account `[p]gh user self` will select your user account `[p]gh user` will display the currently selected user""" try: if user == "self": self.user = user = self.gh_client.get_user() elif user: self.user = user = self.gh_client.get_user(user) else: if self.user: user = self.user else: return await self.bot.send_help_for( ctx.command, "No account is currently selected." ) if self.repo.owner.name != self.user.name: self.repo = None repos = len(list(user.get_repos())) gists = len(list(user.get_gists())) stars = len(list(user.get_gists())) em = Embed( title=f"{user.login}'s Public GitHub Profile", description=f"*\"{user.bio}\"*\n\n" f"{Emoji.repo} [Repositories]({user.html_url}?tab=repositories): {repos}\n" f"{Emoji.gist} [Gists](https://gist.github.com/{user.login}): {gists}\n" f"{Emoji.star} [Starred Repositories]({user.html_url}?tab=stars): {stars}", color=Colour.green() ) em.set_author(name=user.name, url=user.html_url, icon_url=user.avatar_url) except: em = Embed( title="GitHub: Error", description="Unable to load user or user not found", color=Colour.red() ) await ctx.send(embed=em)
async def play(self, ctx: Context, *, query: str = None): if not ctx.guild: raise OutOfServer() if not ctx.author.voice: raise OutOfVoiceChannel() guild: Guild = ctx.guild clients = self.clients if guild.id not in clients: client: VoiceClient = await ctx.author.voice.channel.connect() clients[guild.id] = client else: client = clients[guild.id] if not query: if client.is_paused(): client.resume() await ctx.send(embed=alert("▶️ Resumed").get_embed()) return raise InvalidArgs("Tell me what to play!") await ctx.send(embed=alert(f"🔎 Searching for '{query}'").get_embed()) results = YoutubeSearch(query).to_dict() url = f"https://youtube.com{results[0]['url_suffix']}" title = results[0]["title"] player = await YTDLSource.from_url(url, loop=self.bot.loop) if results[0]["thumbnails"]: image = results[0]["thumbnails"][0] else: image = None await ctx.send(embed=Embed( f"Now playing {title}", description=url, colour=Colour.red(), image=image, ).get_embed()) if client.is_playing(): client.stop() client.play(player, after=lambda e: print("Player error: %s" % e) if e else None)
def alert(msg: str): embed = Embed(msg, colour=Colour.red()) return embed
async def roles(self, ctx: commands.Context, *args): receivers = {} embed = discord.Embed() embed_sender = discord.Embed() roles = ctx.message await ctx.message.delete() def check_exit(msg: discord.Message): return msg.author.id is ctx.author.id and msg.content == "exit" def check_role(msg: discord.Message): return msg.author.id is ctx.author.id and ( msg.content.strip().startswith("<@&") and msg.content.strip().endswith(">")) or (msg.content == "exit") def check_emoji(payload: discord.RawReactionActionEvent): return payload.member.id is ctx.author.id and payload.message_id == sender.id embed_sender.add_field(name="Tapez `exit`", value="Pour annuler la commande") embed_sender.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url) embed_sender.colour = Colour.orange() embed_sender.title = ":anger: Rôles :anger:" embed_sender.timestamp = datetime.utcnow() embed_sender.description = "__**Veuillez entrer des rôles (20 max) séparés d'un espace entre chaque**__ *(Ex: @admin @nitro @helper ...)*" sender = await ctx.send(embed=embed_sender) try: roles = await self.client.wait_for("message", check=check_role, timeout=120.0) except asyncio.TimeoutError: embed_sender.colour = Colour.red() embed_sender.title = ":x: Temps expiré :x:" embed_sender.timestamp = datetime.utcnow() embed_sender.description = "Vous avez mis plus de 120 secondes pour me répondre. Commande annulée" embed_sender.clear_fields() return await sender.edit(embed=embed_sender) else: if roles.content.strip().lower() == "exit": return await ctx.send("Commande annulée") await roles.delete() if len(roles.role_mentions) > 20: warning = await ctx.send( ":warning: **Trop de rôles indiqués** *(seuls les 20 premiers on été pris en compte)* :warning:" ) roles.role_mentions.sort(reverse=True) for role in roles.role_mentions: if roles.role_mentions.index(role) >= 20: roles.role_mentions.pop(roles.role_mentions.index(role)) embed_sender.colour = Colour.green() embed_sender.title = f":white_check_mark: {role.name} :white_check_mark:" embed_sender.description = f"Ajoutez une réaction à ce message pour le rôle **{role.name}**" embed_sender.clear_fields() embed_sender.add_field(name="Rôle", value=role.mention) embed_sender.timestamp = datetime.utcnow() embed_sender.set_footer( text= f"{roles.role_mentions.index(role)}/{len(roles.role_mentions[:20])}" ) await sender.edit(embed=embed_sender) done, pending = await asyncio.wait( [ self.client.wait_for("message", check=check_exit), self.client.wait_for("raw_reaction_add", check=check_emoji) ], return_when=asyncio.FIRST_COMPLETED) try: stuff = done.pop().result() if isinstance(stuff, discord.Message) and stuff.content == "exit": return await ctx.send("Commande annulée") else: receivers[role] = stuff except: return ctx.send("Une erreur s'est produite") for future in done: future.exception() for future in pending: future.cancel() try: await warning.delete() except: pass await sender.delete() embed.title = " ".join(args) or "Attribution des Rôles" embed.description = "Cliquez sur l'une des réactions à ce message pour obtenir le rôle associé." embed.colour = discord.Colour(126) embed.set_author(name=ctx.message.guild.name) embed.set_thumbnail(url=ctx.guild.icon_url) embed.timestamp = datetime.now(timezone.utc) for key, value in receivers.items(): embed.add_field(name=value.emoji, value=key.mention, inline=True) message = await ctx.send(embed=embed) await message.pin(reason="Roles Attribution") await ctx.channel.purge(limit=1) for emoji in receivers.values(): await message.add_reaction(emoji.emoji)
async def log_delete(type_: str, name: str, author: str): embed = Embed(title=f"Deleted {type_}: {name}", color=Colour.red(), timestamp=datetime.utcnow()) embed.set_author(name=author) await log_to_webhook(embed=embed)
# coding=utf-8 import datetime from discord import TextChannel, Guild, Embed, HTTPException, Member from discord.colour import Colour from discord.ext.commands import AutoShardedBot, Context, group, guild_only, has_permissions from peewee import DoesNotExist from smithy.constants import NOTE_CLOSED, NOTE_OPEN, NOTE_RESOLVED from smithy.database import manager, DBServer, Note __author__ = "Gareth Coles" CLOSED_COLOUR = Colour.red() OPEN_COLOR = Colour.blurple() RESOLVED_COLOUR = Colour.green() class Notes: """ In-channel notes """ def __init__(self, bot: AutoShardedBot): self.bot = bot @group(invoke_without_command=True, aliases=["note"]) async def notes(self, ctx: Context): """ In-channel notes management """ await ctx.invoke(self.bot.get_command("help"), "notes")
active = 0 won = 1 draw = 2 forfeit = 3 timeout = 4 class MsgLevel(Enum): info = 0 warning = 1 error = 2 MSG_ICON = [Emoji.info, Emoji.warning, Emoji.error] MSG_COLOR = [Colour.blue(), Colour.orange(), Colour.red()] AWBW_ROLES = { "os": 424524133670453250, # Orange Star Commander "bm": 424524139999789058, # Blue Moon Commander "ge": 424524144353476629, # Green Earth Commander "yc": 424524148958560266, # Yellow Comet Commander "bh": 424524153387876353, # Black Hole Commander "rf": 424541540740890624, # Red Fire Commander "gs": 424541543810990089, # Grey Sky Commander "bd": 424541547757961216, # Brown Desert Commander "ab": 424541550853488640, # Amber Blaze Commander "js": 424541553898291200, # Jade Sun Commander "ci": 424541559766122518, # Cobalt Ice Commander "pc": 424541563520024576, # Pink Cosmos Commander "tg": 424541566934319104, # Teal Galaxy Commander
def get_legion_building(event, context): region = event['pathParameters']['region'].lower() session = HTMLSession() r = session.get("https://wowhead.com") # .attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") status = r.html.find(".tiw-bs-status") states = r.html.find(".tiw-bs-status-state") percents = r.html.find(".tiw-bs-status-progress") if region == "us": embed = { "title": "Broken Shore Building Status", "fields": [ { "name": "Mage Tower", "value": "%s - %s" % (states[0].text, percents[0].text), "inline": True }, { "name": "Command Center", "value": "%s - %s" % (states[1].text, percents[1].text), "inline": True }, { "name": "Nether Disruptor", "value": "%s - %s" % (states[2].text, percents[2].text), "inline": True } ] } if states[0].text == "Completed": embed["color"] = Colour.green().value embed['image'] = { "url": status[0].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[1].text == "Completed": embed["color"] = Colour.green().value embed['image'] = { "url": status[1].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[2].text == "Completed": embed["color"] = Colour.green().value embed['image'] = { "url": status[2].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[0].text == "Under Attack": embed["color"] = Colour.from_rgb(255, 255, 0).value embed['image'] = { "url": status[0].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[1].text == "Under Attack": embed["color"] = Colour.from_rgb(255, 255, 0).value embed['image'] = { "url": status[1].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[2].text == "Under Attack": embed["color"] = Colour.from_rgb(255, 255, 0).value embed['image'] = { "url": status[2].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } else: embed["color"] = Colour.red().value embed['image'] = { "url": status[0].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } else: embed = { "title": "Broken Shore Building Status", "fields": [ { "name": "Mage Tower", "value": "%s - %s" % (states[3].text, percents[3].text), "inline": True }, { "name": "Command Center", "value": "%s - %s" % (states[4].text, percents[4].text), "inline": True }, { "name": "Nether Disruptor", "value": "%s - %s" % (states[5].text, percents[5].text), "inline": True } ] } if states[3].text == "Completed": embed["color"] = Colour.green().value embed['image'] = { "url": status[3].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[4].text == "Completed": embed["color"] = Colour.green().value embed['image'] = { "url": status[4].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[5].text == "Completed": embed["color"] = Colour.green().value embed['image'] = { "url": status[5].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[3].text == "Under Attack": embed["color"] = Colour.from_rgb(255, 255, 0).value embed['image'] = { "url": status[3].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[4].text == "Under Attack": embed["color"] = Colour.from_rgb(255, 255, 0).value embed['image'] = { "url": status[4].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } elif states[5].text == "Under Attack": embed["color"] = Colour.from_rgb(255, 255, 0).value embed['image'] = { "url": status[5].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } else: embed["color"] = Colour.red().value embed['image'] = { "url": status[3].attrs['style'].split("(")[1].split(")")[0].replace("//", "https://") } return { "statusCode": 200, "body": json.dumps(embed) }
def error(message): embed = Embed(title="Error", description=message, colour=Colour.red()) return embed
class YouTubeTrack(Track): _embed_colour = Colour.red() _track_type = 'YouTube video' # youtube_api_url = f"https://www.googleapis.com/ # {COG_CONFIG.YOUTUBE_API.SERVICE_NAME}/{COG_CONFIG.YOUTUBE_API.VERSION}" # video_url_check = compile(r'(?:youtube(?:-nocookie)?\.com/(?:[^/\n\s]+/\S+/|(?:v|e(?:mbed)?)/|' # r'\S*?[?&]v=)|youtu\.be/)([a-zA-Z0-9_-]{11})') ydl_options = {'format': 'bestaudio/best', "ignoreerrors": True} def __init__( self, video_url: str, config: SubRedis, volume: float = 0.15, requester: Optional[User] = None, **kwargs ): self.config = config if not volume: volume = float(self.config.hget("config:defaults", "volume")) with YoutubeDL(self.ydl_options) as ydl: info = ydl.extract_info(video_url, download=False) if 'entries' in info: info = info['entries'][0] self.length = info['duration'] self._title = info['title'] self._url = info['webpage_url'] self._uploader = info['uploader'] self._uploader_url = info['channel_url'] self._thumbnail = info['thumbnail'] super().__init__( info['url'], config, volume, requester, before_options='-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', options='-bufsize 7680k', **kwargs ) @property def information(self) -> str: return f'**[{self._title}]({self._url})** by **[{self._uploader}]({self._uploader_url})**' @property def status_information(self) -> str: return f'{self._title} by {self._uploader}' @property def playing_message(self) -> Dict[str, Embed]: em = Embed( colour=self._embed_colour, description=f'[{self._title}]({self._url})' ) em.set_author(name=self._uploader, url=self._uploader_url) em.set_thumbnail(url=self._thumbnail) return {'embed': em} @property def request_message(self) -> Dict[str, Embed]: message = super().request_message message['embed'].set_thumbnail( url=self._thumbnail ) return message