Ejemplo n.º 1
0
def random():
    # type: () -> Color

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

    return choice([
        Color.teal(),
        Color.dark_teal(),
        Color.green(),
        Color.dark_green(),
        Color.blue(),
        Color.dark_blue(),
        Color.purple(),
        Color.dark_purple(),
        Color.magenta(),
        Color.dark_magenta(),
        Color.gold(),
        Color.dark_gold(),
        Color.orange(),
        Color.dark_orange(),
        Color.red(),
        Color.dark_red(),
        Color.lighter_grey(),
        Color.darker_grey(),
        Color.blurple(),
        tan,
        icedcoffee,
        chilipepper,
    ])
Ejemplo n.º 2
0
    def wildcard_embed(self):
        this_embed = Embed(color=Color.purple(), title=f"{self.name} Wildcard Race")
        standings = {}
        for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
            standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
        for subleague in iter(self.league.keys()):
            subleague_array = []
            for division in iter(self.league[subleague].keys()):
                this_div = [this_team for this_team, wins, losses, diff, gb in self.division_standings(self.league[subleague][division], standings)[self.constraints["division_leaders"]:]]
                subleague_array += this_div

            teams = self.division_standings(subleague_array, standings)
            teams_string = ""
            for index in range(0, len(teams)):
                if index == self.constraints["wild_cards"] - 1:
                    teams[index][4] = "-"
                else:
                    games_behind = ((teams[self.constraints["wild_cards"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["wild_cards"] - 1][2]))/2
                    teams[index][4] = games_behind

            for this_team in teams:
                if this_team[2] != 0 or this_team[1] != 0:
                    teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
                else:
                    teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"

            this_embed.add_field(name=f"{subleague} League:", value=teams_string, inline = False)
        
        this_embed.set_footer(text=f"Wildcard standings as of day {self.day-1}")
        return this_embed
Ejemplo n.º 3
0
def create_embed(data):
    """Takes the level information and returns the embed that has blend stuff."""
    date = datetime.now().strftime("%a, %b %d, %Y")

    modes = []
    if data['single_player']:
        modes.append("1P")
    if data['two_player']:
        modes.append("2P")

    embed = Embed(title=f"Daily Blend: {date}", color=Color.purple())
    embed.add_field(name="Level", value=f"{data['artist']} - {data['song']}")
    embed.add_field(name="Creator", value=data['author'])
    embed.add_field(name="Description",
                    value=data['description'],
                    inline=False)
    embed.add_field(name="Tags",
                    value=", ".join([f'**[{x}]**' for x in data['tags']]),
                    inline=False)
    embed.add_field(name="Modes", value=" ".join(modes))
    embed.add_field(name="Difficulty", value=data['difficulty'])
    embed.add_field(name="Download",
                    value=f"[Link]({data['download_url']})",
                    inline=True)
    embed.set_image(url=data['preview_img'])

    return embed
Ejemplo n.º 4
0
async def poll(ctx, col, arg2):
    try:
        if col == "red":
            embedcolor = Color.red()
        if col == "orange":
            embedcolor = Color.orange()
        if col == "yellow":
            embedcolor = Color.yellow()
        if col == "green":
            embedcolor = Color.green()
        if col == "blue":
            embedcolor = Color.blue()
        if col == "purple":
            embedcolor = Color.purple()
        if col == "black":
            embedcolor = Color.black()
        if col == "none":
            embedcolor = Color.default()
        embed=discord.Embed(title="POLL:", description=arg2, color=embedcolor)
        embed.set_footer(text="Vote by reacting")
        embedmsg = await ctx.send(embed=embed)
        await ctx.message.delete()
        await embedmsg.add_reaction("👍")
        await embedmsg.add_reaction("👎")
        print(Fore.GREEN+f'[>] Poll "{arg2}" sent!')
    except:
        print(Fore.RED+"[>] Poll failed")
    print(Fore.RESET)
Ejemplo n.º 5
0
 def __init__(self, client):
     self.client = client
     self.client_color = Color.red()
     self.color_dict = {
         1: [Color.teal(), 'teal'],
         2: [Color.dark_teal(), 'dark_teal'],
         3: [Color.green(), 'green'],
         4: [Color.dark_green(), 'dark_green'],
         5: [Color.blue(), 'blue'],
         6: [Color.dark_blue(), 'dark_blue'],
         7: [Color.purple(), 'purple'],
         8: [Color.dark_purple(), 'dark_purple'],
         9: [Color.magenta(), 'magenta'],
         10: [Color.dark_magenta(), 'dark_magenta'],
         11: [Color.gold(), 'gold'],
         12: [Color.dark_gold(), 'dark_gold'],
         13: [Color.orange(), 'orange'],
         14: [Color.dark_orange(), 'dark_orange'],
         15: [Color.red(), 'red'],
         16: [Color.dark_red(), 'dark_red'],
         17: [Color.lighter_grey(), 'lighter_grey'],
         18: [Color.dark_grey(), 'grey'],
         19: [Color.light_grey(), 'light_grey'],
         20: [Color.darker_grey(), 'darker_grey']
     }
Ejemplo n.º 6
0
 async def message(desc:str,color:Color=Color.purple(),title:str=None):
     return Embed(
         type="rich",
         description=desc,
         color=color,
         title=title
     )
Ejemplo n.º 7
0
    def standings_embed(self):
        this_embed = Embed(color=Color.purple(), title=f"{self.name} Season {self.season}")
        standings = {}
        for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
            standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
        for subleague in iter(self.league.keys()):
            this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False)
            for division in iter(self.league[subleague].keys()):
                teams = self.division_standings(self.league[subleague][division], standings)

                for index in range(0, len(teams)):
                    if index == self.constraints["division_leaders"] - 1:
                        teams[index][4] = "-"
                    else:
                        games_behind = ((teams[self.constraints["division_leaders"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["division_leaders"] - 1][2]))/2
                        teams[index][4] = games_behind
                teams_string = ""
                for this_team in teams:
                    if this_team[2] != 0 or this_team[1] != 0:
                        teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
                    else:
                        teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"

                this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False)
        
        this_embed.set_footer(text=f"Standings as of day {self.day-1} / {self.season_length()}")
        return this_embed
