Beispiel #1
0
    def base_embed(self, ctx: Context) -> Embed:
        """Create All Embed, Ready to update."""

        embed = Embed(
            description = "Click the reaction to select and edit.",
            colour = Colour.teal(),
            timestamp = ctx.message.created_at
        )

        embed.set_author(name = "Homework Menu", icon_url = ctx.author.avatar_url)
        embed.set_footer(text = "Send message to set info!")

        # Declare variable to use later.
        details = self.tasks[ctx.author.id]["details"]
        header = details["headers"]
        state = details["state"]
        
        # Create a header, Not including Image because It will be process later on.
        for n in header:
            name = self.get_title_from_key(n, state)
            value = self.bot.planner.get_readable_date(header[n])
            embed.add_field(name=name, value=value, inline=False)

        # Check if Image Attached or not
        if details["image"] != "Not Attached":
            # Image Attached, Attach add it into embed.
            embed.set_image(url=details["image"])
        else:
            # If not, Add field instead.
            embed.add_field(
                name=self.get_title_from_key("image", state), value = details["image"], inline=False
            )
        return embed
Beispiel #2
0
    async def warn(self,
                   ctx,
                   m: discord.Member = None,
                   reason: str = 'No reason specified.'):
        if m is None:
            return await ctx.reply(
                'You didnt specify a member! Usage:\n`warn <member> <reason>')

        _id = "".join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(15))

        await self.db.execute("INSERT INTO warnings VALUES('" + str(_id) +
                              "','" + str(m.id) + "')")
        e = em(
            description=
            f'I have warned {m.mention} for the reason **{reason}** with the warn id: `{_id}`',
            colour=Colour.teal(),
            timestamp=datetime.utcnow())
        await ctx.reply(embed=e)

        e2 = em(
            description=
            f'You got warned on **{ctx.guild}** by {ctx.author.mention} for the reason: **{reason}**\nWarn ID: `{_id}`',
            colour=Colour.red())
        await m.send(embed=e2)
Beispiel #3
0
    async def command_formatting(self, command: Command) -> Embed:
        # Return Embed of command
        embed = Embed(title=":grey_question: Command Help",
                      colour=Colour.teal())

        parent = command.full_parent_name

        name = str(command) if not parent else f"{parent} {command.name}"
        command_details = f"**```{PREFIX}{name} {command.signature}```**\n"

        # show command aliases
        aliases = [
            f"`{alias}`" if not parent else f"`{parent} {alias}`"
            for alias in command.aliases
        ]
        aliases += [
            f"`{alias}`" for alias in getattr(command, "root_aliases", ())
        ]
        aliases = ", ".join(sorted(aliases))
        if aliases:
            command_details += f"**Can also use:** {aliases}\n\n"

        # check if the user is allowed to run this command
        if not await command.can_run(self.context):
            command_details += "***You cannot run this command.***\n\n"

        command_details += f"*{command.help or 'No details provided.'}*\n"
        embed.description = command_details

        return embed
Beispiel #4
0
    def __init__(self, image, username):
        super().__init__(
                title=image['Name'],
                type="rich"
            )

        self.set_image(url=image['Url'])
        self.colour = Colour.teal()
        self.add_field(name="Requester", value=username)
