Exemple #1
0
    async def verify(self, ctx: Context, username: str = None):
        if ctx.channel.type != ChannelType.private:
            return await ctx.send(embed=Embed(
                color=Color.gold(),
                title=_('unsupported'),
                description=_('only supported in dm'),
            ))
        if username is None or username == '':
            return await ctx.send(embed=Embed(
                color=Color.red(),
                title=_('Errors'),
                description=_('provide username'),
            ))
        discord_id = ctx.author.id
        if User.exists(discord_id=discord_id):
            user = User.get(discord_id=discord_id)
            return await ctx.send(embed=Embed(
                color=Color.gold(),
                description=_('user already verified {mail} {username}').format(
                    mail=user.mail_address,
                    username=username,
                ),
            )) if user.verified_at is not None else await ctx.send(embed=Embed(
                color=Color.gold(),
                description=_('already sent verification {mail} {username}').format(
                    mail=user.mail_address,
                    username=username,
                ),
            ))
        await ctx.send(embed=Embed(
            color=Color.green(),
            description=_('sent verification mail {username}').format(username=username),
        ))
        mail_address = f'{username}@alumni.fh-aachen.de'
        user_id = str(uuid4())
        db_session.add(User(
            id=user_id,
            discord_id=discord_id,
            mail_address=mail_address,
        ))
        db_session.commit()
        message = f"""From: No-Reply <{self.config['verification']['mail_user']}>
To: {ctx.author.name} <{mail_address}>
Subject: Fachschaft 5 Discord Verification

Hello {ctx.author.name},

Visit this link to verify your Discord account:
    {self.config['verification']['host']}:{self.config['verification']['port']}{self.config['verification']['endpoint']}/{user_id}

Best regards
"""

        try:
            client = smtplib.SMTP_SSL(self.config['verification']['mail_server'], 465)
            client.login(self.config['verification']['mail_user'], self.config['verification']['mail_pass'])
            client.sendmail(self.config['verification']['mail_user'], [mail_address], message)
        except smtplib.SMTPException as err:
            logging.error(str(err))
Exemple #2
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']
     }
Exemple #3
0
async def ex(message, client):

    args = message.content.split()

    if len(args) > 1:
        global last_invite
        last_invite[args[1]] = message.author

        invite_receivers = [utils.get(message.server.members, id=uid) for uid in functions.get_settings()["roles"]["invite-receivers"]]
        for u in invite_receivers:
            await client.send_message(u, embed=Embed(
                color=Color.gold(),
                title="Bot invite from " + message.author.name,
                description="https://discordapp.com/oauth2/authorize?client_id=%s&scope=bot" % args[1]))
            em = Embed(
                    colour=Color.green(),
                    description="[Invite link](https://discordapp.com/oauth2/authorize?client_id=%s&scope=bot) "
                                "send to %s. One of them will (hopefully ^^) accept your invite as soon as possible.\n"
                                "**Please don't send multiple invite links! It can take a while until someone will accept the bot manually!**\n\n"
                                "**ATTENTION:**\nYou ned to set yout Bot as a **Public Bot** (see screenshot)!\n"
                                "Otherwise, we will not be able to add the bot to the server!"
                                % (args[1], ", ".join([m.mention for m in invite_receivers])))
            em.set_image(url="https://image.prntscr.com/image/R8AjJQ77R__Gg6HCnw9TeQ.png")
            await client.send_message(message.author, embed=em)
            await client.delete_message(message)

    else:
        await client.send_message(message.channel, embed=Embed(description="**USAGE:**\n`!invite <Bot ID>`\n*You can get your Bot ID from the [Discord Apps Panel](https://discordapp.com/developers/applications/me) from `Client ID`.*", color=Color.red()))
Exemple #4
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,
    ])
