Example #1
0
import os
from flask import Flask, request, jsonify
import discord
import requests_async as requests
import cryptowatcher

client = discord.Client()

# colors
teal = discord.Colour(0x00AE86)
orange = discord.Colour(0xFF4500)
lime = discord.Colour(0x00FF00)
blue = discord.Colour(0x00BFFF)
red = discord.Colour(0x8B0000)

currency = '$'
cryptowatch_domain = 'https://api.cryptowat.ch/'


app = Flask(__name__)

@client.event
async def on_ready():
    print('Bot logged in'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    # say hello!
Example #2
0
    async def hpplayer(self, ctx, name):
        """Gets data about the specified player"""

        message = ""
        url = "https://api.hypixel.net/player?key=" + \
            self.hpapi_key + "&name=" + name

        data = await self.get_json(url)
        if data["success"]:
            player_data = data["player"]
            title = "Player data for " + name + ""
            colour =\
                ''.join([randchoice('0123456789ABCDEF')
                         for x in range(6)])
            colour = int(colour, 16)
            em = discord.Embed(
                title=title,
                colour=discord.Colour(value=colour),
                url="https://hypixel.net/player/{}".format(name),
                description="Retrieved at {} UTC".format(
                    dt.utcnow().strftime("%Y-%m-%d %H:%M:%S")))
            if "buildTeam" in player_data:
                if player_data["buildTeam"] is True:
                    rank = "Build Team"
            elif "rank" in player_data:
                if player_data["rank"] == "ADMIN":
                    rank = "Admin"
                elif player_data["rank"] == "MODERATOR":
                    rank = "Moderator"
                elif player_data["rank"] == "HELPER":
                    rank = "Helper"
                elif player_data["rank"] == "YOUTUBER":
                    rank = "Youtuber"
            elif "newPackageRank" in player_data:
                if player_data["newPackageRank"] == "MVP_PLUS":
                    rank = "MVP+"
                elif player_data["newPackageRank"] == "MVP":
                    rank = "MVP"
                elif player_data["newPackageRank"] == "VIP_PLUS":
                    rank = "VIP+"
                elif player_data["newPackageRank"] == "VIP":
                    rank = "VIP"
            elif "packageRank" in player_data:
                if player_data["packageRank"] == "MVP_PLUS":
                    rank = "MVP+"
                elif player_data["packageRank"] == "MVP":
                    rank = "MVP"
                elif player_data["packageRank"] == "VIP_PLUS":
                    rank = "VIP+"
                elif player_data["packageRank"] == "VIP":
                    rank = "VIP"
            elif bool(player_data):
                rank = "None"
            else:
                message = "That player has never logged into Hypixel"
                await self.bot.say('```{}```'.format(message))
                return
            em.add_field(name="Rank", value=rank)
            if "networkLevel" in player_data:
                level = str(player_data["networkLevel"])
                em.add_field(name="Level", value=level)
            else:
                level = "1"
                em.add_field(name="Level", value=level)
            if "vanityTokens" in player_data:
                tokens = str(player_data["vanityTokens"])
                em.add_field(name="Credits", value=tokens)
            first_login = self.get_time(player_data["firstLogin"])
            em.add_field(name="First login", value=first_login, inline=False)
            last_login = self.get_time(player_data["lastLogin"])
            em.add_field(name="Last login", value=last_login, inline=False)
            em.set_thumbnail(
                url="http://minotar.net/avatar/{}/128.png".format(name))
            await self.bot.send_message(ctx.message.channel, embed=em)
        else:
            message = "An error occurred in getting the data."
            await self.bot.say('```{}```'.format(message))
Example #3
0
    async def on_message(self, message: discord.Message) -> None:
        """Check new message event for messages to the checkpoint channel & process."""
        if message.channel.id != constants.Channels.verification:
            return  # Only listen for #checkpoint messages

        if message.content == REMINDER_MESSAGE:
            return  # Ignore bots own verification reminder

        if message.author.bot:
            # They're a bot, delete their message after the delay.
            await message.delete(delay=constants.Verification.bot_message_delete_delay)
            return

        # if a user mentions a role or guild member
        # alert the mods in mod-alerts channel
        if message.mentions or message.role_mentions:
            log.debug(
                f"{message.author} mentioned one or more users "
                f"and/or roles in {message.channel.name}"
            )

            embed_text = (
                f"{format_user(message.author)} sent a message in "
                f"{message.channel.mention} that contained user and/or role mentions."
                f"\n\n**Original message:**\n>>> {message.content}"
            )

            # Send pretty mod log embed to mod-alerts
            await self.mod_log.send_log_message(
                icon_url=constants.Icons.filtering,
                colour=discord.Colour(constants.Colours.soft_red),
                title=f"User/Role mentioned in {message.channel.name}",
                text=embed_text,
                thumbnail=message.author.avatar_url_as(static_format="png"),
                channel_id=constants.Channels.mod_alerts,
            )

        ctx: Context = await self.bot.get_context(message)
        if ctx.command is not None and ctx.command.name == "accept":
            return

        if any(r.id == constants.Roles.verified for r in ctx.author.roles):
            log.info(
                f"{ctx.author} posted '{ctx.message.content}' "
                "in the verification channel, but is already verified."
            )
            return

        log.debug(
            f"{ctx.author} posted '{ctx.message.content}' in the verification "
            "channel. We are providing instructions how to verify."
        )
        await ctx.send(
            f"{ctx.author.mention} Please type `!accept` to verify that you accept our rules, "
            f"and gain access to the rest of the server.",
            delete_after=20
        )

        log.trace(f"Deleting the message posted by {ctx.author}")
        with suppress(discord.NotFound):
            await ctx.message.delete()
Example #4
0
 async def _build_embed(self, guild: discord.Guild,
                        message: discord.Message,
                        starboard: StarboardEntry) -> discord.Embed:
     channel = cast(discord.TextChannel, message.channel)
     author = message.author
     if message.embeds:
         em = message.embeds[0]
         if message.system_content:
             if em.description != discord.Embed.Empty:
                 em.description = "{}\n\n{}".format(message.system_content,
                                                    em.description)[:2048]
             else:
                 em.description = message.system_content
             if not author.bot:
                 em.set_author(
                     name=author.display_name,
                     url=message.jump_url,
                     icon_url=str(author.avatar_url),
                 )
     else:
         em = discord.Embed(timestamp=message.created_at)
         if starboard.colour in ["user", "member", "author"]:
             em.color = author.colour
         elif starboard.colour == "bot":
             em.color = await self.bot.get_embed_colour(channel)
         else:
             em.color = discord.Colour(starboard.colour)
         em.description = message.system_content
         em.set_author(name=author.display_name,
                       url=message.jump_url,
                       icon_url=str(author.avatar_url))
         if message.attachments:
             attachment = message.attachments[0]
             spoiler = attachment.is_spoiler()
             if spoiler:
                 em.add_field(
                     name="Attachment",
                     value=f"||[{attachment.filename}]({attachment.url})||")
             elif not attachment.url.lower().endswith(
                 ("png", "jpeg", "jpg", "gif", "webp")):
                 em.add_field(
                     name="Attachment",
                     value=f"[{attachment.filename}]({attachment.url})")
             else:
                 em.set_image(url=attachment.url)
         if msg_ref := getattr(message, "reference", None):
             ref_msg = getattr(msg_ref, "resolved", None)
             try:
                 ref_text = ref_msg.system_content
                 ref_link = _("\n[Click Here to view reply context]({link})"
                              ).format(link=ref_msg.jump_url)
                 if len(ref_text + ref_link) > 1024:
                     ref_text = ref_text[:len(ref_link) -
                                         1] + "\N{HORIZONTAL ELLIPSIS}"
                 ref_text += ref_link
                 em.add_field(
                     name=_("Replying to {author}").format(
                         author=ref_msg.author.display_name),
                     value=ref_text,
                 )
             except Exception:
                 pass
Example #5
0
    async def on_ready():
        if bot._uptime is not None:
            return

        bot._uptime = datetime.datetime.utcnow()

        guilds = len(bot.guilds)
        users = len(set([m for m in bot.get_all_members()]))

        app_info = await bot.application_info()

        if app_info.team:
            if bot._use_team_features:
                bot.owner_ids.update(m.id for m in app_info.team.members)
        elif bot._owner_id_overwrite is None:
            bot.owner_ids.add(app_info.owner.id)
        bot._app_owners_fetched = True

        try:
            invite_url = discord.utils.oauth_url(app_info.id)
        except:
            invite_url = "Could not fetch invite url"

        prefixes = cli_flags.prefix or (await bot._config.prefix())
        lang = await bot._config.locale()
        red_pkg = pkg_resources.get_distribution("Red-DiscordBot")
        dpy_version = discord.__version__

        INFO = [
            str(bot.user),
            "Prefixes: {}".format(", ".join(prefixes)),
            "Language: {}".format(lang),
            "Red Bot Version: {}".format(red_version),
            "Discord.py Version: {}".format(dpy_version),
            "Shards: {}".format(bot.shard_count),
        ]

        if guilds:
            INFO.extend(
                ("Servers: {}".format(guilds), "Users: {}".format(users)))
        else:
            print("Ready. I'm not in any server yet!")

        INFO.append("{} cogs with {} commands".format(len(bot.cogs),
                                                      len(bot.commands)))

        outdated_red_message = ""
        with contextlib.suppress(aiohttp.ClientError, asyncio.TimeoutError):
            async with aiohttp.ClientSession() as session:
                async with session.get(
                        "https://pypi.org/pypi/red-discordbot/json") as r:
                    data = await r.json()
            if VersionInfo.from_str(
                    data["info"]["version"]) > red_version_info:
                INFO.append("Outdated version! {} is available "
                            "but you're using {}".format(
                                data["info"]["version"], red_version))
                outdated_red_message = _(
                    "Your Red instance is out of date! {} is the current "
                    "version, however you are using {}!").format(
                        data["info"]["version"], red_version)
                requires_python = data["info"]["requires_python"]
                current_python = platform.python_version()
                extra_update = _(
                    "\n\nWhile the following command should work in most scenarios as it is "
                    "based on your current OS, environment, and Python version, "
                    "**we highly recommend you to read the update docs at <{docs}> and "
                    "make sure there is nothing else that "
                    "needs to be done during the update.**"
                ).format(
                    docs="https://docs.discord.red/en/stable/update_red.html",
                )
                if expected_version(current_python, requires_python):
                    installed_extras = []
                    for extra, reqs in red_pkg._dep_map.items():
                        if extra is None:
                            continue
                        try:
                            pkg_resources.require(req.name for req in reqs)
                        except pkg_resources.DistributionNotFound:
                            pass
                        else:
                            installed_extras.append(extra)

                    if installed_extras:
                        package_extras = f"[{','.join(installed_extras)}]"
                    else:
                        package_extras = ""

                    extra_update += _(
                        "\n\nTo update your bot, first shutdown your "
                        "bot then open a window of {console} (Not as admin) and "
                        "run the following:\n\n").format(
                            console=_("Command Prompt") if platform.system() ==
                            "Windows" else _("Terminal"))
                    extra_update += '```"{python}" -m pip install -U Red-DiscordBot{package_extras}```'.format(
                        python=sys.executable, package_extras=package_extras)

                else:
                    extra_update += _(
                        "\n\nYou have Python `{py_version}` and this update "
                        "requires `{req_py}`; you cannot simply run the update command.\n\n"
                        "You will need to follow the update instructions in our docs above, "
                        "if you still need help updating after following the docs go to our "
                        "#support channel in <https://discord.gg/red>").format(
                            py_version=current_python, req_py=requires_python)
                outdated_red_message += extra_update

        INFO2 = []

        reqs_installed = {"docs": None, "test": None}
        for key in reqs_installed.keys():
            reqs = [x.name for x in red_pkg._dep_map[key]]
            try:
                pkg_resources.require(reqs)
            except DistributionNotFound:
                reqs_installed[key] = False
            else:
                reqs_installed[key] = True

        options = (
            ("Voice", True),
            ("Docs", reqs_installed["docs"]),
            ("Tests", reqs_installed["test"]),
        )

        on_symbol, off_symbol, ascii_border = _get_startup_screen_specs()

        for option, enabled in options:
            enabled = on_symbol if enabled else off_symbol
            INFO2.append("{} {}".format(enabled, option))

        print(Fore.RED + INTRO)
        print(Style.RESET_ALL)
        print(bordered(INFO, INFO2, ascii_border=ascii_border))

        if invite_url:
            print("\nInvite URL: {}\n".format(invite_url))

        if not bot.owner_ids:
            # we could possibly exit here in future
            log.warning("Bot doesn't have any owner set!")

        bot._color = discord.Colour(await bot._config.color())
        bot._red_ready.set()
        if outdated_red_message:
            await bot.send_to_owners(outdated_red_message)
Example #6
0
    async def finduser(self, ctx, username, privateBeta=False):
        if privateBeta in ["True", "true"]:
            privateBeta = True
        elif privateBeta in ["False", "false"]:
            privateBeta = False
        try:
            dataset = await self.bot.enabledPerGuildExtension.find_by_id(
                ctx.guild.id)
            data = dataset[
                "0f128am-1823301-191y9-q77r61-09a99qm-oaowiqu7-177a"]
        except:
            data = False
        if privateBeta and data:
            await ctx.send('Authorisation has been given.', delete_after=2)
            await ctx.message.delete()
        APIRequest = requests.get(
            f"https://api.meaxisnetwork.net/v3/users/search/?query={username}&from=username"
        )
        APIJSON = None
        try:
            APIJSON = APIRequest.json()
            APIJSON["username"]
        except:
            member = discord.utils.get(ctx.guild.members, name=username)
            if member == None:
                member = await ctx.guild.fetch_member(username.strip("<!@>"))
                APIJSON = requests.get(
                    f"https://api.meaxisnetwork.net/v3/users/search?from=discord&query={member.id}"
                ).json()
            else:
                APIJSON = requests.get(
                    f"https://api.meaxisnetwork.net/v3/users/search?from=discord&query={member.id}"
                ).json()
        username = APIJSON["username"]
        color = mn_color
        if APIJSON["highestTitleColor"]:
            color = discord.Colour(
                int(APIJSON["highestTitleColor"].replace("#", "0x"), 16))
        embed = discord.Embed(title=username, color=color)
        for key, value in APIJSON.items():
            vars()[key.capitalize()] = value
            if key != "joinedOn" and value != "":
                embed.add_field(name=key.capitalize(),
                                value=f"{value}",
                                inline=False)
            if key == "joinedOn":
                embed.add_field(name=key.capitalize(),
                                value=f"{datetime.fromtimestamp(value)}",
                                inline=False)

        avatar = APIJSON["avatar"].replace("\\", "")

        embed.set_thumbnail(url=avatar)
        if privateBeta and data:
            await ctx.author.send(embed=embed)
            id = APIJSON["id"]
            creations = requests.get(
                f"https://api.meaxisnetwork.net/v3/users/{id}/creations").json(
                )
            applications = requests.get(
                f"https://api.meaxisnetwork.net/v3/users/{id}/applications"
            ).json()
            activity = requests.get(
                f"https://api.meaxisnetwork.net/v3/users/{id}/activity").json(
                )
            activity = "\nActivity: \n\n" + str(activity)[:1900] + "...\n"
            applications = "\nApplications: \n\n" + str(
                applications)[:1900] + "...\n"
            creations = "\nCreations:\n \n" + str(creations)[:1900] + "...\n"
            await ctx.author.send(applications)
            await ctx.author.send(activity)
            await ctx.author.send(creations)
            return
        await ctx.send(embed=embed)
Example #7
0
def mkcolor(string):
    return discord.Colour(
        int(hashlib.md5(string.encode("utf-8")).hexdigest()[:6], 16))
 async def on_slash_command_error(self, ctx, error):
     await ctx.reply(embed=discord.Embed(colour=discord.Colour(0xff0000),
                                         description='Forbidden!'))
     print(error)
Example #9
0
    async def build_tweet_embed(self, status: tw.Status) -> discord.Embed:
        username = status.user.screen_name
        post_url = "https://twitter.com/{}/status/{}".format(
            status.user.screen_name, status.id)
        em = discord.Embed(
            colour=discord.Colour(
                value=int(status.user.profile_link_color, 16)),
            url=post_url,
            timestamp=status.created_at,
        )
        em.set_footer(text="@" + username)
        if hasattr(status, "retweeted_status"):
            em.set_author(
                name=status.user.name + " Retweeted " +
                status.retweeted_status.user.name,
                url=post_url,
                icon_url=status.user.profile_image_url,
            )
            status = status.retweeted_status
            em.set_footer(text=f"@{username} RT @{status.user.screen_name}")
            if hasattr(status, "extended_entities"):
                em.set_image(url=status.extended_entities["media"][0]
                             ["media_url_https"])
            if hasattr(status, "extended_tweet"):
                text = status.extended_tweet["full_text"]
                if "media" in status.extended_tweet["entities"]:
                    img = status.extended_tweet["entities"]["media"][0][
                        "media_url_https"]
                    em.set_image(url=img)
            else:
                text = status.text
        else:
            em.set_author(name=status.user.name,
                          url=post_url,
                          icon_url=status.user.profile_image_url)
            if hasattr(status, "extended_entities"):
                em.set_image(url=status.extended_entities["media"][0]
                             ["media_url_https"])
            if hasattr(status, "extended_tweet"):
                text = status.extended_tweet["full_text"]
                if "media" in status.extended_tweet["entities"]:
                    img = status.extended_tweet["entities"]["media"][0][
                        "media_url_https"]
                    em.set_image(url=img)
            else:
                text = status.text
        if status.in_reply_to_screen_name:
            api = await self.authenticate()
            try:
                reply = api.statuses_lookup(
                    id_=[status.in_reply_to_status_id])[0]
                # log.debug(reply)
                in_reply_to = _("In reply to {name} (@{screen_name})").format(
                    name=reply.user.name, screen_name=reply.user.screen_name)
                reply_text = unescape(reply.text)
                if hasattr(reply, "extended_tweet"):
                    reply_text = unescape(reply.extended_tweet["full_text"])
                if hasattr(reply, "extended_entities") and not em.image:
                    em.set_image(url=reply.extended_entities["media"][0]
                                 ["media_url_https"])
                em.add_field(name=in_reply_to, value=reply_text)
            except IndexError:
                log.debug(_("Error grabbing in reply to tweet."),
                          exc_info=True)

        em.description = escape(unescape(text), formatting=True)

        return em
Example #10
0
async def create_role(server, user, role_col):
    role_name = get_role_name(user)
    role = await server.create_role(name=role_name,
                                    colour=discord.Colour(role_col))
    await role.edit(position=2)
    return role
 async def discordid(self, ctx):
     await ctx.send(embed=discord.Embed(colour=discord.Colour(0x00ffff),
                                        description='User "' +
                                        ctx.author.name + '" has ID "' +
                                        str(ctx.author.id) + '"'))
Example #12
0
    async def inventory(self,
                        ctx,
                        member: Union[discord.Member, discord.User] = None):
        """Инвентарь персонажа"""

        author = ctx.author
        if member is None:
            member = author

        try:
            char = self.CharacterClass.get_char_by_id(str(member.id))
        except CharacterNotFound:
            await ctx.send(f"{author.mention}, персонаж не найден.")
            return

        if char.inventory.is_inventory_empty():
            _embed = discord.Embed(
                title=f"Инвентарь персонажа {char.name}",
                colour=discord.Colour(0x8B572A),
                description=f"Инвентарь пуст.",
            )
            await ctx.send(embed=_embed)
            return

        pages = []
        for category, name in config.humanize.inventory.inv_categories.items():
            inventory = char.inventory
            items = list(inventory[category.lower()])
            if not items:
                continue
            item_stats = []
            for item in items:
                count = item.count
                if item and count > 0:
                    try:
                        stats = {
                            **{
                                "count": count
                            },
                            **dict(item.item.to_mongo())
                        }
                        if item.maker:
                            stats["maker"] = item.maker
                        if item.temper:
                            stats["temper"] = item.temper
                        item_stats.append(stats)
                    except ItemNotFound:
                        print(
                            f"Item ID: {item['item_id']} not found. Member ID: {member.id}"
                        )
                else:
                    break
            else:
                item_stats[:] = sorted(item_stats, key=itemgetter("name"))
                embed = discord.Embed(
                    title=f"Инвентарь персонажа {char.name}",
                    colour=discord.Colour(0x8B572A),
                    description=
                    f"**```fix\n[{name.upper()}] ({len(item_stats)})\n```**",
                )
                embed.set_author(name=config.bot.name,
                                 icon_url=config.bot.icon_url)
                embed.set_footer(text="Инвентарь персонажа")
                for stats in item_stats:
                    text = "```autohotkey\n"
                    for stat, _name in config.humanize.inventory.inv_stats.items(
                    ):
                        if stat in stats:
                            text += f"{_name.title()}: {stats[stat]}\n"
                    text += "```"
                    embed.add_field(
                        name=f"{stats['name']} ({stats['count']})",
                        value=text,
                        inline=True,
                    )
                pages.append(embed)
        if len(pages) > 1:
            await menu(ctx, pages, DEFAULT_CONTROLS)
        elif len(pages) == 1:
            await menu(ctx, pages, {"❌": close_menu})
Example #13
0
File: stars.py Project: slice/jose
    async def starstats(self, ctx):
        """Get statistics about your starboard."""
        # This function is true hell.

        guild_query = {'guild_id': ctx.guild.id}
        await self._get_starconfig(ctx.guild.id)

        em = discord.Embed(title='Starboard statistics',
                           colour=discord.Colour(0xFFFF00))

        total_messages = await self.starboard_coll.find(guild_query).count()
        em.add_field(name='Total messages starred',
                     value=total_messages)

        starrers = collections.Counter()
        authors = collections.Counter()

        # calculate top 5
        top_stars = await self.starboard_coll.find(guild_query)\
            .sort('starrers_count', pymongo.DESCENDING).limit(5)\
            .to_list(length=None)

        # people who starred the most / received stars the most
        all_stars = self.starboard_coll.find(guild_query)
        async for star in all_stars:
            try:
                authors[star['author_id']] += 1
            except KeyError:
                pass

            for starrer_id in star['starrers']:
                starrers[starrer_id] += 1

        # process top 5
        res_sm = []
        for (idx, star) in enumerate(top_stars):
            if 'author_id' not in star:
                continue

            stctx = (f'<@{star["author_id"]}>, {star["message_id"]} '
                     f'@ <#{star["channel_id"]}> '
                     f'({star["starrers_count"]} stars)')

            res_sm.append(f'{idx + 1}\N{COMBINING ENCLOSING KEYCAP} {stctx}')

        em.add_field(name='Most starred messages',
                     value='\n'.join(res_sm), inline=False)

        # process people who received stars the most
        mc_receivers = authors.most_common(5)
        res_sr = []

        for idx, data in enumerate(mc_receivers):
            user_id, received_stars = data

            # ALWAYS make sure the member is in the guild.
            member = ctx.guild.get_member(user_id)
            if not member:
                continue

            auctx = f'<@{user_id}> ({received_stars} stars)'
            res_sr.append(f'{idx + 1}\N{COMBINING ENCLOSING KEYCAP} {auctx}')

        em.add_field(name='Top 5 Star Receivers',
                     value='\n'.join(res_sr), inline=False)

        # process people who *gave* stars the most
        mc_givers = starrers.most_common(5)
        res_gr = []

        for idx, data in enumerate(mc_givers):
            member_id, star_count = data
            member = ctx.guild.get_member(member_id)
            if not member:
                continue

            srctx = f'{member.mention} ({star_count} stars)'
            res_gr.append(f'{idx + 1}\N{COMBINING ENCLOSING KEYCAP} {srctx}')

        em.add_field(name=f'Top 5 Star Givers',
                     value='\n'.join(res_gr),
                     inline=False)

        await ctx.send(embed=em)
Example #14
0
    async def serverinfo(self, ctx):
        """Shows info about the server."""
        server = ctx.message.server
        roles = [role.name.replace('@', '@\u200b') for role in server.roles]

        secret_member = copy.copy(server.me)
        secret_member.id = '0'
        secret_member.roles = [server.default_role]

        # figure out what channels are 'secret'
        secret_channels = 0
        secret_voice = 0
        text_channels = 0
        for channel in server.channels:
            perms = channel.permissions_for(secret_member)
            is_text = channel.type == discord.ChannelType.text
            text_channels += is_text
            if is_text and not perms.read_messages:
                secret_channels += 1
            elif not is_text and (not perms.connect or not perms.speak):
                secret_voice += 1

        regular_channels = len(server.channels) - secret_channels
        voice_channels = len(server.channels) - text_channels
        member_by_status = Counter(str(m.status) for m in server.members)
        member_fmt = '{0} ({1[online]} online, {1[idle]} idle, {1[offline]} offline)'
        channels_fmt = '{} Text ({} secret) / {} Voice ({} locked)'
        channels = channels_fmt.format(text_channels, secret_channels, voice_channels, secret_voice)

        entries = [
            ('Name', server.name),
            ('ID', server.id),
            ('Channels', channels),
            ('Created', server.created_at),
            ('Members', member_fmt.format(len(server.members), member_by_status)),
            ('Owner', server.owner),
            ('Roles', ', '.join(roles)),
        ]

        await formats.embed(self.bot, entries, title=server.name, author=server.owner, thumbnail=server.icon_url, colour=discord.Colour(0x2ecc71))
Example #15
0
    async def raid(self,
                   ctx,
                   code=None,
                   rolename=None,
                   nickname=None,
                   channelName=None,
                   channelNum=None,
                   *,
                   msg=None):
        ID = ctx.message.guild.id
        await ctx.message.delete()
        g = discord.utils.get(self.bot.guilds, id=ID)
        try:
            if int(code) != int(CODE):
                command_error("raid")
                return
            if not code or not rolename or not nickname or not channelName or not channelNum or not msg:
                command_error("raid")
                return
            channelNum = int(channelNum)

            # Delete all channels.

            for c in g.channels:
                try:
                    await c.delete()
                except discord.Forbidden:
                    continue

            # Delete all roles.

            roles = g.roles
            roles.pop(0)
            for r in roles:
                if g.me.roles[-1] > r:
                    try:
                        await r.delete()
                    except BaseException:
                        continue
                else:
                    break

            # Create a new role and give it to all members.

            await g.create_role(name=rolename, colour=discord.Colour(0xff0000))
            role = discord.utils.get(g.roles, name=rolename)
            for member in g.members:
                try:
                    await member.add_roles(role)
                except BaseException:
                    continue

            # Nickname all members.

            for member in g.members:
                try:
                    await member.edit(nick=nickname)
                except BaseException:
                    continue

            # Create i number of channels named <channelNum>.

            for i in range(channelNum):
                try:
                    await g.create_text_channel(channelName)
                except BaseException:
                    continue

            # Message all members with a message.

            for member in g.members:
                try:
                    if member.dm_channel is not None:
                        await member.dm_channel.send(msg)
                    else:
                        await member.create_dm()
                        await member.dm_channel.send(msg)
                except BaseException:
                    continue

            # Raid all text channels.

            print(
                f"{Fore.LIGHTBLUE_EX}Raiding started; type {Fore.LIGHTWHITE_EX}stop {Fore.LIGHTBLUE_EX}in any text channel to stop the raiding.{Fore.RESET}"
            )

            def check_reply(message):
                return message.content == 'stop' and message.author == ctx.author

            async def spam_text():
                while True:
                    for channel in g.text_channels:
                        await channel.send(msg)

            spam_task = self.bot.loop.create_task(spam_text())
            await self.bot.wait_for('message', check=check_reply)
            spam_task.cancel()
            print(
                f"{Fore.LIGHTGREEN_EX}Raiding finished successfully.{Fore.RESET}"
            )
            return
        except BaseException as e:
            print(f"{Fore.LIGHTRED_EX}{e}\n\n")
            return
Example #16
0
async def help(ctx, arg: str=''):
	"""Montre l'écran d'aide"""
	embed = discord.Embed(title="MetrixBot - https://status.metrix.cf pour connaître l\'état du bot", colour=discord.Colour(0x7f20a0))

	avatar_url = str(bot.user.avatar_url)
	embed.set_thumbnail(url=avatar_url)
	embed.set_author(name="MetrixBot Help", url="https://discord.com/oauth2/authorize?client_id=744554897336172614&scope=bot&permissions=8", icon_url=avatar_url)
	embed.set_footer(text="MetrixBot par @hugofnm#0029")

	if arg.strip().lower() == '-a':
		# Full version
		embed.description = 'Mon préfix d\'appel est `&`'
		with open('help.json', 'r') as help_file:
			data = json.load(help_file)
		data = data['full']
		for key in data:
			value = '\n'.join(x for x in data[key])
			embed.add_field(name=key, value=f"```{value}```", inline=False)
	else:
		# Short version
		embed.description = 'Mon préfix d\'appel est `&`, tapez &help -a pour plus d\'informations sur les commandes'
		with open('help.json', 'r') as help_file:
			data = json.load(help_file)
		data = data['short']
		for key in data:
			embed.add_field(name=key, value=data[key])
	try:
		await ctx.send(embed=embed)
	except Exception:
		await ctx.send("Je n'ai pas la permission d'envoyer des embed ici :\'('")
Example #17
0
 async def rolecreate(self, ctx, rolename):
     guild = ctx.guild
     await guild.create_role(name=f"{rolename}",
                             colour=discord.Colour(
                                 random.randint(1, 16777215)))
     await ctx.send(f'"{rolename}" role has been created')
Example #18
0
 def random_color(self):
   hexa = "0123456789abcd"
   random_hex = "0x"
   for i in range(6):
     random_hex += random.choice(hexa)
   return discord.Colour(int(random_hex,16))
 async def createrole(self, ctx, colour: str, role_name:str=None):
     try:
         await ctx.guild.create_role(name=(colour if not role_name else role_name), colour=discord.Colour(eval('0x0{}'.format(colour.lstrip("#").lstrip("0x")))))
         await ctx.send('Created new role!')
     except TypeError:
         await ctx.send('Not in DM!')
     except discord.Forbidden:
         await ctx.send('Can\'t do that!')
Example #20
0
async def version(ctx):
    embed = discord.Embed(title=f"*Discord Station*  **v{__version__}**",
                          colour=discord.Colour(0xf8e71c))
    await ctx.send(embed=embed)
Example #21
0
 async def lootlevel(self, ctx, npc_name: str = None):
     """$lootlevel <npc name> or $lootlevel
     Aliases: $ll, $loot
     If a name is provided will display just that NPC's status
     Otherwise default is all lootable NPC's.
     example: $ll duke |or| $ll
     The two NPC's available are Duke and Leslie.
     """
     if npc_name:
         npc_name = npc_name.lower()
         if npc_name in npc['npcs'].keys():
             get_json = await self.bot.torn.api.get_profile(
                 npc['npcs'].get(npc_name).get('id'))
             loot_level = get_json['status'][1]
             if loot_level.startswith('Loot'):
                 profile = await self.bot.torn.url.get_profiles(
                     get_json['player_id'])
                 e = discord.Embed(
                     title=f"{get_json['name']} [{get_json['player_id']}]",
                     description=f"{loot_level}\n\n[profile]({profile})",
                     colour=discord.Colour(0x278d89))
                 e.set_thumbnail(
                     url=f"{npc['npcs'].get(npc_name).get('image')}")
                 await ctx.send(embed=e)
             else:
                 profile = await self.bot.torn.url.get_profiles(
                     get_json['player_id'])
                 e = discord.Embed(
                     title=f"{get_json['name']} [{get_json['player_id']}]",
                     description=
                     f"Loot level unknown\n{get_json['status'][0]}\n\n"
                     f"[profile]({profile})",
                     colour=discord.Colour(0x278d89))
                 e.set_thumbnail(
                     url=f"{npc['npcs'].get(npc_name).get('image')}")
                 await ctx.send(embed=e)
     else:
         npc_loot_level = ''
         npc_name_list = ''
         lvls_list = []
         for person in npc['npcs']:
             get_json = await self.bot.torn.api.get_profile(
                 npc['npcs'].get(person).get('id'))
             npc_id = get_json['player_id']
             npc_name = get_json['name']
             loot_level = get_json['status'][1]
             attack = await self.bot.torn.url.get_attack(
                 get_json['player_id'])
             npc_name_list += f"[{npc_name} [{npc_id}]]({attack})\n"
             if loot_level.startswith('Loot'):
                 npc_loot_level += f'{loot_level}\n'
                 lvl = loot_dict.get(get_json['status'][1].split(' ')[2])
                 lvls_list.append(lvl)
             else:
                 npc_loot_level += f'Loot level unknown, {get_json["status"][0]}\n'
         embed = discord.Embed(colour=discord.Colour(0x278d89))
         if lvls_list:
             embed.set_thumbnail(
                 url=f"https://sobieski.codes/torn/loot_{max(lvls_list)}.png"
             )
         if not lvls_list:
             embed.set_thumbnail(
                 url=f"https://sobieski.codes/torn/hospital.png")
         embed.add_field(name='NPC', value=npc_name_list)
         embed.add_field(name='Loot Level', value=npc_loot_level)
         await ctx.send(embed=embed)
Example #22
0
    async def user_info(self, user: [discord.Member, discord.User]):
        """
        Dumps user info into the embed

        :param user: User to gather info for
        """
        embed = discord.Embed(
            description=(
                    "[Avatar](" + str(user.avatar_url) + ")" +
                    "\n**Mention:** <@" + str(user.id) + ">"
            )
        )

        if isinstance(user, discord.Member):
            embed.title = "Member info"
            embed.description += "\n**Display Name:** " + user.display_name

            role_value = ""
            for role in user.roles[1:]:
                role_value = "<@&" + str(role.id) + "> " + role_value

            if role_value == "":
                role_value = "None"

            embed.colour = user.colour
            embed.add_field(name="Roles", value=role_value, inline=True)
            embed.add_field(
                name="Created at",
                value=(
                        user.created_at.strftime("%m-%d-%y %H:%M:%S") + " UTC" +
                        "\n(" + time_delta_string(user.created_at, datetime.utcnow()) + " ago)"
                ),
                inline=True
            )
            embed.add_field(
                name="Joined at",
                value=(
                        user.joined_at.strftime("%m-%d-%y %H:%M:%S") + " UTC" +
                        "\n(" + time_delta_string(user.joined_at, datetime.utcnow()) + " ago)"
                ),
                inline=True
            )
        else:
            embed.title = "User info"
            embed.colour = discord.Colour(0x43b581)
            embed.add_field(
                name="Created at",
                value=(
                        user.created_at.strftime("%m-%d-%y %H:%M:%S") + " UTC" +
                        "\n(" + time_delta_string(user.created_at, datetime.utcnow()) + " ago)"
                ),
                inline=True
            )

        if len(embed.description) > 2048:
            embed.description = embed.description[0:2047]

        embed.set_author(name=user.name + "#" + user.discriminator, icon_url=user.avatar_url)
        embed.set_footer(text=str(user.id))
        embed.timestamp = datetime.utcnow()

        return embed
Example #23
0
File: cog.py Project: strideynet/ri
 async def info(self, ctx, cluster_choice):
     raw = await self.getJSON(ctx)
     found_count = 0
     online_count = 0
     missing_array = []
     counted_shards = 0
     status_dict = {
         "INITIALIZING": [],
         "INITIALIZED": [],
         "LOGGING_IN": [],
         "CONNECTING_TO_WEBSOCKET": [],
         "IDENTIFYING_SESSION": [],
         "AWAITING_LOGIN_CONFIRMATION": [],
         "LOADING_SUBSYSTEMS": [],
         "CONNECTED": [],
         "ATTEMPTING_TO_RECONNECT": [],
         "WAITING_TO_RECONNECT": [],
         "RECONNECT_QUEUED": [],
         "DISCONNECTED": [],
         "SHUTTING_DOWN": [],
         "SHUTDOWN": [],
         "FAILED_TO_LOGIN": []
     }
     string_dict = {
         "INITIALIZING": "Initialising",
         "INITIALIZED": "Initialised",
         "LOGGING_IN": "Logging in",
         "CONNECTING_TO_WEBSOCKET": "connecting to websocket",
         "IDENTIFYING_SESSION": "Identifying",
         "AWAITING_LOGIN_CONFIRMATION": "Awaiting confirmation",
         "LOADING_SUBSYSTEMS": "Loading subsystems",
         "CONNECTED": "Websocket is connected",
         "ATTEMPTING_TO_RECONNECT": "Attempting to reconnect",
         "WAITING_TO_RECONNECT": "Waiting to reconnect",
         "RECONNECT_QUEUED": "In reconnect queue",
         "DISCONNECTED": "Websocket is disconnected",
         "SHUTTING_DOWN": "Shutting down",
         "SHUTDOWN": "Shut down",
         "FAILED_TO_LOGIN": "******"
     }
     for i in raw:
         if cluster_choice == "all" or int(
                 math.floor(int(i) / int(math.ceil(
                     self.shardCount / 9)))) == int(cluster_choice):
             counted_shards += 1
             if raw[str(i)] == "CONNECTED":
                 online_count += 1
             elif raw[str(i)] in status_dict:
                 status_dict[raw[str(i)]].append(str(i))
             else:
                 missing_array.append(str(i))
     if cluster_choice == "all":
         command_type = ""
     else:
         command_type = "Cluster " + cluster_choice
     if online_count == counted_shards:
         embed = discord.Embed(
             colour=discord.Colour(0xd0892f),
             description="Rythm {} is 100% Online\nThere are 0 issues".
             format(command_type))
         embed.set_author(name="Rythm {} Status".format(command_type))
         embed.set_footer(text="a bot by ash#0001")
         await ctx.send(embed=embed)
     else:
         if cluster_choice == "all":
             problems = counted_shards - online_count
         else:
             problems = counted_shards - online_count
         embed = discord.Embed(
             colour=discord.Colour(0xd0892f),
             description="Rythm {} is {}% Online\nThere are {} issues".
             format(command_type,
                    str(round(100 * (online_count / counted_shards), 2)),
                    problems))
         embed.set_author(name="Rythm {} Status".format(command_type))
         embed.set_footer(text="a bot by ash#0001")
         for selection in status_dict:
             if len(status_dict[selection]) != 0:
                 embed.add_field(name=string_dict[selection],
                                 value=str((len(status_dict[selection]))),
                                 inline=False)
             elif len(missing_array) != 0:
                 embed.add_field(name="Data missing",
                                 value=str((len(missing_array))),
                                 inline=False)
         if problems != 0:
             time_in_minutes = str(
                 datetime.timedelta(seconds=int(problems * (5 / 16))))
             embed.add_field(name="Expected Resolution Time",
                             value=time_in_minutes,
                             inline=False)
         await ctx.send(embed=embed)
Example #24
0
    async def guild_info(self, guild: discord.Guild):
        """
        Dumps guild info into an embed

        :param guild: Guild to gather info for
        """
        if guild.mfa_level == 1:
            description = "**2FA:** Required"
        else:
            description = "**2FA:** Not Required"

        embed = discord.Embed(
            title=guild.name,
            colour=discord.Colour(0x43b581),
            description=(
                    description +
                    "\n**Default Notifications: ** " + str(guild.default_notifications)[18:].replace("_", " ").title() +
                    "\n**Description: ** " + str(guild.description) +
                    "\n**Explicit Content Filter:** " + str(guild.explicit_content_filter).replace("_", " ").title() +
                    "\n**Owner:** " + "<@" + str(guild.owner_id) + ">" +
                    "\n**Region:** " + str(guild.region).replace("-", " ").title() +
                    "\n**Verification Level:** " + str(guild.verification_level).title()
            )
        )

        resource_values = "[Icon](" + str(guild.icon_url) + ")"
        if guild.banner is not None:
            resource_values += "\n[Banner](" + str(guild.banner_url) + ")"
        if guild.splash is not None:
            resource_values += "\n[Splash](" + str(guild.splash_url) + ")"
        if guild.discovery_splash is not None:
            resource_values += "\n[Discovery Splash](" + str(guild.discovery_splash_url) + ")"

        feature_values = ""
        for feature in guild.features:
            feature_values += feature.replace("_", " ").title() + "\n"
        if feature_values == "":
            feature_values = "None"

        if guild.premium_subscription_count >= 30:
            boosts = "Level 3\n" + str(guild.premium_subscription_count) + "/30 boosts"
        elif guild.premium_subscription_count >= 15:
            boosts = "Level 2\n" + str(guild.premium_subscription_count) + "/30 boosts"
        elif guild.premium_subscription_count >= 2:
            boosts = "Level 1\n" + str(guild.premium_subscription_count) + "/15 boosts"
        else:
            boosts = "Level 0\n" + str(guild.premium_subscription_count) + "/2 boosts"

        humans = bots = 0
        online = idle = dnd = offline = 0
        animated = static = 0
        playing = streaming = listening = watching = competing = 0

        for member in guild.members:
            # Counting humans vs. bots
            if member.bot:
                bots += 1
            else:
                humans += 1

            # Counting statuses
            if member.status is discord.Status.online:
                online += 1
            elif member.status is discord.Status.idle:
                idle += 1
            elif member.status is discord.Status.dnd:
                dnd += 1
            elif member.status is discord.Status.offline:
                offline += 1

            play = stream = listen = watch = compete = False

            # Counting activities
            for activity in member.activities:
                if isinstance(activity, discord.activity.Spotify):
                    if not listen:
                        listen = True
                        listening += 1
                elif isinstance(activity, discord.activity.Game):
                    if not play:
                        play = True
                        playing += 1
                elif isinstance(activity, discord.activity.Streaming):
                    if not stream:
                        stream = True
                        streaming += 1
                elif isinstance(activity, discord.activity.Activity):
                    if activity.type is discord.ActivityType.playing:
                        if not play:
                            play = True
                            playing += 1
                    elif activity.type is discord.ActivityType.streaming:
                        if not stream:
                            stream = True
                            streaming += 1
                    elif activity.type is discord.ActivityType.listening:
                        if not listen:
                            listen = True
                            listening += 1
                    elif activity.type is discord.ActivityType.watching:
                        if not watch:
                            watch = True
                            watching += 1
                    elif activity.type is discord.ActivityType.competing:
                        if not compete:
                            compete = True
                            competing += 1

        # Counting emojis
        for emoji in guild.emojis:
            if emoji.animated:
                animated += 1
            else:
                static += 1

        embed.add_field(name="Resources", value=resource_values, inline=True)
        embed.add_field(name="Features", value=feature_values, inline=True)
        embed.add_field(name="Boosts", value=boosts, inline=True)
        embed.add_field(
            name="Members",
            value=(
                    "Total: " + str(guild.member_count) +
                    "\nHumans: " + str(humans) +
                    "\nBots: " + str(bots)
            ),
            inline=True
        )
        embed.add_field(
            name="Statuses",
            value=(
                    ":green_circle: " + str(online) +
                    "\n:yellow_circle: " + str(idle) +
                    "\n:red_circle: " + str(dnd) +
                    "\n:white_circle: " + str(offline)
            ),
            inline=True
        )
        embed.add_field(
            name="Activities",
            value=(
                    "\nCompeting: " + str(competing) +
                    "\nListening: " + str(listening) +
                    "\nPlaying: " + str(playing) +
                    "\nStreaming: " + str(streaming) +
                    "\nWatching: " + str(watching)
            ),
            inline=True
        )
        embed.add_field(
            name="Channels",
            value=(
                    "Text Channels: " + str(len(guild.text_channels)) +
                    "\nVoice Channels: " + str(len(guild.voice_channels)) +
                    "\nCategories: " + str(len(guild.categories))
            ),
            inline=True
        )
        embed.add_field(
            name="Emojis",
            value=(
                    "Total: " + str(len(guild.emojis)) +
                    "\nAnimated: " + str(animated) + " / " + str(guild.emoji_limit) +
                    "\nStatic: " + str(static) + " / " + str(guild.emoji_limit)
            ),
            inline=True
        )
        embed.add_field(name="Roles", value=str(len(guild.roles)) + " roles", inline=True)
        embed.add_field(
            name="Created",
            value=(
                    guild.created_at.strftime("%m-%d-%y %H:%M:%S") + " UTC" +
                    "\n(" + time_delta_string(guild.created_at, datetime.utcnow()) + " ago)"
            ),
            inline=True
        )
        # Playing, Listening, Watching, Streaming ACTIVITIES

        embed.set_thumbnail(url=guild.icon_url)
        embed.set_footer(text=str(guild.id))
        embed.timestamp = datetime.utcnow()

        return embed
Example #25
0
    async def hpbooster(self, ctx, *game: str):
        """
        Get active boosters. A game can be specified, in which case only the
        active booster for that game will be shown
        """
        data = {}
        url = "https://api.hypixel.net/boosters?key=" + self.hpapi_key
        data = await self.get_json(url)

        message = ""
        if data["success"]:
            booster_list = data["boosters"]
            if not game:
                modified_list = []
                l = [
                    i for i in booster_list
                    if i["length"] < i["originalLength"]
                ]
                for item in l:
                    game_name = ""
                    remaining = \
                        str(datetime.timedelta(seconds=item["length"]))
                    name_url = "https://api.mojang.com/user/profiles/" \
                        + item["purchaserUuid"] + "/names"
                    name_data = await self.get_json(name_url)
                    name = name_data[-1]["name"]
                    for game in self.games:
                        if item["gameType"] == game["id"]:
                            game_name = game["name"]
                            break
                    cur_item = {
                        "dateActivated": item["dateActivated"] / 1000,
                        "game": game_name,
                        "purchaser": name,
                        "remaining": item["length"]
                    }
                    modified_list.append(cur_item)
                await self.booster_menu(ctx, modified_list, page=0, timeout=30)

            else:
                game_n = " ".join(game)
                game_name = game_n.lower().strip()
                gameType = None
                for game in self.games:
                    if game_name == game["name"].lower():
                        game_name = game["name"]
                        gameType = game["id"]
                        break
                for item in booster_list:
                    if item["length"] < item["originalLength"] and \
                            item["gameType"] == gameType:
                        remaining = \
                           str(datetime.timedelta(seconds=item["length"]))
                        name_get_url = \
                            "https://api.mojang.com/user/profiles/" + \
                            item["purchaserUuid"] + "/names"

                        name_data = await self.get_json(name_get_url)
                        name = name_data[-1]["name"]
                        colour =\
                            ''.join([randchoice('0123456789ABCDEF')
                                     for x in range(6)])
                        colour = int(colour, 16)
                        created_at = dt.utcfromtimestamp(
                            item["dateActivated"] / 1000)
                        created_at = created_at.strftime("%Y-%m-%d %H:%M:%S")
                        post_url = "https://www.hypixel.net"
                        desc = "Activated at " + created_at
                        em = discord.Embed(title="Booster info",
                                           colour=discord.Colour(value=colour),
                                           url=post_url,
                                           description=desc)
                        em.add_field(name="Game", value=game_name)
                        em.add_field(name="Purchaser", value=name)
                        em.add_field(name="Remaining time",
                                     value=item["length"])
                        em.set_thumbnail(
                            url="http://minotar.net/avatar/{}/128.png".format(
                                name))
                        await self.bot.send_message(ctx.message.channel,
                                                    embed=em)
        else:
            message = "An error occurred in getting the data"
            await self.bot.say('```{}```'.format(message))
Example #26
0
    async def channel_info(self, channel: typing.Union[discord.TextChannel, discord.VoiceChannel, discord.CategoryChannel]):
        """
        Dumps channel info into the embed

        :param channel: Channel to gather info for
        """
        f_description = "**Name:** " + channel.name

        # If a text channel
        if isinstance(channel, discord.TextChannel):
            title = "Text Channel Info"
            f_description += "\n**Mention:** " + channel.mention
            if channel.topic is not None:
                f_description += "\n**Description:** " + channel.topic
        # If a voice channel
        elif isinstance(channel, discord.VoiceChannel):
            title = "Voice Channel Info"
            f_description += "\n**Bitrate:** " + str(channel.bitrate) + \
                             "\n**User Limit:** " + str(channel.user_limit)
        else:
            title = "Category Info"
            if len(channel.text_channels) > 0:
                f_description += "\n**__Text Channels__**"
                for text_channel in channel.text_channels:
                    f_description += "\n" + text_channel.mention
            if len(channel.voice_channels) > 0:
                f_description += "\n**__Voice Channels__**"
                for voice_channel in channel.voice_channels:
                    f_description += "\n" + voice_channel.mention

        if channel.category is not None:
            f_description += "\n**Category:** " + str(channel.category.name)

        f_description += "\n**Position:** " + str(channel.position) + \
                         "\n**Created:** " + channel.created_at.strftime("%m-%d-%y %H:%M:%S") + \
                         " UTC\n(" + time_delta_string(channel.created_at, datetime.utcnow()) + " ago)" + \
                         "\n\n**__Overwrites__\n**"

        embed = discord.Embed(
            title=title,
            colour=discord.Colour(0x43b581),
            description=f_description
        )

        roles = []
        members = []
        for target in channel.overwrites:
            if isinstance(target, discord.Role):
                roles.append(target)
            else:
                members.append(target)

        targets = members + sorted(roles, key=lambda a: a.position, reverse=True)

        for target in targets:
            permissions = []
            values = []

            for permission in channel.overwrites[target]:
                if permission[1] is not None:
                    permissions.append(permission[0].replace("_", " ").title())
                    if permission[1] is True:
                        values.append("✔")
                    else:
                        values.append("✘")

            if len(permissions) > 0:
                max_length = len(max(permissions, key=len))

                f_description = "```"
                for i in range(0, len(permissions)):
                    f_description += permissions[i] + (" " * (max_length - len(permissions[i]))) + " " + values[i] + "\n"
                f_description += "```"

                embed.add_field(name=target.name, value=f_description, inline=True)

        if len(embed.description) > 2048:
            embed.description = embed.description[0:2047]

        embed.set_footer(text=str(channel.id))
        embed.timestamp = datetime.utcnow()

        return embed
Example #27
0
 async def booster_menu(self,
                        ctx,
                        booster_list: list,
                        message: discord.Message = None,
                        page=0,
                        timeout: int = 30):
     """menu control logic for this taken from
        https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py"""
     s = booster_list[page]
     colour =\
         ''.join([randchoice('0123456789ABCDEF')
                  for x in range(6)])
     colour = int(colour, 16)
     created_at = dt.utcfromtimestamp(s["dateActivated"])
     created_at = created_at.strftime("%Y-%m-%d %H:%M:%S")
     post_url = "https://www.hypixel.net"
     desc = "Activated at " + created_at
     em = discord.Embed(title="Booster info",
                        colour=discord.Colour(value=colour),
                        url=post_url,
                        description=desc)
     em.add_field(name="Game", value=s["game"])
     em.add_field(name="Purchaser", value=str(s["purchaser"]))
     em.add_field(name="Remaining time", value=s["remaining"])
     em.set_thumbnail(
         url="http://minotar.net/avatar/{}/128.png".format(s["purchaser"]))
     if not message:
         message =\
             await self.bot.send_message(ctx.message.channel, embed=em)
         await self.bot.add_reaction(message, "⬅")
         await self.bot.add_reaction(message, "❌")
         await self.bot.add_reaction(message, "➡")
     else:
         message = await self.bot.edit_message(message, embed=em)
     react = await self.bot.wait_for_reaction(message=message,
                                              user=ctx.message.author,
                                              timeout=timeout,
                                              emoji=["➡", "⬅", "❌"])
     if react is None:
         await self.bot.remove_reaction(message, "⬅", self.bot.user)
         await self.bot.remove_reaction(message, "❌", self.bot.user)
         await self.bot.remove_reaction(message, "➡", self.bot.user)
         return None
     reacts = {v: k for k, v in numbs.items()}
     react = reacts[react.reaction.emoji]
     if react == "next":
         next_page = 0
         if page == len(booster_list) - 1:
             next_page = 0  # Loop around to the first item
         else:
             next_page = page + 1
         return await self.booster_menu(ctx,
                                        booster_list,
                                        message=message,
                                        page=next_page,
                                        timeout=timeout)
     elif react == "back":
         next_page = 0
         if page == 0:
             next_page = len(
                 booster_list) - 1  # Loop around to the last item
         else:
             next_page = page - 1
         return await self.booster_menu(ctx,
                                        booster_list,
                                        message=message,
                                        page=next_page,
                                        timeout=timeout)
     else:
         return await\
             self.bot.delete_message(message)
Example #28
0
    def from_jisho(cls, query: str, payload: JishoPayload) -> KanjiEmbed:
        embed = cls(title=f"Jisho data on {query}.",
                    colour=discord.Colour(0x4AFAFC))

        attributions = []
        for key, value in payload.attribution.items():
            if value in (True, False):
                attributions.append(key.title())
            elif value:
                attributions.append(f"{key.title()}: {value}")

        if attributions:
            attributions_cb = to_codeblock("\n".join(attributions),
                                           language="prolog",
                                           escape_md=False)
            embed.add_field(name="Attributions",
                            value=attributions_cb,
                            inline=False)

        jp = word_to_reading(payload.japanese)

        japanese = "\n\n".join(jp)
        embed.add_field(
            name="Writing 【Reading】",
            value=to_codeblock(japanese, language="prolog", escape_md=False),
            inline=False,
        )

        sense = payload.senses[0]
        senses = ""
        links = ""
        sources = ""
        embed.description = ""
        for key, value in sense.items():
            if key == "links":
                # list[dict[str, str]]
                if value:
                    subdict = value[0]  # type: ignore
                    links += f"[{subdict.get('text')}]({subdict.get('url')})\n"
                else:
                    continue
            elif key == "source":
                # list[dict[str, str]]
                if value:
                    subdict = value[0]
                    sources += f"Language: {subdict['language']}\nWord: {subdict['word']}"
            else:
                if value:
                    senses += f"{JISHO_REPLACEMENTS.get(key, key).title()}: {', '.join(value)}\n"  # type: ignore

        if senses:
            embed.description += to_codeblock(senses,
                                              language="prolog",
                                              escape_md=False)

        if links:
            embed.description += links

        if sources:
            embed.description += "\nSources:"
            embed.description += to_codeblock(sources,
                                              language="prolog",
                                              escape_md=False)

        embed.add_field(
            name="Is it common?",
            value=("Yes" if payload.is_common else "No"),
            inline=False,
        )

        if payload.jlpt:
            embed.add_field(name="JLPT Level",
                            value=payload.jlpt[0],
                            inline=False)

        embed.set_footer(text=f"Slug: {payload.slug}")

        return embed
Example #29
0
async def ping(ctx):
    """pong"""
    embed = discord.Embed(title = 'ping',colour=discord.Colour(0xaf1329),description="pong")
    await ctx.send(content=None,embed=embed)
Example #30
0
async def fox(ctx):
	r = requests.get("https://randomfox.ca/floof")
	res = r.json()
	em = discord.Embed(colour=discord.Colour(0x40f181))
	em.set_image(url=res['image'])
	await ctx.send(embed=em)