Ejemplo n.º 1
0
async def get_vk_album(url):
    album = vk_album_rx.search(url)
    if not album:
        return Embed(color=Color.blue(), title='❌Плейлист не найден')
    headers = {
        'User-Agent': agent
    }
    params = {
        'access_token': vk_personal_audio_token,
        'v': '5.999',
        'owner_id': album.group(1),
        'playlist_id': album.group(2)
    }
    if album.group(3):
        params['access_key'] = album.group(3)
    async with ClientSession() as client:
        res = await client.get('https://api.vk.com/method/audio.get', headers=headers, params=params)
        playlist = await client.get('https://api.vk.com/method/audio.getPlaylistById', headers=headers, params=params)
        res = await res.json()
        playlist = await playlist.json()
    if 'error' in res.keys():
        if res['error']['error_code'] == 201:
            return Embed(color=Color.blue(), title='❌Нет доступа к аудио пользователя')
        elif res['error']['error_code'] == 15:
            return Embed(color=Color.blue(), title='❌Нет доступа к аудио сообщества')
        else:
            print(res)
            return Embed(color=Color.blue(), title='❌Ошибка при добавлении плейлиста')
    res = res['response']
    playlist = playlist['response']
    album_url = f'https://vk.com/music/album/{album.group(1)}_{album.group(2)}'
    if album.group(3):
        album_url += f'_{album.group(3)}'
    return Playlist(playlist['title'],
                    [Track(item['artist'], item['title'], item['url'], album_url) for item in res['items'] if item['url']])
Ejemplo n.º 2
0
    async def watched_command(self, ctx: Context, from_cache: bool = True):
        """
        Shows all users that are currently monitored and in which channel.
        By default, the users are returned from the cache.
        If this is not desired, `from_cache` can be given as a falsy value, e.g. e.g. 'no'.
        """

        if from_cache:
            lines = tuple(
                f"• <@{user_id}> in <#{self.watched_users[user_id].id}>"
                for user_id in self.watched_users
            )
            await LinePaginator.paginate(
                lines or ("There's nothing here yet.",),
                ctx,
                Embed(title="Watched users (cached)", color=Color.blue()),
                empty=False
            )

        else:
            async with self.bot.http_session.get(URLs.site_bigbrother_api, headers=self.HEADERS) as response:
                if response.status == 200:
                    data = await response.json()
                    self.update_cache(data)
                    lines = tuple(f"• <@{entry['user_id']}> in <#{entry['channel_id']}>" for entry in data)

                    await LinePaginator.paginate(
                        lines or ("There's nothing here yet.",),
                        ctx,
                        Embed(title="Watched users", color=Color.blue()),
                        empty=False
                    )

                else:
                    await ctx.send(f":x: got non-200 response from the API")
Ejemplo n.º 3
0
async def get_vk_personal(url):
    user = vk_pers_rx.search(url)
    if not user:
        return Embed(color=Color.blue(), title='❌Плейлист не найден')
    headers = {
        'User-Agent': agent
    }
    params = {
        'access_token': vk_personal_audio_token,
        'v': '5.999',
        'owner_id': user.group(1),
        'need_user': 1
    }
    async with ClientSession() as client:
        ans = await client.get('https://api.vk.com/method/audio.get', headers=headers, params=params)
        res = await ans.json()
    if 'error' in res.keys():
        if res['error']['error_code'] == 201:
            return Embed(color=Color.blue(), title='❌Нет доступа к аудио пользователя')
        else:
            return Embed(color=Color.blue(), title='❌Ошибка при добавлении плейлиста')
    playlist = res['response']
    items = playlist['items']
    user_info = items.pop(0)
    audios_url = f'https://vk.com/audios/{user.group(1)}'
    return Playlist(f'Аудиозаписи {user_info["name_gen"]}',
                    [Track(item['artist'], item['title'], item['url'], audios_url) for item in items if item['url']])