Ejemplo n.º 8
0
def random():
    # type: () -> Color

    tan = Color(0xBEAA3E)

    return choice([
        Color.teal(),
        Color.dark_teal(),
        Color.green(),
        Color.dark_green(),
        Color.blue(),
        Color.dark_blue(),
        Color.purple(),
        Color.dark_purple(),
        Color.magenta(),
        Color.dark_magenta(),
        Color.gold(),
        Color.dark_gold(),
        Color.orange(),
        Color.dark_orange(),
        Color.red(),
        Color.dark_red(),
        Color.lighter_grey(),
        Color.darker_grey(),
        Color.blurple(),
        tan,
    ])
Ejemplo n.º 9
0
    async def on_member_unban(self, guild, user):
        # TODO: what if we arent allowed to see audit logs
        # NOTE: we assume the event always gets called before the audit logs get updated
        trigger_time = datetime.datetime.utcnow() - datetime.timedelta(
            seconds=10)

        # Give Discord some time to put the unban in the audit logs
        await asyncio.sleep(1)

        # Only check unbans and after the time this event got triggered
        async for entry in guild.audit_logs(action=AuditLogAction.unban):
            # NOTE: the `after`-tag in audit_logs seems to get ignored :|, so we have to check manually
            if trigger_time > entry.created_at:
                await self.log(
                    guild=guild,
                    embed=Embed(
                        color=Color.purple(),
                        description=
                        "Unban happened, but audit logs dont seem to have information"
                    ).set_author(name=str(user)))
                break

            elif entry.target == user:
                # Check if the target is the user that got unbanned
                await self.log(guild=guild,
                               embed=Embed(color=Color.green()).set_author(
                                   name=str(entry.user)).add_field(
                                       name="unbanned", value=str(user)))
                break