Beispiel #5
0
    async def send_bot_help(self, mapping: dict) -> None:
        """Sends help for all bot commands and cogs."""
        bot = self.context.bot

        embed = Embed(title=":grey_question: Command Help",
                      colour=Colour.teal())

        filter_commands = await self.filter_commands(bot.commands,
                                                     sort=True,
                                                     key=self._category_key)

        cog_or_category_pages = []

        for cog_or_category, _commands in itertools.groupby(
                filter_commands, key=self._category_key):
            sorted_commands = sorted(_commands, key=lambda c: c.name)

            if len(sorted_commands) == 0:
                continue

            command_detail_lines = self.get_commands_brief_details(
                sorted_commands, return_as_list=True)

            # Split cogs or categories which have too many commands to fit in one page.
            # The length of commands is included for later use when aggregating into pages for the paginator.
            for index in range(0, len(sorted_commands), COMMANDS_PER_PAGE):
                truncated_lines = command_detail_lines[index:index +
                                                       COMMANDS_PER_PAGE]
                joined_lines = "".join(truncated_lines)
                cog_or_category_pages.append(
                    (f"**{cog_or_category}**{joined_lines}",
                     len(truncated_lines)))

        pages = []
        counter = 0
        page = ""
        for page_details, length in cog_or_category_pages:
            counter += length
            if counter > COMMANDS_PER_PAGE:
                # force a new page on paginator even if it falls short of the max pages
                # since we still want to group categories/cogs.
                counter = length
                pages.append(page)
                page = f"{page_details}\n\n"
            else:
                page += f"{page_details}\n\n"

        if page:
            # add any remaining command help that didn't get added in the last iteration above.
            pages.append(page)

        await LinePaginator.paginate(pages,
                                     self.context,
                                     embed=embed,
                                     max_lines=1,
                                     max_size=2000)
Beispiel #6
0
    async def on_member_update(before, after):
        broles = ""
        aroles = ""

        for i in range(len(before.roles)):
            broles += str(before.roles[i].mention) + ", "

        for i in range(len(after.roles)):
            aroles += str(after.roles[i].mention) + ", "

        if before.roles != after.roles:
            embed = discord.Embed(title=str(before.name) + "'s Roles Changed",
                                  colour=Colour.teal())
            embed.add_field(name="Old Roles", value=broles)
            embed.add_field(name="New Roles", value=aroles)

            guild = before.guild
            await guild.get_channel(649677778014437378).send(embed=embed)
            await bot.get_guild(647218684095365139).get_channel(
                653687223266443264).send(embed=embed)

        # async for entry in after.guild.audit_logs(limit=1, after=datetime.utcnow, action=discord.AuditLogAction.member_update):
        #    await before.guild.get_channel(649677778014437378).send('{0.user} updated {0.target}s role(s)'.format(entry))

        if before.nick != after.nick:
            embed = discord.Embed(title="Member changed Nick",
                                  colour=Colour.teal())
            embed.add_field(name="Old Username", value=str(before.nick))
            embed.add_field(name="New Nick", value=after.nick)

            guild = before.guild
            await guild.get_channel(649677778014437378).send(embed=embed)
            await bot.get_guild(647218684095365139).get_channel(
                653687223266443264).send(embed=embed)

            f = open(
                "logs/discord/member_update/" +
                datetime.now().strftime('%Y-%m-%d') + ".log", "a+")
            f.write(datetime.now().strftime('%Y-%m-%d - %I:%M %p') + " | " +
                    str(before.name) + "'s nick was changed from " +
                    str(before.nick) + " to " + str(after.nick) + "\n")
            f.close()
Beispiel #7
0
    async def warnings(self, ctx, m: discord.Member = None):
        if m is None:
            return await ctx.reply('You didnt specify a member to view warnings! Usage:\n`warnings <member>`')
        
        r = await self.db.execute('SELECT * FROM warnings WHERE user_id = ' + str(m.id) + '')

        warnings = []
        for i in range(len(r)):
            warnings.append(f'{i + 1} - {r[i][0]}')

        e = em(title=f'{m}(s) Warnings', colour=Colour.teal(), description='\n'.join(warnings), timestamp=datetime.utcnow())
        e . set_thumbnail(url=self.bot.user.avatar_url_as(format='png'))
        await ctx.reply(embed=e)
Beispiel #8
0
    def get_random_color() -> Colour:

        """
        TODO: Add more colors that look good
        :return:
        """

        colors = [
            Colour.blurple(), Colour.dark_blue(), Colour.dark_orange(),
            Colour.dark_magenta(), Colour.teal(), Colour.magenta(),
            Colour.dark_gold(), Colour.blurple()
        ]

        return random.choice(colors)
    async def push_version_change(self, old_version: int,
                                  new_version: int) -> None:
        embed = Embed(title="Version Change Detected",
                      colour=Colour.teal(),
                      timestamp=datetime.utcnow())

        patch_notes = "\n".join(self.bot.config.note) if len(
            self.bot.config.note) != 0 else "No patch note were found."

        embed.description = "Version **{}** → **{}**".format(
            old_version, new_version)
        embed.add_field(name="Patch Note:", value=patch_notes)

        await self.bot.get_channel(762326316455821363).send(embed=embed)
