Пример #1
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
Пример #2
0
    async def send_board(self, channel: TextChannel) -> Message:
        """Prepare game Embed and update message"""

        session = self.session(channel)

        em = Embed(
            title=
            f"{session.p1.chip}{session.p1.name} {Emoji.vs} {session.p2.name}{session.p2.chip}",
            description=f"\n"
            f"{Emoji.one}{Emoji.two}{Emoji.three}{Emoji.four}{Emoji.five}{Emoji.six}{Emoji.seven}\n"
            f"{session.draw_board}")

        if session.state == State.init:
            em.description = f"New game! Turn: 1\n" \
                             f"{em.description}\n" \
                             f"\n" \
                             f"{session.current_player.mention}'s turn: {session.current_player.chip}"
            em.colour = session.colour

            return await self.init_game_message(channel, session, em)

        elif session.state == State.active:
            em.description = f"Turn: {(session.turn + 2) // 2}\n" \
                             f"{em.description}\n" \
                             f"\n" \
                             f"{session.current_player.mention}'s turn: {session.current_player.chip}"
            em.colour = session.colour

        elif session.state == State.draw:
            self.sessions.pop(channel.id)
            em.description = f"Game ended in a Draw.\n" \
                             f"{em.description}"
            em.colour = Colour.dark_grey()
            await session.msg.clear_reactions()

        elif session.state == State.forfeit:
            self.sessions.pop(channel.id)
            em.description = f"Game Over. {session.current_player.name} Forfeits.\n" \
                             f"{em.description}"
            em.colour = Colour.dark_grey()
            await session.msg.clear_reactions()

        elif session.state == State.timeout:
            self.sessions.pop(channel.id)
            em.description = f"Time Out. {session.current_player.name} Forfeits.\n" \
                             f"{em.description}"
            em.colour = Colour.dark_grey()
            await session.msg.clear_reactions()

        elif session.state == State.won:
            self.sessions.pop(channel.id)
            em.description = f"Game Over!\n{session.current_player.name} wins! {Emoji.tada}\n" \
                             f"{em.description}"
            em.colour = 0xFDFF00
            await session.msg.clear_reactions()

        # TODO: check I can edit the message (retrievable), if not, init message
        return await session.msg.edit(embed=em)
Пример #3
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)
Пример #4
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)
Пример #5
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)
Пример #6
0
 async def hanime(self, ctx: Context, *, query: str = ''):
     """Searches hanime for hentai"""
     if query == '':
         return await self.hanimerandom.invoke(ctx)
     data = await self.hanime_search(query)
     if len(data) == 0:
         await ctx.send(f"No hentai found for query `{query}`")
         return
     embeds = [
         discord.Embed(
             colour=Colour.gold(),
             title=hentai['name'],
             description=re.sub(r'<.+?>', '', hentai['description'])
         ).set_author(
             name=f"Result for search {query}",
             url="https://hanime.tv/videos/hentai/"+hentai['slug']
         ).set_image(
             url=hentai['cover_url']
         ).add_field(
             name="tags",
             value=", ".join(hentai['tags'])
         ).set_footer(
             text=f"{hentai['views']} views | "
                 f"{hentai['likes']} likes & {hentai['dislikes']} dislikes"
         )
         for hentai in data
     ]
     menu = DefaultMenu()
     await menu.send_pages(ctx, ctx, embeds)
    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
Пример #8
0
def get_blizzardcs_last_tweet(event, context):
    region = event['pathParameters']['region']
    api = twitter.Api(consumer_key=os.getenv("TWITTER_CONSUMER_KEY"),
                      consumer_secret=os.getenv("TWITTER_CONSUMER_SECRET"),
                      application_only_auth=True)
    status = api.GetUserTimeline(screen_name="blizzardcs" if region.lower()
                                 == "us" else "blizzardcseu_en",
                                 include_rts=False,
                                 exclude_replies=True)

    date = datetime.strptime(status[0].created_at,
                             "%a %b %d %H:%M:%S +0000 %Y")
    date = date.replace(tzinfo=simple_utc())
    embed = {
        "thumbnail": {
            "url": status[0].user.profile_image_url_https
        },
        "author": {
            "name": status[0].user.screen_name,
            "url": "https://twitter.com/%s" % status[0].user.screen_name
        },
        "description": status[0].text,
        "color": Colour.from_rgb(29, 161, 242).value,
        "timestamp": date.isoformat()
    }

    if status[0].media:
        embed["image"] = {"url": status[0].media[0].media_url_https}
    return {"statusCode": 200, "body": json.dumps(embed)}
Пример #9
0
    async def server_info(self, ctx: Context):
        target = ctx.guild

        embed = Embed(title=target.name,
                      colour=Colour.from_rgb(255, 255, 0),
                      timestamp=datetime.now().astimezone(est))
        embed.set_thumbnail(url=target.icon_url)

        created = target.created_at
        created = utc.localize(created)

        fields = [
            ("ID", target.id, False),
            ("Roles", ', '.join([
                role.mention for role in target.roles
                if str(role) != "@everyone"
            ]), True),
            ("Region", target.region, False),
            ("Created", created.astimezone(est).strftime("%d/%m/%Y, %H:%M:%S"),
             True),
            ("Total Members", target.member_count, True),
        ]

        for name, value, inline in fields:
            embed.add_field(name=name, value=value, inline=inline)

        await ctx.reply(embed=embed)
Пример #10
0
 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)
Пример #11
0
async def log_edit(type_: str, name: str, author: str, url: str):
    embed = Embed(title=f"Edited {type_}: {name}",
                  color=Colour.blue(),
                  timestamp=datetime.utcnow(),
                  url=url)
    embed.set_author(name=author)
    await log_to_webhook(embed=embed)
Пример #12
0
    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