Exemple #5
0
 async def drink(self, ctx, *, name):
     name = name.title()
     name = '+'.join(name.split())
     tail = Embed(color=Color.gold())
     if name:
         base = f"https://www.thecocktaildb.com/api/json/v1/1/search.php?s={name}"
     else:
         base = "https://www.thecocktaildb.com/api/json/v1/1/random.php"
     async with ClientSession() as session:
         data = await get(session, base)
     data = loads(data)
     data = data['drinks'][0]
     tail.set_author(name=data['strDrink'])
     tail.set_thumbnail(url=data['strDrinkThumb'])
     tail.add_field(name="Alcoholic ­ЪЇ╗", value=data['strAlcoholic'])
     tail.add_field(name="Category", value=data['strCategory'])
     ingr = ""
     for i in range(1, 17):
         item = data[f'strIngredient{i}']
         if item is None:
             break
         ingr += f'{item}\n'
     tail.add_field(name="Ingridients", value=f'```{ingr}```', inline=False)
     tail.add_field(name="Instructions",
                    value=f"```{data['strInstructions']}```",
                    inline=False)
     return await ctx.send(embed=tail)
Exemple #6
0
    async def send_wordle_embed(self, ctx, wordle, guesses, header_str):
        """
    Generates the wordle image, host it on imgur and send the it as an interaction response
    --
    input:
      ctx: interactions.CommandContext
      wordle: wordle.Wordle
      guesses: List[str]
      header_str: str
    """
        img_path = "wordle_tmp.png"
        wordle.generate_image(guesses, img_path)
        link = utils.upload_image_to_imgur(img_path)
        os.remove(img_path)

        color = Color.gold()
        if len(guesses) > 0 and guesses[-1] == wordle.solution:
            color = Color.dark_green()
        elif len(guesses
                 ) == wordle.nb_trials and guesses[-1] != wordle.solution:
            color = Color.dark_red()

        embed = Embed(title="Wordle",
                      description=header_str,
                      color=color.value,
                      image=EmbedImageStruct(url=link)._json)
        await ctx.send(embeds=embed, ephemeral=True)
Exemple #7
0
def random():
    c = [
        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
    ]
    return c[randint(0, len(c) - 1)]
    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))
Exemple #9
0
def black_jack_embed(user: User,
                     player,
                     outcome: str = None,
                     hidden: bool = True) -> Embed:
    """
    Creates embed based on set of constraints for blackjack
    :param user:  discord.User
    :param player: player object for blackjack
    :param outcome: blackjack game outcome
    :param hidden: dealer card value
    :return: discord.Embed
    """
    embed = black_jack_template(user, player, "", Color.gold())
    embed.add_field(name="Dealer hand",
                    value=player.game.get_emote_string(hidden=hidden))
    if outcome == "win":
        embed.colour = Color.dark_green()
        embed.description = "**Outcome:** You won!"
    elif outcome == "lose":
        embed.colour = Color.dark_red()
        embed.description = "**Outcome:** You lost!"
    elif outcome == "tie":
        embed.colour = Color.dark_grey()
        embed.description = "**Outcome:** It's a tie!"
    return embed
Exemple #10
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)
Exemple #11
0
    async def serverinfo(self, ctx: Context) -> None:
        """Get information about the server."""

        embed = Embed(colour=Color.gold())
        embed.title = f"{ctx.guild.name}'s stats and information."
        embed.description = ctx.guild.description if ctx.guild.description else None
        embed.add_field(
            name="__**General information:**__",
            value=textwrap.dedent(f"""
                **Owner:** {ctx.guild.owner}
                **Created at:** {datetime.datetime.strftime(ctx.guild.created_at, "%A %d %B %Y at %H:%M")}
                **Members:** {ctx.guild.member_count}
                **Nitro Tier:** {ctx.guild.premium_tier} | **Boosters:** {ctx.guild.premium_subscription_count}
                **File Size:** {round(ctx.guild.filesize_limit / 1048576)} MB
                **Bitrate:** {round(ctx.guild.bitrate_limit / 1000)} kbps
                **Emoji:** {ctx.guild.emoji_limit}
                """),
        )

        embed.add_field(
            name="__**Channels:**__",
            value=textwrap.dedent(f"""
                **AFK timeout:** {int(ctx.guild.afk_timeout / 60)}m | **AFK channel:** {ctx.guild.afk_channel}
                **Text channels:** {len(ctx.guild.text_channels)} | **Voice channels:** {len(ctx.guild.voice_channels)}
                """),
            inline=False,
        )

        embed.set_footer(text=f"ID: {ctx.guild.id}")

        await ctx.send(embed=embed)
        return