Ejemplo n.º 4
0
    async def on_user_update(self, user_before: User, user_after: User) -> None:
        if user_before.avatar != user_after.avatar:
            embed = Embed(
                title="Avatar change",
                description=textwrap.dedent(
                    f"""
                    **Previous:** [link]({user_before.avatar_url})
                    **Current:** [link]({user_after.avatar_url})
                    **Mention:** {user_after.mention}
                    """
                ),
                color=Color.blue()
            )
        elif user_before.name != user_after.name:
            embed = Embed(
                title="Username change",
                description=textwrap.dedent(
                    f"""
                    **Previous:** {user_before.name}
                    **Current:** {user_after.name}
                    **Mention:** {user_after.mention}
                    """
                ),
                color=Color.blue()
            )
        elif user_before.discriminator != user_after.discriminator:
            embed = Embed(
                title="Discriminator change",
                description=textwrap.dedent(
                    f"""
                    **Previous:** {user_before.discriminator}
                    **Current:** {user_after.discriminator}
                    **Mention:** {user_after.mention}
                    """
                ),
                color=Color.blue()
            )
        else:
            return

        embed.set_thumbnail(url=user_after.avatar_url)
        embed.set_footer(text=f"User ID: {user_after.id}")
        embed.timestamp = datetime.datetime.utcnow()

        member_log_channels = []
        for guild in self.bot.guilds:
            if guild.get_member(user_after.id) is None:
                continue

            member_log_channel = self.get_log(guild)
            if member_log_channel:
                member_log_channels.append(member_log_channel)

        for member_log_channel in member_log_channels:
            if self.bot.log_is_ignored(Event.user_update, (member_log_channel.guild.id, user_after.id)):
                continue
            await member_log_channel.send(embed=embed)
Ejemplo n.º 5
0
    async def botstatus(self, ctx: Context, status: str, *,
                        status_info: str) -> None:
        """
        Change the status of the bot.

        `botstatus playing <new status>` - Change playing status
        `botstatus watching <new status>` - Change watching status
        `botstatus listening <new status>` - Change listening status
        """
        statuses = ["playing", "watching", "listening"]
        if status.lower() not in statuses:
            await ctx.send("Invalid status type!")
            return

        if status.lower() == "playing":
            try:
                await self.bot.change_presence(activity=Game(type=0,
                                                             name=status_info),
                                               status=Status.online)
                await ctx.send(
                    f"Successfully changed playing status to **{status_info}**"
                )
            except DiscordException:
                await ctx.send(embed=Embed(
                    title="Exception",
                    description=f"```py\n{traceback.format_exc()}\n```",
                    color=Color.blue(),
                ))

        elif status.lower() == "watching":
            try:
                await self.bot.change_presence(activity=Activity(
                    type=ActivityType.watching, name=status_info))
                await ctx.send(
                    f"Successfully changed watching status to **{status_info}**"
                )
            except DiscordException:
                await ctx.send(embed=Embed(
                    title="Exception",
                    description=f"```py\n{traceback.format_exc()}\n```",
                    color=Color.blue(),
                ))

        elif status.lower() == "listening":
            try:
                await self.bot.change_presence(activity=Activity(
                    type=ActivityType.listening, name=status_info))
                await ctx.send(
                    f"Successfully changed listening status to **{status_info}**"
                )
            except DiscordException:
                await ctx.send(embed=Embed(
                    title="Exception",
                    description=f"```py\n{traceback.format_exc()}\n```",
                    color=Color.blue(),
                ))
Ejemplo n.º 6
0
async def versions_(ctx: commands.Context):
    """
    View all available versions releases for the repo.
    """
    versions = await get_versions()
    em = Embed(title='Versions:', color=Color.blue())
    for num, (version, tarball) in enumerate(versions.items()):
        if num % 25 == 0 and num > 0:
            await ctx.send(embed=em)
            em = Embed(title='Versions:', color=Color.blue())
        em.add_field(name=version, value=tarball)
    return await ctx.send(embed=em)