Beispiel #10
0
    async def unwarn(self, ctx, m: discord.Member = None, warnid: str = None):
        if m is None or warnid is None:
            return await ctx.reply(
                'You didnt specify a member to unwarn! Usage:\n`unwarn <member> <warn id>`'
            )

        await self.db.execute("DELETE FROM warnings WHERE warn_id = '" +
                              warnid + "'")
        e = em(description=
               f'I have removed the warning **{warnid}** from {m.mention}.',
               colour=Colour.green())
        await ctx.reply(embed=e)

        e2 = em(
            description=
            f'Your warning by the id **{warnid}** got removed by {ctx.author.mention}!',
            colour=Colour.teal())
        await m.send(embed=e2)
Beispiel #11
0
 async def update_events(self, interval: int = 12):
     '''
     Updates the events channel.
     :interval (int): The interval in hours to update.
     '''
     bot = self.bot
     await bot.wait_until_ready()
     channel = bot.get_channel(bot.events_channel)
     logging.info(f'update_events being ran on {channel}.')
     while bot.is_ready():
         logging.info('sending an event update.')
         seconds = interval * 3600
         now = datetime.utcnow().replace(tzinfo=pytz.utc)
         wiki = await gbfwiki.init_wiki()
         events = wiki.get_events()
         msg_current = Embed(title='Granblue Fantasy Current Events',
                             url='https://gbf.wiki',
                             color=Colour.teal(),
                             timestamp=now)
         for event in events['current']:
             msg_current.add_field(
                 name=f"[{event['title']}]({event['url']})",
                 value=f"Ends on {event['finish']}",
                 inline=False)
         msg_upcoming = Embed(title='Granblue Fantasy Upcoming Events',
                              url='https://gbf.wiki',
                              color=Colour.dark_purple(),
                              timestamp=now)
         for event in events['upcoming']:
             msg_upcoming.add_field(
                 name=f"[{event['title']}]({event['url']})",
                 value=f"{event['start']} to {event['finish']}",
                 inline=False)
         existing_messages = []
         async for message in channel.history(limit=200):
             # Assume the first message to edit is the current events,
             # and the second message is the upcoming events.
             if message.author == bot.user and message.pinned:
                 existing_messages.append(message)
             if len(existing_messages) >= 2:
                 break
         await existing_messages[0].edit(embed=msg_current)
         await existing_messages[1].edit(embed=msg_upcoming)
         await asyncio.sleep(seconds)
Beispiel #12
0
	def __init__(self, fissures):
		"""Generate an embed containing the list of fissures

		Parameters:
		-----------

		l_fissures: iterable of :class:`warframe.parser.fissure.Fissure`
		The list of fissures.

		platform: str [Optional]
		The platform those fissures are on.
		"""

		title = "Fissures"
		Embed.__init__(self, title = title, type = "rich")
		self.url = "http://warframe.wikia.com/wiki/Void_Fissure"
		for fissure in fissures:
			self.add_fissure(fissure)
		self.colour = Colour.teal()
Beispiel #13
0
    async def show_next_shuffle(self) -> None:
        if not self.is_ready():
            raise UsageException.not_enough_for_match(self.channel)

        if "shuffles" not in self._cache:
            matches = self.get_matches()
            shuffle(matches)
            self._cache["shuffles"] = iter(enumerate(matches))

        next_match = next(self._cache["shuffles"], None)
        if next_match is None:
            raise UsageException.seen_all_matches(self.channel)

        (number, match) = next_match
        embed = Embed(colour=Colour.teal())
        embed.title = f"Shuffle {number+1}"
        for i, team in enumerate(match):
            players = "".join([f"• {p.get_name()}\n" for p in team])
            players = players if players else "(empty)"
            embed.add_field(name=f"Team {i+1}", value=players, inline=False)
        await self.channel.send(embed=embed)