Ejemplo n.º 10
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)]
Ejemplo n.º 11
0
 def stat_embed(self, stat_name, season_num):
     if season_num is None:
         season_string = str(self.season)
         day = self.day
     else:
         season_string = str(season_num)
         day = len(self.schedule)
     this_embed = Embed(
         color=Color.purple(),
         title=f"{self.name} Season {season_string} {stat_name} Leaders")
     stats = league_db.get_stats(self.name,
                                 stat_name.lower(),
                                 day=day,
                                 season=season_num)
     if stats is None:
         return None
     else:
         stat_names = list(stats[0].keys())[2:]
         for index in range(0, min(10, len(stats))):
             this_row = list(stats[index])
             player_name = this_row.pop(0)
             content_string = f"**{this_row.pop(0)}**\n"
             for stat_index in range(0, len(this_row)):
                 content_string += f"**{stat_names[stat_index]}**: {str(this_row[stat_index])}; "
             this_embed.add_field(name=player_name,
                                  value=content_string,
                                  inline=False)
         return this_embed
Ejemplo n.º 12
0
async def embed(ctx, col, arg1, arg2, arg3):
    try:
        if col == "red":
            embedcolor = Color.red()
        if col == "orange":
            embedcolor = Color.orange()
        if col == "yellow":
            embedcolor = Color.yellow()
        if col == "green":
            embedcolor = Color.green()
        if col == "blue":
            embedcolor = Color.blue()
        if col == "purple":
            embedcolor = Color.purple()
        if col == "black":
            embedcolor = Color.black()
        if col == "none":
            embedcolor = "none"
        if embedcolor == "none":
            embed=discord.Embed(title=arg1, description=arg2)
            embed.set_footer(text=arg3)
            await ctx.send(embed=embed)
            await ctx.message.delete()
        if embedcolor != "none":
            embed=discord.Embed(title=arg1, description=arg2, color=embedcolor)
            embed.set_footer(text=arg3)
            await ctx.send(embed=embed)
            await ctx.message.delete()
    except:
        print(Fore.RED+"[>] Failed to send embed")
Ejemplo n.º 13
0
async def _get_message(ctx: Context, msg: Optional[Message] = None,
        expiry: Optional[str] = None):
    roles = settings['roles.catalog'].get(ctx)[:10]
    embed = Embed(title=f':billed_cap: Available roles',
                  description='Use post reactions to manage role membership',
                  color=Color.purple())

    if expiry is not None:
        embed.set_footer(text=f'This post will be deleted in {expiry}.')

    count = 0

    for role in sorted(roles, key=lambda x: x.lower()):
        embed.add_field(name=f'{count}{DIGIT_SUFFIX} {role}', value='\u200b')
        count += 1

    if msg is None:
        msg: Message = await ctx.send(embed=embed)
    else:
        await msg.edit(embed=embed)
        await msg.clear_reactions()

    for i in range(0, count):
        await msg.add_reaction(f'{i}{DIGIT_SUFFIX}')

    return msg
Ejemplo n.º 14
0
async def embd(ctx, *args):
    colors = {
        "red": Color.red(),
        "green": Color.green(),
        "gold": Color.gold(),
        "orange": Color.orange(),
        "blue": Color.blue(),
        "purple": Color.purple(),
        "teal": Color.teal(),
        "magenta": Color.magenta(),
        "grey": Color.lighter_grey()
    }
    if args:
        argstr = " ".join(args)
        if "-c " in argstr:
            text = argstr.split("-c ")[0]
            color_str = argstr.split("-c ")[1]
            color = colors[
                color_str] if color_str in colors else Color.default()
        else:
            text = argstr
            color = Color.default()

            await client.say(embed=Embed(color=color, description=text))
            await client.delete_message(ctx.message)