Ejemplo n.º 7
0
async def getenv_(ctx: commands.Context):
    """
    View all environment variables.
    """
    async with session.get(config_url, headers=headers) as resp:
        envs = await resp.json()
        em = Embed(title='Environment Variables:', color=Color.blue())
        for num, (key, val) in enumerate(envs.items()):
            if num % 25 == 0 and num > 0:
                await ctx.send(embed=em)
                em = Embed(title='Environment Variables:', color=Color.blue())
            em.add_field(name=key + ':', value=f'`{val}`')
        return await ctx.send(embed=em)
Ejemplo n.º 8
0
    async def stack_overflow(self, ctx: Context, *, query: str) -> None:
        """Queries Stackoverflow and gives you top results."""
        async with ctx.typing():
            site = stackexchange.Site(stackexchange.StackOverflow, StackExchangeToken)
            site.impose_throttling = True
            site.throttle_stop = False

            results = site.search(intitle=query)[:5]
            embed = Embed(title="StackOverflow search")
            embed.set_thumbnail(url=f"http://s2.googleusercontent.com/s2/favicons?domain_url={site.domain}")

            description = f"**Query:** {query}\n"

            if results:
                embed.color = Color.blue()
            else:
                embed.color = Color.red()
                description += "\nSorry, No results found for given query."

            for result in results:
                # Fetch question's data, include vote_counts and answers
                result = site.question(result.id, filter="!b1MME4lS1P-8fK")
                description += f"\n**[{result.title}](https://{site.domain}/q/{result.id})**"
                description += f"\n**Score:** {result.score}, **Answers:** {len(result.answers)}\n"

            embed.description = description
            await ctx.send(embed=embed)
Ejemplo n.º 9
0
    async def _manage_cog(self,
                          ctx: Context,
                          process: str,
                          extension: t.Optional[str] = None) -> None:
        from bot.core.loader import COGS

        if not extension:
            extensions = COGS
        else:
            extensions = [f"bot.cogs.{extension}"]

        for ext in extensions:
            try:
                if process == "load":
                    self.bot.load_extension(ext)
                elif process == "unload":
                    self.bot.unload_extension(ext)
                elif process == "reload":
                    self.bot.unload_extension(ext)
                    self.bot.load_extension(ext)
                else:
                    await ctx.send("❌ Invalid process for extensions")
            except DiscordException:
                await ctx.send(embed=Embed(
                    title="Exception",
                    description=f"```py\n{traceback.format_exc()}\n```",
                    color=Color.blue(),
                ))
            else:
                await ctx.send("✅")
Ejemplo n.º 10
0
    async def history_command(self, ctx: Context,
                              user: Union[User, proxy_user]) -> None:
        """Shows the specified user's nomination history."""
        result = await self.bot.api_client.get(self.api_endpoint,
                                               params={
                                                   'user__id':
                                                   str(user.id),
                                                   'ordering':
                                                   "-active,-inserted_at"
                                               })
        if not result:
            await ctx.send(":warning: This user has never been nominated")
            return

        embed = Embed(
            title=f"Nominations for {user.display_name} `({user.id})`",
            color=Color.blue())
        lines = [
            self._nomination_to_string(nomination) for nomination in result
        ]
        await LinePaginator.paginate(lines,
                                     ctx=ctx,
                                     embed=embed,
                                     empty=True,
                                     max_lines=3,
                                     max_size=1000)