Beispiel #14
0
 async def info(self, ctx):
     '''
     Outputs running info about this bot.
     '''
     guild = ctx.guild if ctx.guild else 'a direct message'
     logging.info(f'blame requested by {ctx.author} in {guild}.')
     app_info = await self.bot.application_info()
     msg = Embed(
         title='Silva (https://github.com/brasstax/silva)',
         url='https://github.com/brasstax/silva',
         color=Colour.teal())
     msg.set_author(
         name='Silva',
         url='https://github.com/brasstax/silva',
         icon_url=app_info.icon_url)
     msg.add_field(
         name="Author",
         value=app_info.owner,
         inline=False)
     msg.add_field(
         name="Framework",
         value=f"Discord.py {__version__}"
     )
     await ctx.send(embed=msg)
Beispiel #15
0
async def status(ctx, *args):
    """Get the bot status including uptime, API connection, latency and owner."""
    uptime = get_uptime()
    api_status = await check_status()
    app_info = await bot.application_info()
    latency = int(bot.latency * 1000)

    if api_status == 0:
        api_txt = "```glsl\nDown\n```"
    elif api_status == 1:
        api_txt = "```yaml\nGood\n```"
    else:
        api_txt = "```fix\nSlow\n```"

    if bot.is_closed():
        ws_conn = "```glsl\nClosed\n```"
    else:
        ws_conn = "```yaml\nOpen\n```"

    embed = Embed(title=f"Status - {app_info.name}",
                  description=f"{app_info.description}",
                  url="https://github.com/SmCTwelve/f1-bot",
                  colour=Colour.teal())
    embed.set_thumbnail(
        url=app_info.icon_url or "https://i.imgur.com/kvZYOue.png")
    embed.add_field(name='Owner', value=app_info.owner.name, inline=True)
    embed.add_field(name='Source',
                    value="[GitHub](https://github.com/SmCTwelve/f1-bot)",
                    inline=True)
    embed.add_field(name='Ping', value=f'{latency} ms', inline=True)
    embed.add_field(name='Uptime',
                    value=f'{uptime[0]}d, {uptime[1]}h, {uptime[2]}m',
                    inline=True)
    embed.add_field(name='Websocket', value=ws_conn, inline=True)
    embed.add_field(name='API Connection', value=api_txt, inline=True)
    await ctx.send(embed=embed)
Beispiel #16
0
def make_poll_help_embed(ctx: Context) -> Embed:
    """
    投票機能の説明のEmbedを生成します。

    :param ctx: Context
    :return: 生成したEmbed
    """
    embed = Embed(title="投票機能の使い方", colour=Colour.teal())
    embed.add_field(name="投票の作成: 基本的な構文",
                    value=SYNTAX_MESSAGE.format(prefix=ctx.prefix),
                    inline=False)
    embed.add_field(name="投票の作成: 投票数を制限する",
                    value=LIMITED_MESSAGE.format(prefix=ctx.prefix),
                    inline=False)
    embed.add_field(
        name="投票の終了",
        value=f"`{ctx.prefix}poll end <投票ID>`\n投票を終了します。これ以降のリアクションの変更は無視されます。"
    )
    embed.add_field(
        name="投票の集計",
        value=
        f"`{ctx.prefix}poll result <投票ID>`\n投票の集計をします。投票を終了していた場合、終了時までの投票のみが集計されます。",
        inline=False)
    return embed