Ejemplo n.º 15
0
async def info(ctx: Context):
    await ctx.send(embed=Embed(color=Color.purple(),
                               description=f"""
**Bot by:** *BaseChip*
**Project:** *TheBotDev*
**Support:** *[BaseChips support server](https://discord.gg/HD7x2vx)*
**Bot Invite:** *[INVITE BaseChips Bot]({oauth_url(client.user.id, Permissions(67577856))})*
*This is a fork from GitHub from the Bot from BaseChip*"""))
Ejemplo n.º 16
0
async def info(ctx: Context):
    await ctx.send(embed=Embed(
        color=Color.purple(),
        description=
        "**Bot by:** *BaseChip*\n**Project:** *TheBotDev*\n**Support:** *[BaseChips support server]("
        "https://discord.gg/HD7x2vx)*\n**Bot Invite:** *[INVITE BaseChips Bot]("
        "https://discordapp.com/api/oauth2/authorize?client_id=384757717346025472&permissions"
        "=67577856&scope=bot)*\n*This is a fork from GitHub from the Bot from BaseChip*"
    ))
Ejemplo n.º 17
0
def get_media_embed(data):
    em = Embed(title=data['title']['english'] or data['title']['romaji']
               or data['title']['native'],
               color=Color.purple())
    if data['bannerImage']:
        em.set_image(url=data['bannerImage'])
    em.set_author(name="id#" + str(data['id']), url=data['siteUrl'])
    des = truncate(data['description'], 400)
    em.add_field(name="Description:", value=des, inline=False)
    em.add_field(name="Status:", value=data['status'])
    if data['type'] == "ANIME":
        em.add_field(name="Format/Duration:",
                     value=f"{data['format']} / {data['duration']} mins")
    s_e = "Yet Not Released" if data['startDate'][
        'day'] is None else f"{data['startDate']['day']}.{data['startDate']['month']}.{data['startDate']['year']}"
    s_e += " - "
    s_e += "None" if data['startDate']['day'] is None else ""
    s_e += "Ongoing" if data['endDate']['day'] is None else ""
    s_e += f"{data['endDate']['day']}.{data['endDate']['month']}.{data['endDate']['year']}" if data[
        'endDate']['day'] else ""
    em.add_field(name="Date(Start-End):", value=s_e, inline=False)
    if data['type'] == "ANIME":
        if data['status'] == "RELEASING":
            at = f"Airing episode {data['nextAiringEpisode']['episode']} At "
            d = datetime.datetime.utcfromtimestamp(
                data['nextAiringEpisode']['airingAt'])
            d = d.strftime("%d.%m.%Y %H:%MUTC")
            at += d
            em.add_field(name="Episodes:", value=at, inline=False)
        else:
            em.add_field(name="Episodes: ", value=data['episodes'])
    else:
        em.add_field(name="Volumes: ", value=data['volumes'] or "None")
        em.add_field(name="Chapters : ", value=data['chapters'] or "None")
    em.add_field(name="Genres:",
                 value=truncate(", ".join(data['genres']), 70),
                 inline=False)
    em.add_field(name="Favourites: ",
                 value=f"{data['favourites']} anilist users liked this",
                 inline=False)
    em.add_field(name="Average Score:", value=f"{data['averageScore']}%")
    e_plus = "Yes" if data['isAdult'] == "true" else "No"
    em.add_field(name="18+ :", value=e_plus)
    if data['type'] == "ANIME" and len(data['studios']['nodes']) > 0:
        st = []
        for i in data['studios']['nodes']:
            st.append(i['name'])
        st = ", ".join(st)
        em.add_field(name="Studios:", value=truncate(st, 50), inline=False)
    ot = []
    for i in data['title'].keys():
        if data['title'][i]:
            ot.append(data['title'][i])
    ot = ", ".join(ot)
    em.add_field(name="Other Names:", value=ot)
    return em