Exemple #12
0
async def ud(ctx, *args):
    if args:
        url = "http://urbandictionary.com/define.php?term=" + "+".join(args)
        await client.say(
            embed=Embed(description="**[Urban Dictionary!](%s)**" % url,
                        color=Color.gold()))
    await client.delete_message(ctx.message)
Exemple #13
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,
    ])
Exemple #14
0
    async def handle_bday(self, user_id: int, year: int) -> None:
        embed = Embed(color=Color.gold())

        if year is not None:
            age = datetime.date.today().year - int(year)
            embed.description = f"<@!{user_id}> is now **{age} years old**. :tada: "
        else:
            embed.description = f"It's <@!{user_id}>'s birthday today! :tada: "

        for server_id, channel_id in self.config["channels"].items():
            server = self.bot.get_server(server_id)

            if server is not None:
                member = server.get_member(user_id)

                if member is not None:
                    role_id = self.config["roles"].get(server_id)

                    if role_id is not None:
                        role = utils.find(lambda r: r.id == role_id,
                                          server.roles)

                        if role is not None:
                            try:
                                await self.bot.add_roles(member, role)
                            except (Forbidden, HTTPException):
                                pass
                            else:
                                self.config["yesterday"].append(member.id)

                    channel = server.get_channel(channel_id)

                    if channel is not None:
                        await channel.send(embed=embed)
Exemple #15
0
    def get_server_embed(self, guild: Guild) -> Embed:
        embed = Embed(
            title="Server's stats and information.",
            description=guild.description if guild.description else None,
            color=Color.gold())

        embed.add_field(
            name="❯❯ General information",
            value=textwrap.dedent(f"""
                Name: {guild.name}
                Created at: {datetime.datetime.strftime(guild.created_at, "%A %d %B %Y at %H:%M")}
                Members: {guild.member_count}
                Owner: <@!{guild.owner}>
                Nitro Tier: {guild.premium_tier} | Boosters: {guild.premium_subscription_count}

                File Size: {round(guild.filesize_limit / 1048576)} MB
                Bitrate: {round(guild.bitrate_limit / 1000)} kbps
                Emoji: {guild.emoji_limit}
                """),
        )
        embed.add_field(
            name="❯❯ Channels",
            value=textwrap.dedent(f"""
                Text channels: {len(guild.text_channels)}
                Voice channels: {len(guild.voice_channels)}
                AFK timeout: {round(guild.afk_timeout / 60)}m | AFK channel: {guild.afk_channel.mention}
                """),
            inline=False,
        )

        embed.set_thumbnail(url=guild.icon_url)
        embed.set_footer(text=f"Guild ID: {guild.id}")

        return embed
Exemple #16
0
 async def url(self, ctx, url: str):
     ad = Embed(color=Color.gold())
     apiurl = "http://tinyurl.com/api-create.php?url="
     tinyurl = await self.bot.loop.run_in_executor(
         None, lambda: urlopen(apiurl + url).read().decode("utf-8"))
     ad.title = "URL Shortener 🔁"
     ad.description = tinyurl
     return await ctx.send(embed=ad)
Exemple #17
0
 async def joe_username(self, ctx: Context, lim: int = 4):
     op = joe_generate(lim)
     if lim == 4:
         op = joe_generate(random.randint(3, 11))
     embed = Embed(
         title=op,
         description='That sounds cool, cool, cool.. Right.',
         color=Color.gold())
     await ctx.send(embed=embed)