Beispiel #17
0
    async def process_reaction_event(self, payload: RawReactionActionEvent) -> None:
        """
        Process Reaction event.

        Checks:
            * Emoji is in the list.
            * User has a menu opened.
            * State of menu needs to be valid.

        """
        emoji = str(payload.emoji)
        
        if emoji not in EMOJIS or \
        payload.user_id not in self.tasks or \
        self.tasks[payload.user_id]['details']['state'] == 0:
            return
        
        ctx = self.tasks[payload.user_id]["info"]["ctx"]
        old_state = self.tasks[payload.user_id]["details"]["state"]
        log.debug(f'processing {emoji} for {ctx.author.id}')

        if emoji == "❎": # Close menu
            await self.close(ctx)
            return        
        elif emoji == "✅":
            type_ = self.tasks[ctx.author.id]['details']['type']

            if self.bot.planner.check_passed_date(self.tasks[ctx.author.id]["details"]["headers"]["date"]):
                log.debug(f'{ctx.author.id} tried to add/edit passed assignment.')
                await self.close(ctx, "Cannot add/edit already passed assignment.")
                return
            
            title = self.tasks[ctx.author.id]["details"]["headers"]["title"]
            description = self.tasks[ctx.author.id]["details"]["headers"]["description"]
            date = self.tasks[ctx.author.id]["details"]["headers"]["date"]
            image_url = self.tasks[ctx.author.id]["details"]["image"]

            if all( 
                (title == "Untitled", description == "No Description Provied", 
                date == "Unknown", image_url == "Not Attached") 
            ): 
                log.debug(f'{ctx.author.id} tried to add/edit to invalid assignement.')
                await self.close(ctx, "Invalid Assignment")
                return
            
            try:
                ret = await self.bot.planner.add(
                    ctx.guild.id,
                    title = title,
                    description = description,
                    date = date,
                    image_url = image_url,
                    key = self.tasks[ctx.author.id]['details']['key']
                )

            except Exception:                
                text = f"Unable to {type_} Assignment, Problem has been reported."
                log.warning(f'something went wrong while {ctx.author.id} add/edit in homework menu')
                log.warning(traceback.format_exc())
                await self.bot.log(__name__, f"An Exception were found while finishing adding assignment\n```py\n{traceback.format_exc()}\n```", True)
                colour = Colour.default()

            else:
                text = f"Successfully Added Assignment with key `{ ret }`" if type_ == 'add' \
                else "Successfully Edited Assignment."
                colour = Colour.teal()
                log.debug(f'{ctx.author.id} add/edit new assignment and passed in successfully.')

            await self.close(ctx, text, colour)
            return

        elif emoji == "1️⃣":
            self.tasks[payload.user_id]["details"]["state"] = 1
        elif emoji == "2️⃣":
            self.tasks[payload.user_id]["details"]["state"] = 2
        elif emoji == "3️⃣":
            self.tasks[payload.user_id]["details"]["state"] = 3
        elif emoji == "4️⃣":
            self.tasks[payload.user_id]["details"]["state"] = 4
        
        if old_state != self.tasks[payload.user_id]["details"]["state"]:
            # update if the state changed.
            await self.update_embed(ctx)
Beispiel #18
0
 async def events(self, ctx):
     '''
     Gets information from gbf.wiki on current and future events.
     '''
     guild = ctx.guild if ctx.guild else 'a direct message'
     logging.info(f'events requested by {ctx.author} in {guild}.')
     thinking_msg = 'One sec, grabbing the current and upcoming events.'
     msg = await ctx.send(thinking_msg)
     now = datetime.utcnow().replace(tzinfo=pytz.utc)
     try:
         wiki = await gbfwiki.init_wiki()
         events = wiki.get_events()
         msg_current = Embed(
             title='Granblue Fantasy Current Events',
             url='https://gbf.wiki',
             color=Colour.teal(),
             timestamp=now)
         for event in events['current']:
             msg_current.add_field(
                 name=f"[{event['title']}]({event['url']})",
                 value=f"Ends on {event['finish']}",
                 inline=False
             )
         msg_upcoming = Embed(
             title='Granblue Fantasy Upcoming Events',
             url='https://gbf.wiki',
             color=Colour.dark_purple(),
             timestamp=now)
         for event in events['upcoming']:
             msg_upcoming.add_field(
                 name=f"[{event['title']}]({event['url']})",
                 value=f"{event['start']} to {event['finish']}",
                 inline=False
             )
         # send to a dedicated event channel if the message is not a DM
         if ctx.guild:
             events_channel = self.bot.get_channel(self.bot.events_channel)
         else:
             events_channel = ctx
         # If the event channel exists, search to see if the bot has posted
         # existing events before. If so, edit those instead of sending
         # a new embed. Best used for an events channel that is locked to
         # posting only by the bot.
         if ctx.guild:
             existing_messages = []
             async for message in events_channel.history(limit=200):
                 # Assume the first message to edit is the current events,
                 # and the second message is the upcoming events.
                 if message.author == self.bot.user and message.pinned:
                     existing_messages.append(message)
                 if len(existing_messages) >= 2:
                     break
             if not existing_messages:
                 await events_channel.send(embed=msg_current)
                 await events_channel.send(embed=msg_upcoming)
             else:
                 await existing_messages[0].edit(embed=msg_current)
                 await existing_messages[1].edit(embed=msg_upcoming)
         else:
             await events_channel.send(embed=msg_current)
             await events_channel.send(embed=msg_upcoming)
         if ctx.guild:
             mention_msg = (
                 f'Hi {ctx.author.mention}! I posted the current and'
                 f' upcoming events in {events_channel.mention}.')
         else:
             mention_msg = 'Here you go!'
         await msg.edit(content=mention_msg)
     except Exception as e:
         logging.warning(f'Could not retrieve events: {e}')
         await msg.edit(
             content="I couldn't retrieve the events at this time.")