Ejemplo n.º 18
0
def _set_color(card):
    if card == 'Free':
        return Color.light_grey()
    elif card == 'Common':
        return Color.lighter_grey()
    elif card == 'Rare':
        return Color.blue()
    elif card == 'Epic':
        return Color.purple()
    elif card == 'Legendary':
        return Color.orange()
    else:
        return Color.default()
Ejemplo n.º 19
0
def get_embed_twitch_notif():
    """
  Returns an embed message on which to react to get the role to get notified when pibou421 goes live on Twitch
  --
  output:
    embed: interactions.Embed
  """
    embed = Embed(
        title="Twitch notification role",
        description="React to get/remove the Twitch notifications role",
        color=Color.purple().value,
        thumbnail=EmbedImageStruct(
            url=Constants.PIBOU_TWITCH_THUMBNAIL_URL)._json)
    return embed
Ejemplo n.º 20
0
async def get_val(ctx, *query):
    page = valget(' '.join(query))
    if type(page) is dict:
        embed = discord.Embed(title=page.get('title'),
                              url=_create_wiki_url(page.get('title')),
                              description=page.get('description'),
                              color=Color.purple())
        if page.get('fields'):
            for name, value in page.get('fields').items():
                embed.add_field(name=name, value=value)

        if page.get('thumbnail'):
            embed.set_thumbnail(url=page.get('thumbnail'))
    else:
        embed = discord.Embed(title=f'{page}', color=Color.red())

    embed.set_footer(text=f'Requested by {ctx.author.display_name}')
    await ctx.send(embed=embed)
Ejemplo n.º 21
0
    async def norse(self, ctx):
        with open('data/oldNorseToEnglish.json', encoding='utf-8') as norse_file:
            norse_dict = json.load(norse_file)

        index = random.randint(0, len(norse_dict))
        chosen_word = norse_dict[index]

        embed = Embed(title=chosen_word['word'], color=Color.purple())

        embed.add_field(name="Meaning", value=chosen_word['definition'], inline=False)
        embed.add_field(name="Type", value=chosen_word['type'] if chosen_word['type'] != "" else "N/A", inline=True)
        embed.add_field(name="Gender", value=chosen_word['gender'] if chosen_word['gender'] != "" else "None", inline=True)
        embed.add_field(name="Branch", value=chosen_word['branch'], inline=False)

        embed.set_footer(text="Old Norse Dictionary provided by https://github.com/stscoundrel/ordbok-json",
                         icon_url="https://viking-rally.ssago.org/img/events/236/media/Viking%20Rally%20Logo.png")

        await ctx.send(embed=embed)
Ejemplo n.º 22
0
async def get_embed_end_season(bot):
    """
  Returns an embed announcing the end of a season
  --
  output:
    embed: interactions.Embed
  """
    channel = await bot.get_channel(db["out_channel"])
    msg = await channel.get_message(db["piflouz_message_id"])
    url = f"https://discord.com/channels/{channel.guild_id}/{channel.id}/{msg.id}"
    print(url)

    embed = Embed(
        title="The season is over!",
        description=
        f"The last season has ended! Use the `/seasonresults` to see what you earned. Congratulations to every participant!\nThe final rankings are available [here]({url})",
        color=Color.purple().value,
        thumbnail=EmbedImageStruct(
            url=Constants.TURBO_PIFLOUZ_ANIMATED_URL)._json)

    return embed