Ejemplo n.º 11
0
 def __init__(self,
              emoji: Emoji,
              user: Optional[User] = None,
              source: Optional[str] = None,
              timestamp: Union[datetime.datetime, Embed] = Embed.Empty,
              *,
              desc: Optional[str] = ""):
     title = r"\:" + emoji.name + r"\:"
     color = Color.blue() if not emoji.animated else Color.red()
     super().__init__(title=title,
                      description=desc,
                      timestamp=timestamp,
                      color=color)
     super().set_thumbnail(url=emoji.url)
     if user:
         super().add_field(name="Suggested by:",
                           value=user.mention,
                           inline=True)
     if source:
         req = urllib.request.Request(
             "http://www.housepetscomic.com/wp-json/oembed/1.0/embed?url=" +
             source,
             headers={'User-Agent': 'Mozilla/5.0'})
         with urllib.request.urlopen(req) as http:
             response = json.load(fp=http)
         super().add_field(name="Comic source:",
                           value="[{text}]({url})".format(
                               text=html.unescape(response["title"]),
                               url=source),
                           inline=True)
Ejemplo n.º 12
0
 async def embedTest(self, ctx):
     embed = Embed()
     embed.title = "Title"
     embed.type = "rich"
     embed.description = "description lorim ipsum"
     embed.url = "http://classic.wowhead.com"
     embed.timestamp = datetime.datetime.now()
     embed.colour = Color.blue()
     embed.set_footer(
         text="footer",
         icon_url=
         "https://cdn3.iconfinder.com/data/icons/capsocial-round/500/facebook-512.png"
     )
     embed.set_image(
         url="https://wow.zamimg.com/uploads/screenshots/small/5439.jpg")
     embed.set_thumbnail(
         url=
         "https://wow.zamimg.com/images/wow/icons/large/inv_weapon_halberd_11.jpg"
     )
     embed.set_author(
         name="wowhead",
         url="http://classic.wowhead.com",
         icon_url=
         "https://i.pinimg.com/favicons/eca28199c2fbf0ae23373b839916551feae2fe02d04f827a4acaa859.png?8318cd0d651bce539d8d09e39d4f2da5"
     )
     embed.add_field(name="fieldA1", value="valueA1", inline=True)
     embed.add_field(name="fieldA2", value="valueA2", inline=True)
     embed.add_field(name="fieldA3", value="valueA3", inline=True)
     embed.add_field(name="fieldB1", value="valueB1", inline=False)
     embed.add_field(name="fieldB2", value="valueB2", inline=False)
     embed.add_field(name="fieldB3", value="valueB3", inline=False)
     await ctx.send(content=None, embed=embed)
Ejemplo n.º 13
0
    async def countdown(self,
                        ctx: Context,
                        duration: TimeDelta,
                        *,
                        description: t.Optional[str] = Embed.Empty) -> None:
        """A countdown timer that counts down for the specific duration."""
        embed = Embed(title="Timer",
                      description=description,
                      color=Color.blue())
        embed.add_field(name="**Countdown**",
                        value=stringify_timedelta(duration))
        message = await ctx.send(embed=embed)

        final_time = datetime.utcnow() + duration
        while True:
            if final_time <= datetime.utcnow():
                break
            duration = relativedelta(final_time, datetime.utcnow())

            embed.set_field_at(0,
                               name="**Countdown**",
                               value=stringify_timedelta(duration))
            await message.edit(embed=embed)

            await asyncio.sleep(1)

        embed.set_field_at(0,
                           name="**Countdown**",
                           value="Timer reached zero!")
        await message.edit(embed=embed)
Ejemplo n.º 14
0
    async def add(self, context):
        """
        Adds a quote to the database.

        Usage:

            \\q[uote] add <quote>
        """
        match = re.match(add_re, context.message.content)
        if match:
            text = match.string[match.end(0):]
            if text:
                author_id = context.message.author.id
                date = int(time.time())

                server_db = utils.get_db(context.message.server.id)

                connection = sqlite3.connect(server_db)
                connection.execute("INSERT INTO QUOTES VALUES(?, ?, ?)",
                                   (text, author_id, date))
                connection.commit()
                connection.close()

                embed = Embed(title="Quote Added",
                              description="```\n{}\n```".format(text),
                              color=Color.blue())
                embed.set_footer(
                    text="By {}".format(context.message.author.name))

                await self.bot.say(embed=embed)
            else:
                await self.bot.say("No quote passed as argument.")