Beispiel #19
0
 async def check_live_streams(self):
     channel = hkd.get_seiyuu_channel(self.bot.guilds)
     now = datetime.utcnow().isoformat() + 'Z'
     with suppress(Exception):
         events = self.calendar.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute().get('items', [])
         first_event = True
         for event in events:
             start = parser.parse(event['start'].get('dateTime', event['start'].get('date')))
             if start.timestamp() - time.time() < 900 and event['description'][0] != '*':
                 with suppress(Exception):
                     split_index = event['description'].find(';')
                     wug_members_str, stream_link = event['description'][:split_index], event['description'][split_index + 1:]
                     wug_members = wug_members_str.split(',')
                     if (link_start := stream_link.find('<a')) > 0:
                         stream_link = stream_link[:link_start]
                     elif stream_link.startswith('<a'):
                         stream_link = BeautifulSoup(stream_link, 'html.parser').find('a').contents[0]
                     colour = hkd.get_oshi_colour(hkd.get_wug_guild(self.bot.guilds), wug_members[0]) if len(wug_members) == 1 else Colour.teal()
                     embed_fields = []
                     embed_fields.append(('Time', '{0:%Y}-{0:%m}-{0:%d} {0:%H}:{0:%M} JST'.format(start.astimezone(pytz.timezone('Japan')))))
                     embed_fields.append(('WUG Members', ', '.join(wug_members)))
                     content = '**Starting in 15 Minutes**' if first_event else ''
                     await channel.send(content=content, embed=hkd.create_embed(title=event['summary'], colour=colour, url=stream_link, fields=embed_fields))
                     first_event = False
                     event['description'] = '*' + event['description']
                     self.calendar.events().update(calendarId='primary', eventId=event['id'], body=event).execute()