Ejemplo n.º 23
0
async def roles(ctx: Context):
    "Manage your membership in available roles"

    expiry_raw = settings['roles.postexpiry'].get(ctx)
    expiry = seconds_to_str(expiry_raw)
    roles = settings['roles.catalog'].get(ctx)

    if roles is None or len(roles) == 0:
        await ctx.send(':person_shrugging: There are no available '
                       'self-service roles.')
        log.warn(f'{ctx.author} invoked roles self-service, but no roles are '
                 'available')

        return

    roles = roles[:10]
    embed = Embed(title=f':billed_cap: Available roles',
                  description='Use post reactions to manage role membership',
                  color=Color.purple())
    embed.set_footer(text=f'This post will be deleted in {expiry}.')
    count = 0

    for role in sorted(roles, key=lambda x: x.lower()):
        embed.add_field(name=f'{count}{DIGIT_SUFFIX} {role}', value='\u200b')
        count += 1

    msg: Message = await ctx.send(embed=embed)

    for i in range(0, count):
        await msg.add_reaction(f'{i}{DIGIT_SUFFIX}')

    posts[msg.id] = {
        'guild': ctx.guild.id,
        'channel': ctx.channel.id,
        'expiry': datetime.utcnow() + timedelta(seconds=expiry_raw)
    }

    log.info(f'{ctx.author} invoked roles self-service')
    loop.call_later(expiry_raw, _delete, msg.id)
    await ctx.message.delete()
Ejemplo n.º 24
0
def get_color(rank: str = 'F') -> Color:
    """
    Gives `discord.Color` based on rank achieved in score

    :param rank: Rank achieved on score `str`
    :return: `discord.Color`
    """

    rank = rank.upper()
    if rank in ['SH', 'SSH']:
        return Color.light_grey()
    if rank in ['S', 'SS']:
        return Color.gold()
    if rank == 'A':
        return Color.green()
    if rank == 'B':
        return Color.blue()
    if rank == 'C':
        return Color.purple()
    if rank == 'D':
        return Color.red()

    return Color.darker_gray()
Ejemplo n.º 25
0
    def __init__(self):
        intents = discord.Intents.all()
        commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or("Bjørn "), case_insensitive=True,
                              help_command=PrettyHelp(color=Color.purple(), show_index=False), intents=intents)

        # Set up Firebase Database
        # Currently disabled as not needed due to disabled birthday feature
        # config = {
        #     'apiKey': os.getenv('FIREBASE_API_KEY'),
        #     'authDomain': os.getenv('FIREBASE_AUTH_DOMAIN'),
        #     'storageBucket': os.getenv('FIREBASE_STORAGE_BUCKET'),
        #     'databaseURL': os.getenv('FIREBASE_DATABASE_URL')
        # }
        # firebase = pyrebase.initialize_app(config)
        # database = firebase.database()

        # Add cogs here
        self.add_cog(basic_cog.Basic(self))
        self.add_cog(translate_cog.Translate())
        self.add_cog(catch_cog.Catch())
        self.add_cog(famous_vikings_cog.FamousVikings())
        self.add_cog(meme_cog.Meme(self))
        self.add_cog(awards_cog.Awards(self))
Ejemplo n.º 26
0
def generate_embed(birthday):
    dateVal = birthday.val()['birthday']

    dateObj = datetime.strptime(dateVal, '%d/%m/%Y')
    today = datetime.now()
    age = today.year - dateObj.year
    if today.month < dateObj.month or (today.month == dateObj.month
                                       and today.day < dateObj.day):
        age -= 1

    description = birthday.val()['description']

    embed = Embed(title=birthday.key(), color=Color.purple())
    embed.add_field(name="Birth date", value=dateVal, inline=True)
    embed.add_field(name="Current Age", value=age, inline=True)
    embed.add_field(name="Who", value=description, inline=False)
    embed.set_footer(
        text=
        "Viking Rally - 19th to 21st November 2021 @ Moor House Adventure Centre, Durham",
        icon_url=
        "https://viking-rally.ssago.org/img/events/236/media/Viking%20Rally%20Logo.png"
    )

    return embed