Ejemplo n.º 15
0
    async def display_assets(self, ctx, member: Optional[Member]):
        member = member or ctx.author

        guild_house, workers, points = db.record(
            "SELECT guild_house, workers, points FROM member_points WHERE member_id = ? AND guild_id = ?;",
            member.id, member.guild.id)

        result = ""
        net_worth = points
        if int(guild_house) == 1:
            net_worth += 5000
            result += ":house: Owns a guild house\n"

            if int(workers) > 0:
                net_worth += int(workers) * 3000
                result += f":tools: {workers} workers\n"

        if points is not None:
            result += f":purse: {points}\n"

        elif points is None and int(guild_house) == 0:
            await ctx.send("That member does not have any asset data.")
            return

        embed = create_embed(f":bank: {member.display_name}'s Assets",
                             f"{result}\n**net worth**: {net_worth} :coin:",
                             color=Color.blue(),
                             thumbnail_url=member.avatar_url)
        await ctx.send(embed=embed)
Ejemplo n.º 16
0
async def embd(ctx, *args):
    colors = {
        "red": Color.red(),
        "green": Color.green(),
        "gold": Color.gold(),
        "orange": Color.orange(),
        "blue": Color.blue(),
        "purple": Color.purple(),
        "teal": Color.teal(),
        "magenta": Color.magenta(),
        "grey": Color.lighter_grey()
    }
    if args:
        argstr = " ".join(args)
        if "-c " in argstr:
            text = argstr.split("-c ")[0]
            color_str = argstr.split("-c ")[1]
            color = colors[
                color_str] if color_str in colors else Color.default()
        else:
            text = argstr
            color = Color.default()

            await client.say(embed=Embed(color=color, description=text))
            await client.delete_message(ctx.message)
Ejemplo n.º 17
0
async def fb(ctx, *args):
    if args:
        url = "https://www.facebook.com/search/people/?q=" + "/".join(args)
        await client.say(
            embed=Embed(description="**[FB Search Results](%s)**" % url,
                        color=Color.blue()))
    await client.delete_message(ctx.message)
Ejemplo n.º 18
0
def random():
    # type: () -> Color

    chilipepper = Color(0x9B1B30)
    tan = Color(0xBEAA3E)
    icedcoffee = Color(0xB18F6A)

    return choice([
        Color.teal(),
        Color.dark_teal(),
        Color.green(),
        Color.dark_green(),
        Color.blue(),
        Color.dark_blue(),
        Color.purple(),
        Color.dark_purple(),
        Color.magenta(),
        Color.dark_magenta(),
        Color.gold(),
        Color.dark_gold(),
        Color.orange(),
        Color.dark_orange(),
        Color.red(),
        Color.dark_red(),
        Color.lighter_grey(),
        Color.darker_grey(),
        Color.blurple(),
        tan,
        icedcoffee,
        chilipepper,
    ])
Ejemplo n.º 19
0
    async def update(self, *args, **kwargs):
        if self.module.is_first_loop:
            msg = self.module.create_discord_embed(
                subtitle=self.TITLE,
                info='Collecting the latest information...',
                color=Color.light_grey())
            return await self.send(msg)

        game_msg = (self.module.GOOD if self.module.game else
                    self.module.UNREACHABLE).format('game server')
        if not self.module.open:
            acc_msg = self.module.CLOSED
            statuses = [acc_msg]
        else:
            acc_msg = (self.module.GOOD if self.module.account else
                       self.module.UNREACHABLE).format('account server')
            statuses = [game_msg, acc_msg]
        ban_msg = self.module.BANNER.format(
            self.module.banner) if self.module.banner else None
        if ban_msg:
            statuses.append(ban_msg)

        color = Color.green()
        color = Color.blue(
        ) if self.module.banner and self.module.account else color
        color = Color.gold() if (
            not self.module.open
            and not self.module.banner) or not self.module.account else color
        color = Color.red() if not self.module.game else color

        return await self.send(
            self.module.create_discord_embed(subtitle=self.TITLE,
                                             info='\n\n'.join(statuses),
                                             color=color))
