Exemplo n.º 1
0
 async def _list(self, ctx: Context) -> None:
     if len(self._env_store.keys()):
         emb = Embed(title='Environment Store List', color=Colour.green())
         for k, v in self._env_store.items():
             emb.add_field(name=k, value=repr(v))
     else:
         emb = Embed(title='Environment Store List', description='Environment Store is currently empty',
                     color=Colour.green())
     await ctx.send(embed=emb)
Exemplo n.º 2
0
async def _urban_dictionary_search(self, args, message):
    base_req_url = 'http://api.urbandictionary.com/v0/define'

    res = await perform_async(requests.get, base_req_url, {'term': args})
    if not res.ok:
        await self.send_message(message.channel, 'Error:',
                                res.status_code, '-', res.reason)
        return

    json = res.json()
    if len(json['list']) == 0:
        await self.send_message(message.channel,
                                'No results found for "{}".'.format(args))
    else:
        entry = json['list'][0]
        definition = re.sub(r'\[(\w+)\]', '\\1', entry['definition'])

        reply = ''
        reply += definition[:1000].strip()
        if len(definition) > 1000:
            reply += '... (Definition truncated. '
            reply += 'See more at <{}>)'.format(entry['permalink'])
        reply += '\n\n{} :+1: :black_small_square: {} :-1:'.format(
            entry['thumbs_up'], entry['thumbs_down'])

        result = Embed(
            title=args,
            type='rich',
            description=reply,
            url=entry['permalink'],
            colour=Colour.green(),
        )

        await self.send_message(message.channel, embed=result)
Exemplo n.º 3
0
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
Exemplo n.º 4
0
async def log_create(type_: str, name: str, author: str, url: str):
    embed = Embed(
        title=f"Created {type_}: {name}",
        color=Colour.green(),
        timestamp=datetime.utcnow(),
        url=url,
    )
    embed.set_author(name=author)
    await log_to_webhook(embed=embed)
Exemplo n.º 5
0
 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)
Exemplo n.º 6
0
    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)
Exemplo n.º 7
0
    def render(self):
        """
        Builds and returns self.embed.

        A call to self.embed.render() will serialize all of the content
        into a dict suitable to sending to Discord's API.
        """
        self.embed.add_field(
            name=self.type_line(),
            value=self.text_line(),
        )
        self.embed.colour = Colour.green()
        self.embed.set_thumbnail(url=self.image(self.id))
        self.embed.set_footer(text=self.footer_line())
        return self.embed
Exemplo n.º 8
0
    async def gh(self, ctx: Context):
        """GitHub

        Something"""
        user = f"[{self.user.name}]({self.user.html_url})" if self.user else "None Selected"
        repo = f"[{self.repo.name}]({self.repo.html_url})" if self.repo else "None Selected"

        em = Embed(
            title="GitHub",
            description=f"**__Current Selections:__**\n"
                        f"__User:__ {user}\n"
                        f"__Repository:__ {repo}",
            color=Colour.green()
        )

        await ctx.send(embed=em)
Exemplo n.º 9
0
    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)
Exemplo n.º 10
0
 def __init__(
         self,
         title: str,
         description: str = None,
         author: User = None,
         content: List[tuple] = [],
         footer: str = None,
         image: str = None,
         colour: Colour = Colour.green(),
 ):
     self.author = author
     self.content = content
     self.colour = colour
     self.title = title
     self.description = description
     self.footer = footer
     self.image = image
Exemplo n.º 11
0
 def __init__(self, id, colour=Colour.green(), roles=()):
     self.id = id
     self.colour = colour
     self.roles = [Role(r) for r in roles]
Exemplo n.º 12
0
# 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")
Exemplo n.º 13
0
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)
    }
Exemplo n.º 14
0
 def approve(message):
     embed = Embed(description=message, colour=Colour.green())
     return embed
Exemplo n.º 15
0
 def embed(title, message):
     embed = Embed(title=title, description=message, colour=Colour.green())
     return embed
Exemplo n.º 16
0
    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)