Beispiel #20
0
    async def on_message(self, message, **kwargs):
        assert isinstance(message, Message)
        client = self.client

        prefix = kwargs.get("prefix")

        if not is_valid_command(message.content, valid_commands,
                                prefix=prefix):
            return
        else:
            self.stats.add(MESSAGE)

        def startswith(*args):
            for a in args:
                if message.content.startswith(a):
                    return True

            return False

        if startswith(prefix + "osu"):
            username = message.content[len(prefix + "osu "):]

            t_start = time.time()

            user = self.osu.get_user(username)

            if not user:
                await client.send_message(message.channel,
                                          "User does not exist.")
                return

            # About inverting: this inverts the number before and after the splitting
            def prepare(this):
                if not type(this) in (float, int):
                    return None

                return invert_str(",".join(
                    split_every(str(invert_num(this)), 3)))

            global_rank = prepare(user.world_rank)
            country_rank = prepare(user.country_rank)

            total_score = prepare(user.total_score)
            ranked_score = prepare(user.ranked_score)

            try:
                acc = str(round(float(user.accuracy), 2)) + " %"
            except TypeError:
                await client.send_message(message.channel,
                                          ":warning: Something went wrong...")
                return

            pp_amount = str(int(float(user.pp)))

            osu_level = int(float(user.level))
            avatar_url = "http://a.ppy.sh/{}".format(user.id)

            # Color is determined by the level range
            if osu_level < 10:
                color = Colour.darker_grey()
            elif osu_level < 25:
                color = Colour.light_grey()
            elif osu_level < 40:
                color = Colour.dark_teal()
            elif osu_level < 50:
                color = Colour.teal()
            elif osu_level < 75:
                color = Colour.dark_purple()
            elif osu_level < 100:
                color = Colour.purple()
            # Only the masters get the gold ;)
            else:
                color = Colour.gold()

            desc = "**Level**: {}\n**Rank**: \n\t" \
                   "**Global**:            #{}\n\t" \
                   "**Country** (**{}**): #{}\n" \
                   "Total PP: **{}**".format(osu_level, global_rank, user.country, country_rank, pp_amount)

            embed = Embed(url=user.profile_url, description=desc, colour=color)
            embed.set_author(name=user.name)
            embed.set_thumbnail(url=avatar_url)

            embed.add_field(name="Total score", value=total_score)
            embed.add_field(name="Ranked score", value=ranked_score)
            embed.add_field(name="Average accuracy", value=acc)

            delta = int((time.time() - t_start) * 1000)
            embed.set_footer(text="Search took {} ms".format(delta))

            try:
                await client.send_message(message.channel, embed=embed)
            except errors.HTTPException:
                await client.send_message(
                    message.channel,
                    "Something went wrong " + StandardEmoji.THINKING)
Beispiel #21
0
from discord import Colour
from random import seed, randint
from datetime import datetime

seed(datetime.now())