Ejemplo n.º 20
0
 def __init__(self, client):
     self.client = client
     self.client_color = Color.red()
     self.color_dict = {
         1: [Color.teal(), 'teal'],
         2: [Color.dark_teal(), 'dark_teal'],
         3: [Color.green(), 'green'],
         4: [Color.dark_green(), 'dark_green'],
         5: [Color.blue(), 'blue'],
         6: [Color.dark_blue(), 'dark_blue'],
         7: [Color.purple(), 'purple'],
         8: [Color.dark_purple(), 'dark_purple'],
         9: [Color.magenta(), 'magenta'],
         10: [Color.dark_magenta(), 'dark_magenta'],
         11: [Color.gold(), 'gold'],
         12: [Color.dark_gold(), 'dark_gold'],
         13: [Color.orange(), 'orange'],
         14: [Color.dark_orange(), 'dark_orange'],
         15: [Color.red(), 'red'],
         16: [Color.dark_red(), 'dark_red'],
         17: [Color.lighter_grey(), 'lighter_grey'],
         18: [Color.dark_grey(), 'grey'],
         19: [Color.light_grey(), 'light_grey'],
         20: [Color.darker_grey(), 'darker_grey']
     }
Ejemplo n.º 21
0
 async def example(self, ctx):
     embed = Embed(title='This is the embed title.',
                   description='This is the embed description',
                   color=Color.blue())
     embed.set_footer(text='This is the footer.')
     embed.set_image(
         url=
         'http://icons.iconarchive.com/icons/papirus-team/papirus-apps/512/discord-icon.png'
     )
     embed.set_thumbnail(
         url=
         'http://icons.iconarchive.com/icons/papirus-team/papirus-apps/512/discord-icon.png'
     )
     embed.set_author(
         name='Author',
         icon_url=
         'http://icons.iconarchive.com/icons/papirus-team/papirus-apps/512/discord-icon.png'
     )
     embed.add_field(name='This is the first field name.',
                     value='This is the first field name value.',
                     inline=False)
     embed.add_field(name='This is the second field name.',
                     value='This is the second field name value.',
                     inline=False)
     await ctx.send(embed=embed)
Ejemplo n.º 22
0
    async def _basic_search(self, ctx, query: str, category: str) -> None:
        """Basic search formatting."""
        is_nsfw = ctx.channel.is_nsfw() if hasattr(ctx.channel, "is_nsfw") else False

        async with ctx.typing():
            try:
                results = await self._search_logic(query, is_nsfw, category)
            except SafesearchFail:
                await ctx.send(
                    f":x: Sorry {ctx.author.mention}, your message contains filtered words, I've removed this message."
                )
                return await ctx.message.delete()
            count = len(results)

            # Ignore markdown when displaying
            query_display = utils.escape_mentions(query)
            query_display = utils.escape_markdown(query_display)

            # Return if no results
            if not count:
                return await ctx.send(f"No results found for `{query_display}`.")

            # Gets the first entry's data
            first_title = self.tomd.handle(
                results[0]["title"]).rstrip("\n").strip("<>")
            first_url = results[0]["url"]
            first_desc = self.tomd.handle(results[0]["desc"]).rstrip("\n")

            # Builds the substring for each of the other result.
            other_results: List[str] = []

            for result in results[1:count]:
                title = self.tomd.handle(result["title"]).rstrip("\n")
                url = result["url"]
                other_results.append(f"**{title}**\n{url}")

            other_msg = "\n\n".join(other_results).strip()

            # Builds message
            msg = textwrap.dedent(
                f"""
                [{first_title.strip("<>")}]({first_url.strip("<>")})\n
                {first_desc}\n
                {other_msg}
                """
            )

            msg = re.sub(
                r"(https?://(?:www\.)?[-a-zA-Z0-9@:%._+~#=]+\."
                r"[a-zA-Z0-9()]+\b[-a-zA-Z0-9()@:%_+.~#?&/=]*)",
                r"<\1>",
                msg,
            )

            embed = Embed(title="Search Results",
                          description=msg, color=Color.blue())
            embed.set_footer(
                text=f"Showing {count} results for {query_display}.")

            await ctx.send(embed=embed)