Exemple #18
0
    async def wikipedia(self, ctx: Context, *, query: str) -> None:
        """Get information from Wikipedia."""
        payload = {}
        payload["action"] = "query"
        payload["titles"] = query.replace(" ", "_")
        payload["format"] = "json"
        payload["formatversion"] = "2"  # Cleaner json results
        payload["prop"] = "extracts"  # Include extract in returned results
        payload["exintro"] = "1"  # Only return summary paragraph(s) before main content
        payload["redirects"] = "1"  # Follow redirects
        payload["explaintext"] = "1"  # Make sure it's plaintext (not HTML)

        conn = aiohttp.TCPConnector()

        async with aiohttp.ClientSession(connector=conn) as session:
            async with session.get(
                self.base_url, params=payload, headers=self.headers
            ) as res:
                result = await res.json()

        try:
            # Get the last page. Usually this is the only page.
            for page in result["query"]["pages"]:
                title = page["title"]
                description = page["extract"].strip().replace("\n", "\n\n")
                url = "https://en.wikipedia.org/wiki/{}".format(title.replace(" ", "_"))

            if len(description) > 1500:
                description = description[:1500].strip()
                description += "... [(read more)]({})".format(url)

            embed = Embed(
                title=f"Wikipedia: {title}",
                description=u"\u2063\n{}\n\u2063".format(description),
                color=Color.blue(),
                url=url
            )
            embed.set_footer(
                text="Wikipedia", icon_url=self.footer_icon
            )
            await ctx.send(embed=embed)

        except KeyError:
            await ctx.send(
                embed=Embed(
                    description=f"I'm sorry, I couldn't find \"{query}\" on Wikipedia",
                    color=Color.red()
                )
            )
        except discord.Forbidden:
            await ctx.send(
                embed=Embed(
                    description=f"I'm not allowed to do embeds here...\n{url}",
                    color=Color.gold()
                )
            )
Exemple #19
0
async def status(ctx, *args):
    """
    Change account status visible for others*
    *an effect of using a userbot is, that the bot displays your status as 'online'
    for other users while you can change your status to 'idle' or 'dnd', but
    noone will see it until the bot changes the status.
    """
    stati = {
        "on": Status.online,
        "online": Status.online,
        "off": Status.invisible,
        "offline": Status.invisible,
        "dnd": Status.dnd,
        "idle": Status.idle,
        "afk": Status.idle
    }
    if args:
        cgame = ctx.message.server.get_member(bot.user.id).game
        if (args[0] in stati):
            if (args[0] == "afk"):
                await bot.change_presence(game=cgame,
                                          status=Status.idle,
                                          afk=True)
            else:
                await bot.change_presence(game=cgame,
                                          status=stati[args[0]],
                                          afk=False)
                print(stati[args[0]])
            msg = await bot.send_message(
                ctx.message.channel,
                embed=Embed(description="Changed current status to `%s`." %
                            args[0],
                            color=Color.gold()))
    else:
        await bot.change_presence(game=cgame, status=Status.online, afk=False)
        msg = await bot.send_message(
            ctx.message.channel,
            embed=Embed(description="Changed current status to `online`.",
                        color=Color.gold()))
    await bot.delete_message(ctx.message)
    await asyncio.sleep(3)
    await bot.delete_message(msg)
Exemple #20
0
async def lmgtfy(ctx, *args):
    """
    Just a simple lmgtfy command, invoche the command and give an arguument, it will search up on google
    """
    if args:
        url = "http://lmgtfy.com/?q=" + "+".join(args)
        await bot.send_message(ctx.message.channel,
                               embed=Embed(description="**[Look here!](%s)**" %
                                           url,
                                           color=Color.gold()))
    await bot.delete_message(ctx.message)
    async def switch_region(self, ctx: Context,
                            new_region: VoiceRegionConverter):
        """Change the server voice region."""

        await ctx.guild.edit(
            reason=f"Switch region command triggered by {ctx.author}",
            region=new_region)
        await ctx.send(embed=Embed(
            title=
            f"\N{WHITE HEAVY CHECK MARK} Updated voice region to {new_region}.",
            color=Color.gold()))