Пример #13
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)
Пример #14
0
 async def random_cat(self, ctx: commands.Context):
     """Sends a random cat. Meow!"""
     filename = requests.get('http://aws.random.cat/meow').json()['file']
     embed = Embed(description='Meow!',
                   colour=Colour(randint(0x000000, 0xFFFFFF)))
     embed.set_image(url=filename)
     await ctx.send(embed=embed)
Пример #15
0
    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
Пример #16
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)
Пример #17
0
class InfoEmbedFormatter(EmbedFormatter):
    """
    Generic informational embed, for instance shown on successful completion
    of some operation.
    """

    icon = "ℹ️"
    colour = Colour.blue()
Пример #18
0
class ErrorEmbedFormatter(EmbedFormatter):
    """
    An embed used for error messages.
    """

    icon = "🛑"
    colour = Colour.red()
    title = "An error has occurred!"
Пример #19
0
 async def random_dog(self, ctx: commands.Context):
     """Sends a random dog. Woof!"""
     filename = requests.get(
         'https://random.dog/woof.json?filter=mp4,webm').json()['url']
     embed = Embed(description='Woof!',
                   colour=Colour(randint(0x000000, 0xFFFFFF)))
     embed.set_image(url=filename)
     await ctx.send(embed=embed)
Пример #20
0
 def __init__(self, text, *args, **kwargs) -> None:
     super().__init__(
         colour=Colour.red(),
         title="ERREUR : ",
         description=f"**{text}**",
         *args,
         **kwargs,
     )
Пример #21
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)
Пример #22
0
    async def queue(self, ctx: Context):

        session = self.get_session(ctx.guild)

        em = Embed(colour=Colour.dark_green(), title="Upcoming requests")

        for index, track in enumerate(session.queue.requests[:10], 1):
            em.add_field(name=f"{index} - Requested by {track.requester}",
                         value=track.information)

        if not em.fields:
            em.description = "There are currently no requests"

        await ctx.send(embed=em)
Пример #23
0
def get_token_price(event, context):
    region = event['pathParameters']['region'].upper()
    region = "NA" if region.casefold() == "US".casefold() else region
    r = requests.get("https://data.wowtoken.info/snapshot.json")
    jsonEntry = r.json()
    if region in jsonEntry:
        region_json = jsonEntry[region]['formatted']
        embed = {
            "title": "Price for 1 WoW Token in the %s region" % region,
            "thumbnail": {
                "url": "http://wow.zamimg.com/images/wow/icons/large/wow_token01.jpg"
            },
            "color": Colour.from_rgb(255, 215, 0).value,
            "fields": [
                {
                    "name": "Current Price",
                    "value": region_json['buy'],
                    "inline": True
                },
                {
                    "name": "Minimum 24H",
                    "value": region_json['24min'],
                    "inline": True
                },
                {
                    "name": "Maximum 24H",
                    "value": region_json['24max'],
                    "inline": True
                },
                {
                    "name": "Percentage 24H range",
                    "value": "%s %%" % region_json['24pct'],
                    "inline": True
                }
            ],
            "footer": {
                "text": "Information taken from https://wowtoken.info",
                "icon_url": "http://wow.zamimg.com/images/wow/icons/large/wow_token01.jpg"
            }
        }
        response = {
            "statusCode": 200,
            "body": json.dumps(embed)
        }
        return response
    response = {
        "statusCode": 404
    }
    return response
Пример #24
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
Пример #25
0
    def __init__(self, data: Dict[str, Any]) -> None:
        self.id = int(data["id"])
        self.name = data["name"]
        self.permissions = Permissions(int(data.get("permissions", 0)))
        self.position = data.get("position", 0)
        self.colour = Colour(data.get("color", 0))
        self.hoist = data.get("hoist", False)
        self.managed = data.get("managed", False)
        self.mentionable = data.get("mentionable", False)

        self.tags: Optional[RoleTags]
        try:
            self.tags = RoleTags(data=data["tags"])  # type: ignore
        except KeyError:
            self.tags = None
Пример #26
0
    async def _generate_embed(self, mail: MailMessage) -> Embed:
        embed = Embed(
            title=f'`Neue E-Mail: {mail.subject}`',
            type='rich',
            colour=Colour.dark_magenta(),
        )

        text = self._cut_mail_text(mail.text)

        embed.set_author(name=mail.from_)
        embed.add_field(name='Nachricht', value=text)
        embed.add_field(name='Datum', value=mail.date.strftime('%c'))
        embed.set_footer(text=self.bot.signature)

        return embed
Пример #27
0
    def playing_message(self) -> Dict[str, Union[Embed, File]]:
        self._cover.seek(0)

        em = Embed(
            colour=Colour.dark_green(),
            title=self._title,
            description=f'{self._album} - ({self._date})'
        )
        em.set_author(name=self._artist)
        em.set_thumbnail(url='attachment://cover.jpg')

        return {
            'embed': em,
            'file': File(self._cover, 'cover.jpg')
        }
Пример #28
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)
Пример #29
0
    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)
Пример #30
0
    async def roger_foto(self, ctx: commands.Context):
        """Você perguntou? O Roger aparece!"""
        msg: Message = await ctx.send("Invocando o Roger...")
        try:
            roger_img = self._fetch_roger_image()
            embed = Embed(description=roger_img[0], colour=Colour(randint(0x000000, 0xFFFFFF)))
            embed.set_image(url=roger_img[1])

            if roger_img[0].lower() == "julio_cobra":
                ct = 'Cacilda, agora a cobra fumou. Você tirou o julio_cobra.'
            else:
                ct = None
            await msg.edit(content=ct, embed=embed)

        except Exception as e:
            await msg.edit("Ih, deu zica.")
            print(f"Zica thrown: {e}")