colours = [
    Colour.teal(),
    Colour.dark_teal(),
    Colour.green(),
    Colour.dark_green(),
    Colour.blue(),
    Colour.dark_blue(),
    Colour.purple(),
    Colour.dark_purple(),
    Colour.magenta(),
    Colour.dark_magenta(),
    Colour.gold(),
    Colour.dark_gold(),
    Colour.orange(),
    Colour.dark_orange(),
    Colour.red(),
    Colour.dark_red(),
    Colour.lighter_grey(),
    Colour.light_grey(),
    Colour.dark_grey(),
    Colour.darker_grey(),
    Colour.blurple(),
    Colour.greyple(),
    Colour.from_rgb(randint(0, 255), randint(0, 255), randint(0, 255))
]
Beispiel #22
0
            if r.id in hkd.WUG_KAMIOSHI_ROLE_IDS.values()
        ]
        kamioshi_role_name = existing_kamioshi_roles[
            0].name if existing_kamioshi_roles else ''
        for oshi in hkd.WUG_ROLE_IDS:
            if (role := disc_utils.get(ctx.guild.roles,
                                       id=hkd.WUG_ROLE_IDS[oshi])
                ) not in ctx.author.roles and role.name != kamioshi_role_name:
                roles_to_add.append(role)
        if roles_to_add:
            await ctx.author.add_roles(*roles_to_add)
            await ctx.send(embed=hkd.create_embed(
                description=
                'Hello {0.author.mention}, you now have every WUG member role.'
                .format(ctx),
                colour=Colour.teal()))
        else:
            await ctx.send(embed=hkd.create_embed(
                description=
                'Hello {0.author.mention}, you already have every WUG member role.'
                .format(ctx),
                colour=Colour.red()))

    @cog_ext.cog_slash(
        description=
        "Set a WUG member as your kamioshi. This will make their role show up at the top.",
        guild_ids=hkd.get_all_guild_ids(),
        options=[
            create_option(
                name="member",
                description="The member that you want to set as your kamioshi.",
Beispiel #23
0
def get_oshi_colour(guild, member):
    with suppress(Exception):
        if member == 'Everyone':
            return Colour.teal()
        return get_wug_role(guild, member).colour
Beispiel #24
0
 async def events(self, ctx: SlashContext, date: str = ''):
     await ctx.defer()
     event_urls = []
     current_time = datetime.now(timezone('Japan'))
     search_date = parser.parse(date) if date else current_time
     if current_time.month > search_date.month or current_time.month == search_date.month and current_time.day > search_date.day:
         search_year = current_time.year + 1
     else:
         search_year = current_time.year
     first = True
     for _ in range(3):
         with suppress(Exception):
             soup = hkd.get_html_from_url(
                 'https://www.eventernote.com/events/month/{0}-{1}-{2}/1?limit=1000'
                 .format(search_year, search_date.month, search_date.day))
             result = soup.find_all(
                 attrs={'class': ['date', 'event', 'actor', 'note_count']})
             for event in [
                     result[i:i + 4] for i in range(0, len(result), 4)
             ]:
                 info = event[1].find_all('a')
                 event_time = event[1].find('span')
                 if (event_url := info[0]['href']) not in event_urls:
                     performers = [
                         p.contents[0] for p in event[2].find_all('a')
                     ]
                     wug_performers = [
                         p for p in performers if p in hkd.WUG_MEMBERS
                     ]
                     if not wug_performers:
                         continue
                     colour = hkd.get_oshi_colour(
                         ctx.guild,
                         list(hkd.WUG_ROLE_IDS.keys())
                         [hkd.WUG_MEMBERS.index(wug_performers[0]) -
                          1]) if len(
                              wug_performers) == 1 else Colour.teal()
                     if first:
                         first = False
                         await ctx.send(
                             '**Events Involving WUG Members on {0:%Y}-{0:%m}-{0:%d} ({0:%A})**'
                             .format(search_date.replace(year=search_year)))
                         await asyncio.sleep(0.5)
                     other_performers = [
                         p for p in performers if p not in hkd.WUG_MEMBERS
                         and p not in hkd.WUG_OTHER_UNITS
                     ]
                     embed_fields = []
                     embed_fields.append(('Location', info[1].contents[0]))
                     embed_fields.append(
                         ('Time', event_time.contents[0]
                          if event_time else 'To be announced'))
                     embed_fields.append(
                         ('WUG Members', ', '.join(wug_performers)))
                     embed_fields.append(
                         ('Other Performers', ', '.join(other_performers)
                          if other_performers else 'None'))
                     embed_fields.append(('Eventernote Attendees',
                                          event[3].find('p').contents[0]))
                     event_urls.append(event_url)
                     await asyncio.sleep(0.5)
                     await ctx.send(embed=hkd.create_embed(
                         title=info[0].contents[0],
                         colour=colour,
                         url='https://www.eventernote.com{0}'.format(
                             event_url),
                         thumbnail=event[0].find('img')['src'],
                         fields=embed_fields,
                         inline=True))
             break
Beispiel #25
0
 if (event_url := info[0]['href']) not in event_urls:
     performers = [
         p.contents[0] for p in event[2].find_all('a')
     ]
     wug_performers = [
         p for p in performers if p in hkd.WUG_MEMBERS
     ]
     if not wug_performers:
         continue
     await ctx.defer()
     colour = hkd.get_oshi_colour(
         ctx.guild,
         list(hkd.WUG_ROLE_IDS.keys())
         [hkd.WUG_MEMBERS.index(wug_performers[0]) -
          1]) if len(
              wug_performers) == 1 else Colour.teal()
     if first:
         first = False
         await ctx.send(
             '**Events for {0} in {1} {2}**'.format(
                 member.title()
                 if member else 'Wake Up, Girls!',
                 month_name[int(search_month)],
                 search_year))
         await asyncio.sleep(0.5)
     other_performers = [
         p for p in performers
         if p not in hkd.WUG_MEMBERS
         and p not in hkd.WUG_OTHER_UNITS
     ]
     embed_fields = []
Beispiel #26
0
 async def shiba(self, ctx):
     async with self.session.get("http://shibe.online/api/shibes") as req:
         json = await req.json()
         await ctx.send(embed=Embed(colour=Colour.teal()).set_image(
             url=json[0]))