Ejemplo n.º 23
0
def random():
    # type: () -> Color

    tan = Color(0xBEAA3E)

    return choice([
        Color.teal(),
        Color.dark_teal(),
        Color.green(),
        Color.dark_green(),
        Color.blue(),
        Color.dark_blue(),
        Color.purple(),
        Color.dark_purple(),
        Color.magenta(),
        Color.dark_magenta(),
        Color.gold(),
        Color.dark_gold(),
        Color.orange(),
        Color.dark_orange(),
        Color.red(),
        Color.dark_red(),
        Color.lighter_grey(),
        Color.darker_grey(),
        Color.blurple(),
        tan,
    ])
Ejemplo n.º 24
0
 async def thank_leaderboard(self, ctx: commands.Context):
     """View a leaderboard of top helpers in the current server"""
     await ctx.trigger_typing()
     lb = (
         await UserModel.annotate(
             thank_count=Count("thanks", _filter=Q(thanks__guild_id=ctx.guild.id))
         )
         .filter(thank_count__gt=0)
         .order_by("-thank_count")
         .limit(5)
     )
     if not lb:
         return await ctx.send(
             embed=Embed(
                 title="Oopsy",
                 description="There are no thanks here yet!",
                 color=Color.red(),
             )
         )
     invis = "\u2800"
     embed = Embed(
         title="LeaderBoard",
         color=Color.blue(),
         description="\n\n".join(
             [
                 f"**{m.thank_count} Thanks**{invis * (4 - len(str(m.thank_count)))}<@!{m.id}>"
                 for m in lb
             ]
         ),
     )
     await ctx.send(embed=embed)
Ejemplo n.º 25
0
    async def list_watched_users(self,
                                 ctx: Context,
                                 update_cache: bool = True) -> None:
        """
        Gives an overview of the watched user list for this channel.

        The optional kwarg `update_cache` specifies whether the cache should
        be refreshed by polling the API.
        """
        if update_cache:
            if not await self.fetch_user_cache():
                await ctx.send(
                    f":x: Failed to update {self.__class__.__name__} user cache, serving from cache"
                )
                update_cache = False

        lines = []
        for user_id, user_data in self.watched_users.items():
            inserted_at = user_data['inserted_at']
            time_delta = self._get_time_delta(inserted_at)
            lines.append(f"• <@{user_id}> (added {time_delta})")

        lines = lines or ("There's nothing here yet.", )
        embed = Embed(
            title=
            f"{self.__class__.__name__} watched users ({'updated' if update_cache else 'cached'})",
            color=Color.blue())
        await LinePaginator.paginate(lines, ctx, embed, empty=False)
Ejemplo n.º 26
0
    async def send_cog_help(self, cog: commands.Cog) -> None:
        if cog.qualified_name in NO_ACCESS_COGS or not cog.help_check(self.context):
            raise self.command_not_found(cog.qualified_name)

        embed = Embed(
            title=f"Help for extension: `{cog.qualified_name}`",
            description="Ooooh ther's lots of fun stuff in here!",
            color=Color.blue(),
        )
        embed.add_field(
            name="What does this extension do?", value=cog.__doc__, inline=False
        )
        command = commands.Command

        commands_in_cog = [
            f"`{command.name}`"
            for command in cog.walk_commands()
            if command.parent is None
        ]

        embed.add_field(
            name="Commands:",
            value=(", ".join(commands_in_cog))
            if commands_in_cog
            else "No Commands Found!",
        )
        await self.dispatch_help(embed)