Ejemplo n.º 27
0
    async def delegate(self, ctx):
        from pprint import pprint
        delegate_name = self.bot.bot_settings["delegateName"]
        data = self.delegates.get_delegates()

        vote_ranks = "total_vote_count"
        new_list = [{
            "delegate_name": x["delegate_name"],
            f"{vote_ranks}": int(x[vote_ranks])
        } for x in data
                    if int(x[vote_ranks]) > 0 and x["online_status"] != 'false'
                    ]
        s_vote_ranks = sorted(new_list,
                              key=lambda d: d[vote_ranks],
                              reverse=True)

        location_votes = 0
        delegate_ranks = dict()
        for d in s_vote_ranks:
            location_votes += 1
            if d["delegate_name"] == delegate_name:
                delegate_ranks["votes"] = location_votes

        block_ranks = "block_producer_total_rounds"
        new_list = [
            {
                "delegate_name": x["delegate_name"],
                f"{block_ranks}": int(x[block_ranks])
            } for x in data
            if int(x[block_ranks]) > 0 and x["online_status"] != 'false'
        ]
        s_block_ranks = sorted(new_list,
                               key=lambda d: d[block_ranks],
                               reverse=True)

        location_blocks = 0
        for d in s_block_ranks:
            location_blocks += 1
            if d["delegate_name"] == delegate_name:
                delegate_ranks["blocks"] = location_blocks

        verifier_ranks = "block_verifier_total_rounds"
        new_list = [
            {
                "delegate_name": x["delegate_name"],
                f"{verifier_ranks}": int(x[verifier_ranks])
            } for x in data
            if int(x[verifier_ranks]) > 0 and x["online_status"] != 'false'
        ]
        s_verifier_ranks = sorted(new_list,
                                  key=lambda d: d[verifier_ranks],
                                  reverse=True)

        location_verifier = 0
        for d in s_verifier_ranks:
            location_verifier += 1
            if d["delegate_name"] == delegate_name:
                delegate_ranks["verifier"] = location_verifier

        delegate_rank = Embed(title=f':trophy: {delegate_name}',
                              colour=Color.purple())
        delegate_rank.set_thumbnail(url=self.bot.user.avatar_url)
        delegate_rank.add_field(name=':ballot_box: Rank by votes',
                                value=f'{delegate_ranks["votes"]}',
                                inline=False)
        delegate_rank.add_field(name=':judge: Verifier rank',
                                value=f'{delegate_ranks["verifier"]}',
                                inline=False)
        delegate_rank.add_field(name=':bricks: Block produced rank',
                                value=f'{delegate_ranks["blocks"]}',
                                inline=False)
        await ctx.author.send(embed=delegate_rank)
Ejemplo n.º 28
0
from discord import Color

COLOR_SUCCESS = Color.green()
COLOR_ERROR = Color.red()
COLOR_GENERIC = Color.purple()
Ejemplo n.º 29
0
    results = await player.node.get_tracks(query)
    if not results or not results['tracks']:
        return 'Ничего не найдено'
    if results['loadType'] == 'PLAYLIST_LOADED':
        return Playlist(results['playlistInfo']['name'], results['tracks'])
    if is_url or force_first or len(results['tracks']) == 1:
        return results['tracks'][0]
    return results['tracks']


embed_colors = {
    'youtube.com': Color.red(),
    'youtu.be': Color.red(),
    'open.spotify.com': Color.green(),
    'soundcloud.com': Color.orange(),
    'twitch.tv': Color.purple(),
    'bandcamp.com': Color.blue(),
    'vk.com': Color.blue(),
    'vimeo.com': Color.dark_blue()
}


def get_embed_color(query):
    if spotify_rx.match(query):
        return Color.green()
    if url_rx.match(query):
        for service in embed_colors:
            if service in query:
                return embed_colors[service]
        return Color.blurple()
    return Color.red()
Ejemplo n.º 30
0
class FeatTypes(Enum):
    DIVINE = Color.from_rgb(255, 255, 255)
    MARTIAL = Color.orange()
    SKILL = Color.purple()
    WILD = Color.dark_green()