Exemple #22
0
 async def battle(self, ctx, p2: Member):
     p1 = ctx.author
     game = Embed(color=Color.green())
     beast = list(animals.keys())
     p1 = [p1, choice(beast)]
     hp = randrange(100, 300)
     b1 = [300, stats[p1[1]]]
     game.set_author(name=p1[1].title(), icon_url=animals[p1[1]])
     game.description = f"{p1[0].display_name} goes to battle with a {p1[1].title()}!"
     s = "**HP**: 300/300\n"
     for i in b1[1]:
         s += f"**{i.upper()}**: {b1[1][i]}\n"
     game.add_field(name="Stats", value=s)
     await ctx.send(embed=game)
     await sleep(2.5)
     p2 = [p2, choice(beast)]
     b2 = [300, stats[p2[1]]]
     game.set_author(name=p2[1].title(), icon_url=animals[p2[1]])
     game.description = f"{p2[0].display_name} goes to battle with a {p2[1].title()}!"
     s = "**HP**: 300/300\n"
     for i in b2[1]:
         s += f"**{i.upper()}**: {b2[1][i]}\n"
     game.set_field_at(index=0, name="Stats", value=s)
     await ctx.send(embed=game)
     await sleep(3)
     battle = Embed(color=Color.red())
     battle.description = "**Battle Start**!"
     msg = await ctx.send(embed=battle)
     await sleep(2)
     while b1[0] > 0 and b2[0] > 0:
         b1a = b1[1]['str'] * 10 - b2[1]['agi'] * 2.5 - b2[1][
             'def'] * 2.5 + randrange(10, 30)
         b2a = b2[1]['str'] * 10 - b1[1]['agi'] * 2.5 - b1[1][
             'def'] * 2.5 + randrange(10, 30)
         b1[0] -= b2a
         b2[0] -= b1a
         battle.set_author(name=p1[1].title(), icon_url=animals[p1[1]])
         log = f"{p1[0].display_name}'s {p1[1]} deals **{b1a}** damage!\n"
         log += f"HP **{b1[0]}**/**300**\n\n\n"
         log += f"{p2[0].display_name}'s {p2[1]} deals **{b2a}** damage!\n"
         log += f"HP **{b2[0]}**/**300**\n"
         battle.description = log
         battle.set_footer(text=p2[1].title(), icon_url=animals[p2[1]])
         await msg.edit(embed=battle)
         await sleep(3)
     result = Embed(color=Color.gold())
     await sleep(2)
     if b1[0] < 0 and b2[0] < 0:
         result.title = f"{ctx.author.display_name} and {p2.display_name}'s tied"
     else:
         win = p1 if b1[0] > b2[0] else p2
         result.title = f"🎉 {win[0].display_name} 🎉 won the battle! "
     result.set_thumbnail(url=animals[win[1]])
     await ctx.send(embed=result)
Exemple #23
0
 async def ping(self, ctx):
     ping = float(self.bot.latency * 1000)
     em = Embed(title="IsThicc", color=Color.gold())
     if ping <=20:
         em.description = (f":green_circle: Latency: {ping:.0f}")
     elif ping <=50:
         em.description = (f":orange_circle: Latency: {ping:.0f}")
     else:
         em.description = {f":red_circle: Latency: {ping:.0f}"}
     
     return await ctx.send(embed=em)
Exemple #24
0
 def __init__(self, webhook):
     self.webhook = webhook
     self.level_color = {
         "INFO": Color.light_grey(),
         "WARNING": Color.gold(),
         "ERROR": Color.dark_red(),
         "CRITICAL": Color.red(),
         "DEBUG": Color.dark_green(),
         "NOTSET": Color.dark_grey(),
     }
     super(DiscordHandler, self).__init__()