Ejemplo n.º 27
0
    async def ghrepo(self,
                     ctx: Context,
                     repo: str = "HotWired-Bot",
                     user: str = "The-Codin-Hole") -> None:
        """
        Show info about a given GitHub repository.

        This command uses the GitHub API and is limited to 1 use per 5 seconds to comply with the rules.
        """
        embed = Embed(color=Color.blue())
        async with await self.session.get(
                f"https://api.github.com/repos/{user}/{repo}") as resp:
            response = await resp.json()

        if resp.status in BAD_RESPONSES:
            await ctx.send(f"ERROR: {BAD_RESPONSES.get(resp.status)}")
            return

        if response["message"]:
            await ctx.send(f"ERROR: {response['message']}")
        if response["description"] == "":
            desc = "No description provided."
        else:
            desc = response["description"]

        stars = response["stargazers_count"]
        forks = response["forks_count"]
        cmd = f'git clone {response["clone_url"]}'
        embed.title = f"{repo} on GitHub"
        embed.description = f"**{desc}**\nStars: {stars} Forks: {forks}\n Command: {cmd}"

        await ctx.send(embed=embed)
Ejemplo n.º 28
0
    async def send_bot_help(
        self, mapping: Mapping[Optional[commands.Cog], List[commands.Command]]
    ) -> None:
        bot = self.context.bot
        embed = Embed(
            title=f"{bot.user.name} help",
            description=f"Here's everything I can do!",
            color=Color.blue(),
        )

        embed.set_footer(
            text="Please keep in mind that these extensions are case sensitive!"
        )

        for cog in self.context.bot.cogs.values():
            if (
                cog.qualified_name in NO_ACCESS_COGS
                or cog.hidden
                or not cog.cog_help_check(self.context)
            ):
                continue
            embed.add_field(
                name=cog.qualified_name,
                value=f"`{self.clean_prefix}help {cog.qualified_name}`",
            )
        await self.dispatch_help(embed)
Ejemplo n.º 29
0
 def rules_embed(prefix=None):
     '''
     Creates the embed representing the game rules
     prefix: str, representing the bot prefix
     '''
     rules_embed = Embed(
         title="Coup Rules",
         description=
         "At the start of their turn, the player can perform one action. Other players may block, challenge, or let the action pass. A block to a response may also be challenged.\nIf a player has over 10 coins, they are required to coup this turn.",
         color=Color.blue(),
     )
     rules_embed.add_field(name="Contessa", value="`Block assassination`")
     rules_embed.add_field(name="Double Contessa", value="`Block coup`")
     rules_embed.add_field(name="Assassin",
                           value="`Assassinate (-3 coins)`")
     rules_embed.add_field(name="Captain",
                           value="`Steal (+2 coins)`\n`Block steal`")
     rules_embed.add_field(name="Ambassador",
                           value="`Exchange cards`\n`Block steal`")
     rules_embed.add_field(name="Duke",
                           value="`Tax (+3 coins)`\n`Block foreign aid`")
     rules_embed.add_field(
         name="(General Ability)",
         value=
         "`Income (+1 coin)`\n`Foreign aid (+2 coins)`\n`Coup (-7 coins)`\n`Challenge action`"
     )
     if prefix is not None:
         rules_embed.set_footer(
             text=f"See {prefix}guide for gameplay guide")
     return rules_embed
Ejemplo n.º 30
0
def ex(args, message, client, invoke, sender):

    if len(args) is 0:
        yield from client.send_message(message.channel,
                                       embed=Embed(color=Color.blue(), description=(STATICS.HELP)))
    else:
        yield from client.send_message(message.channel, embed=Embed(color=Color.red(), description=(STATICS.INVALIDHELP)))