Exemple #25
0
def get_embed_piflouz(bot):
    """
  Creates an embed message containing the explanation for the piflouz game and the balance
  --
  input:
    bot: interactions.Client
  --
  output:
    embed: interactions.Embed
  """
    last_begin_time = datetime.datetime.fromtimestamp(db["last_begin_time"])
    end_time = last_begin_time + relativedelta(months=3)
    desc = f"This is the piflouz mining message, click every {Constants.REACT_TIME_INTERVAL} seconds to gain more {Constants.PIFLOUZ_EMOJI}.\n\n\
You just need to click on the {Constants.PIFLOUZ_EMOJI} button below or use the `/get` command.\n\
If you waited long enough ({utils.seconds_to_formatted_string(Constants.REACT_TIME_INTERVAL)}), you will earn some {Constants.PIFLOUZ_EMOJI}! The amount depends on the current event, your powerups, your mining combo and your accuracy to use `/get`.\n\n\
This season will end on <t:{int(end_time.timestamp())}>.\nYour goal is to earn, donate and flex with as much piflouz as possible. You will earn rewards based on the amount of piflouz you earn and your different rankings."

    fields = []

    # Rankings
    if "piflouz_bank" in db.keys():
        d_piflouz = dict(db["piflouz_bank"])
        d_piflex = [(user_id, len(discovered))
                    for user_id, discovered in db["discovered_piflex"].items()]
        d_donations = [(user_id, val)
                       for user_id, val in db["donation_balance"].items()
                       if val > 0]

        ranking_balance = get_ranking_str(list(d_piflouz.items()))
        ranking_piflex = get_ranking_str(d_piflex)
        ranking_donations = get_ranking_str(d_donations)

        if ranking_balance != "":
            fields.append(
                EmbedField(name="Balance", value=ranking_balance, inline=True))
        if ranking_piflex != "":
            fields.append(
                EmbedField(name="Piflex Discovery",
                           value=ranking_piflex,
                           inline=True))
        if ranking_donations != "":
            fields.append(
                EmbedField(name="Donations",
                           value=ranking_donations,
                           inline=False))

    embed = Embed(title=f"Come get some {Constants.PIFLOUZ_EMOJI}!",
                  description=desc,
                  thumbnail=EmbedImageStruct(url=Constants.PIFLOUZ_URL)._json,
                  fields=fields,
                  color=Color.gold().value)

    return embed
Exemple #26
0
    async def on_message_delete(self, message):
        if message.author.bot:
            return

        fields = [("**Message:**", message.content, False)]

        embed = create_embed("Message deleted", f"Original message by {message.author}.",
        color=Color.gold(), thumbnail_url=message.author.avatar_url, fields=fields)

        log_channel = self.bot.get_log_channel(message.guild.id)
        if log_channel is not None:
            await log_channel.send(embed=embed)
Exemple #27
0
async def lmgtfy(ctx, *args):
    """
    Just a simple lmgtfy command embeding the link into the message.*
    *Links are still visible because discord asks you if this link is safe :/
    """
    if args:
        url = "http://lmgtfy.com/?q=" + "+".join(args)
        await bot.send_message(ctx.message.channel,
                               embed=Embed(description="**[Look here!](%s)**" %
                                           url,
                                           color=Color.gold()))
    await bot.delete_message(ctx.message)
Exemple #28
0
    async def excuse(self, ctx: Context) -> None:
        """
        Bastard Operator from Hell excuses.

        Source: http://pages.cs.wisc.edu/~ballard/bofh
        """
        async with aiohttp.ClientSession() as session:
            async with session.get("http://pages.cs.wisc.edu/~ballard/bofh/excuses") as r:
                data = await r.text()
        lines = data.split("\n")
        embed = Embed(title="Excuses", description=random.choice(lines), color=Color.gold())

        await ctx.send(embed=embed)
Exemple #29
0
async def on_message(message):
    ctx = await bot.get_context(message)
    if ctx.command:
        await bot.invoke(ctx)
        return
    if message.guild or message.author.bot:
        return
    else:
        channel = await bot.fetch_channel(getenv("MODMAIL_CHANNEL"))
        embed = Embed(title=message.content, color=Color.gold())
        embed.set_author(name=str(message.author),
                         icon_url=message.author.avatar_url)
        await channel.send("", embed=embed)
Exemple #30
0
 async def panda(self, ctx: Context) -> None:
     """Get a random picture of a panda."""
     async with self.bot.session.get("https://some-random-api.ml/img/panda",) as resp:
         if resp.status == 200:
             data = await resp.json()
             embed = Embed(
                 title="Random Panda!",
                 color=Color.gold(),
             )
             embed.set_image(url=data["link"])
             await ctx.send(embed=embed)
         else:
             await ctx.send(f"Something went boom! :( [CODE: {resp.status}]")