Пример #1
0
async def queue_(
    client,
    event,
):
    player = client.solarlink.get_player(event.guild_id)
    
    queue = player.queue
    
    embed = Embed(
        'Music queue',
        (
            f'Total number of tracks {len(queue)}\n'
            f'Total duration: {duration_to_string(get_queue_duration(player))}'
        ),
    )
    
    track = player.get_current()
    if (track is not None):
        embed.add_field('Currently playing', create_track_repr(track, None))
    
    if queue:
        tracks_list = [create_track_repr(repr, index) for track, index in zip(queue, range(1, 6))]
        
        queue_length = len(queue)
        if queue_length > 5:
            tracks_list.append(f'\n*{queue_length-5} not shown*')
        
        
        embed.add_field('Track list', '\n'.join(tracks_list))
    
    return embed
async def list_of_cogs(client, message, content):
    cogs = []
    for i in os.listdir(os.path.join('cogs', 'hata')):
        if i.endswith('.py'):
            cogs.append(i[:-3])
    pages = []
    part = []
    index = 0
    for element in cogs:
        if index == 15:
            pages.append('\n'.join(part))
            part.clear()
            index = 0
        part.append(f'**>>** {element}')
        index += 1

    pages.append('\n'.join(part))

    del part

    result = []

    limit = len(pages)
    index = 0
    while index < limit:
        embed = Embed('Cogs:', color='029320', description=pages[index])
        index += 1
        embed.add_field('Cog-list', f'page {index} out of {limit}')
        result.append(embed)

    del pages
    await Pagination(client, message.channel, result)
Пример #3
0
    def create_page(self, index):
        end = index * 10
        start = end - 9
        if end > len(self.source.history):
            end = len(self.source.history)

        shard = []
        embed = Embed('Statistics', f'{start} - {end}', color=KANAKO_COLOR)

        add_options = self.source.possibilities

        for question_index, element in enumerate(
                self.source.history[start - 1:end], start):
            shard.append('```diff')
            if add_options:
                shard.append('\n')
                shard.append(', '.join([
                    f'{index}. : {option}'
                    for index, option in enumerate(element.options, 1)
                ]))
            for user_index, user in enumerate(self.source.users):
                value, time = element.answers[user_index]
                shard.append(
                    f'\n{"+" if element.answer==value else "-"} {user:f} : {value} ( {time:.2f} s )'
                )
            shard.append('\n```')
            embed.add_field(
                f'{question_index}.: {element.question} - {element.answer}',
                ''.join(shard))
            shard.clear()

        embed.add_footer(f'Page {index+1} / {len(self.cache)}')

        self.cache[index] = embed
        return embed
Пример #4
0
    async def command(client, message):
        guild = message.guild
        if guild is None:
            return

        welscome_screen = await client.welcome_screen_get(guild)
        if welscome_screen is None:
            embed = Embed(
                description=f'**{guild.name}** *has no welcome screen enabled*.'
            )
        else:
            embed = Embed(
                f'Welcome to **{guild.name}**',
                f'{welscome_screen.description}\n\n*TOP THINGS TO DO HERE*')

            icon_url = guild.icon_url
            if (icon_url is not None):
                embed.add_thumbnail(icon_url)

            for welcome_channel in welscome_screen.welcome_channels:
                embed.add_field(
                    f'{welcome_channel.emoji:e} {welcome_channel.description}',
                    f'#{welcome_channel.channel:d}')

        await client.message_create(message.channel, embed=embed)
Пример #5
0
async def latest_users(event):
    """Shows the new users of the guild."""
    date_limit = datetime.now() - timedelta(days=7)

    users = []
    guild = event.guild
    for user in guild.users.values():
        # `joined_at` might be set as `None` if the user is a lurker.
        # We can ignore lurkers, so use `created_at` which defaults to Discord epoch.
        created_at = user.guild_profiles[guild].created_at
        if created_at > date_limit:
            users.append((created_at, user))

    users.sort(reverse=True)
    del users[10:]

    embed = Embed('Recently joined users')
    if users:
        for index, (joined_at, user) in enumerate(users, 1):
            created_at = user.created_at
            embed.add_field(
                f'{index}. {user.full_name}',
                f'Id: {user.id}\n'
                f'Mention: {user.mention}\n'
                '\n'
                f'Joined : {joined_at:{DATETIME_FORMAT_CODE}} [*{elapsed_time(joined_at)} ago*]\n'
                f'Created : {created_at:{DATETIME_FORMAT_CODE}} [*{elapsed_time(created_at)} ago*]\n'
                f'Difference : {elapsed_time(relativedelta(created_at, joined_at))}',
            )

    else:
        embed.description = '*none*'

    return InteractionResponse(embed=embed, allowed_mentions=None)
Пример #6
0
def pagination_for_other_libs():
    if request.method != 'POST': return 401
    data = request.json
    pages = []
    part = []
    index = 0
    for element in data['lines']:
        if index == 60:
            pages.append('\n'.join(part))
            part.clear()
            index = 0
        part.append(f'{element}')
        index += 1

    pages.append('\n'.join(part))

    del part

    result = []

    limit = len(pages)
    index = 0
    while index < limit:
        embed = Embed('Pagination', color='029320', description=pages[index])
        index += 1
        embed.add_field(f"{index} pages in total", f'page {index}/{limit}')
        result.append(embed)

    del pages
    pdbot.loop.create_task_threadsafe(
        Pagination(pdbot, CHANNELS[int(data['channel'])], result))
Пример #7
0
async def is_banned(client, event, user: ('user', 'Who should I check?')):
    """Checks whether the user is banned."""
    if (not event.user.has_role(ROLE__NEKO_DUNGEON__TESTER)) and (
            not event.user_permissions.can_ban_users):
        abort('You need to have `ban users` permissions to do this.')

    if not event.channel.cached_permissions_for(client).can_ban_users:
        abort('I need to have `ban users` permissions to do this.')

    yield  # acknowledge the event

    try:
        ban_entry = await client.guild_ban_get(event.guild, user)
    except DiscordException as err:
        if err.code == ERROR_CODES.unknown_ban:
            ban_entry = None
        else:
            raise

    embed = Embed(f'Ban entry for {user:f}').add_thumbnail(user.avatar_url)

    if ban_entry is None:
        embed.description = 'The user **NOT YET** banned.'

    else:
        embed.description = 'The user is banned.'

        reason = ban_entry.reason
        if reason is None:
            reason = '*No reason was specified.*'

        embed.add_field('Reason:', reason)

    yield embed
Пример #8
0
async def rule(client, message, rule_number):
    """
    Gives you the rule that you want
    """
    the_rule = SERVER_RULES.get(rule_number)
    embed = Embed(color=BLUE)
    embed.add_field(f'RULE {rule_number}', the_rule or "Does not Exist")
    return embed
Пример #9
0
 def render(self):
     message = self.target_message
     embed = Embed(render_message_content(message),
                   self.changes.render(),
                   color=AUTO_REACT_ROLE_COLOR)
     embed.add_author(message.author.avatar_url, message.author.full_name,
                      message.url)
     embed.add_field(AUTO_REACT_ROLE_GUI_EMBED_FIELD_NAME,
                     AUTO_REACT_ROLE_GUI_EMBED_FIELD_VALUE)
     return embed
Пример #10
0
async def prices(client, event):
    """Lists the prices of the shop."""
    embed = Embed('Witch shop')
    for item in BUYABLE:
        embed_field_name = f'{item.emoji:e} {item.name}'
        market_cost = item.market_cost
        embed_field_value = f'Sell for: {floor(market_cost*(1.0-MARKET_COST_FEE))} {EMOJI__HEART_CURRENCY:e}\n' \
                            f'Buy for: {floor(market_cost*(1.0+MARKET_COST_FEE))} {EMOJI__HEART_CURRENCY:e}'
        
        embed.add_field(embed_field_name, embed_field_value, inline=True)
    
    return embed
Пример #11
0
async def queue(client, message):
    guild = message.guild
    if guild is None:
        return
    
    voice_client = client.voice_client_for(message)
    color = VOICE_COLORS.get(client)
    
    title = f'Playing queue for {guild}'
    page = Embed(title, color=color)
    pages = [page]
    while True:
        if voice_client is None:
            page.description = '*none*'
            break
        
        source = voice_client.source
        if (source is not None):
            page.add_field('Actual:', source.title)
        
        queue = voice_client.queue
        limit = len(queue)
        if limit:
            index = 0
            while True:
                source = queue[index]
                index += 1
                page.add_field(f'Track {index}.:', source.title)
                
                if index == limit:
                    break
                
                if index%10 == 0:
                    page = Embed(title, color=color)
                    pages.append(page)
            
        else:
            if source is None:
                page.description = '*none*'
        
        break
    
    await Pagination(client, message.channel, pages)
Пример #12
0
    async def command(client, message,
                      target: Converter('user', flags=ConverterFlag.user_all)):
        source = message.author
        if source is target:
            prefix = client.command_processer.get_prefix_for(message)
            embed = Embed('love', ('How much you two fit together?\n'
                                   f'Usage: `{prefix}user *user*`'),
                          color=GAMES_COLOR)
        else:
            percent = ((source.id & 0x1111111111111111111111) +
                       (target.id & 0x1111111111111111111111)) % 101
            element = LOVE_VALUES[percent]

            embed = Embed(
                choice(element['titles']),
                f'{source:f} {BUILTIN_EMOJIS["heart"]:e} {target:f} scored {percent}%!',
                0xad1457,
            )
            embed.add_field('My advice:', element['text'])

        await client.message_create(message.channel, embed=embed)
Пример #13
0
async def help(client, message, content):
    if content not in [None, '']:
        return
    cmds = []
    for i in pdbot.events.message_create.commands:
        cmds.append(i)
    for y in os.listdir('./cmds/'):
        with open('./cmds/'+y, 'r') as f:
            x = json.load(f)
        for i in x:
            if i.lower() != 'help':
                cmds.append(i)
    cmds = sorted(cmds, key=str.lower) # Key positional argument is used to make sure uppercase commands don't take precedence.
    pages=[]
    part=[]
    index=0
    for element in cmds:
        if index==16:
            pages.append('\n'.join(part))
            part.clear()
            index=0
        part.append(f'**>>** {element}')
        index+=1

    pages.append('\n'.join(part))

    del part

    result=[]

    limit=len(pages)
    index=0
    while index<limit:
        embed=Embed('Commands:',color='029320',description=pages[index])
        index+=1
        embed.add_field("Do $meme for some funny memes!", f'page {index}/{limit}')
        result.append(embed)

    del pages
    await Pagination(client, message.channel,result)
Пример #14
0
async def color_(client, event, color: ('str', 'Beauty!')):
    """Shows the given color"""

    color = parse_color(color)
    if color is None:
        yield 'Could not recognize the color.'
        return

    yield

    embed = Embed(color=color)
    embed.add_field('hex', f'#{color:06X}', inline=True)
    embed.add_field('rgb',
                    f'{color>>16} r\n{(color>>8)&255} g\n{color&255} b',
                    inline=True)
    r, g, b = color.as_rgb_float_tuple
    embed.add_field('rgb%',
                    f'{r*100.0:0.2f}% r\n{g*100.0:0.2f}% g\n{b*100.0:0.2f}% b',
                    inline=True)
    h, s, v = rgb_to_hsv(r, g, b)
    embed.add_field('hsv%',
                    f'{h*100.0:0.2f}% h\n{s*100.0:0.2f}% s\n{v*100.0:0.2f}% v',
                    inline=True)
    y, i, q = rgb_to_yiq(r, g, b)
    embed.add_field('yiq%',
                    f'{y*100.0:0.2f}% y\n{i*100.0:0.2f}% i\n{q*100.0:0.2f}% q',
                    inline=True)

    embed.add_image('attachment://color.png')

    with ReuBytesIO() as buffer:
        image = PIL.new('RGB', (240, 30), color.as_rgb)
        image.save(buffer, 'png')
        buffer.seek(0)

        await client.interaction_followup_message_create(event,
                                                         embed=embed,
                                                         file=('color.png',
                                                               buffer))
Пример #15
0
def render_showcase(name, map_):
    result = []
    element_index = 0
    element_limit = len(map_)

    page_index = 1
    page_limit = (element_limit + 29) // 30

    field_text = []

    while True:
        if page_index > page_limit:
            break

        embed = Embed(name.capitalize(), '', KANAKO_COLOR)
        embed.add_footer(f'page {page_index} / {page_limit}')

        for _ in range(((element_limit % 30) + 9) //
                       10 if page_index == page_limit else 3):
            field_index_limit = element_index + 10
            if field_index_limit > element_limit:
                field_index_limit = element_limit

            while element_index < field_index_limit:
                element = map_[element_index]
                element_index += 1
                field_text.append(
                    f'{element_index}.: **{element[0]} - {element[1]}**')

            embed.add_field(f'{element_index-9} - {element_index}',
                            '\n'.join(field_text),
                            inline=True)
            field_text.clear()

        result.append(embed)
        page_index += 1

    return result
Пример #16
0
async def help(client, message):
    cmds = []
    for i in pdbot.events.message_create.commands:
        cmds.append(i)
    for y in os.listdir('./cmds/'):
        with open('./cmds/' + y, 'r') as f:
            x = json.load(f)
        for i in x:
            if i.lower() != 'help':
                cmds.append(i)
    pages = []
    part = []
    index = 0
    for element in cmds:
        if index == 16:
            pages.append('\n'.join(part))
            part.clear()
            index = 0
        part.append(f'**>>** {element}')
        index += 1

    pages.append('\n'.join(part))

    del part

    result = []

    limit = len(pages)
    index = 0
    while index < limit:
        embed = Embed('Commands:', color='029320', description=pages[index])
        index += 1
        embed.add_field("Do $meme for some funny memes!",
                        f'page {index}/{limit}')
        result.append(embed)

    del pages
    await Pagination(client, message.channel, result)
Пример #17
0
def HelpPages(client, message):
    cmds = []
    for i in client.events.message_create.commands:
        cmds.append(i)
    for y in listdir('cmds/'):
        with open('cmds/'+y,) as f:
            x = jload(f)
        for i in x:
            if i.lower() != 'help':
                cmds.append(i)
    cmds = sorted(cmds, key=str.lower) # Key positional argument is used to make sure uppercase commands don't take precedence.
    pages=[]
    part=[]
    index=0
    for element in cmds:
        if index==16:
            pages.append('\n'.join(part))
            part.clear()
            index=0
        part.append(f'**>>** {element}')
        index+=1

    pages.append('\n'.join(part))

    del part

    result=[]

    limit=len(pages)
    index=0
    while index<limit:
        embed=Embed('Commands:',color='029320',description=pages[index])
        index+=1
        embed.add_field("Do $meme for some funny memes!", f'page {index}/{limit}')
        result.append(embed)

    del pages
    return result
Пример #18
0
async def character(client, event,
        name: ('str', 'Who\'s?'),
            ):
    """Shows you the given Touhou character's portrait."""
    name_length = len(name)
    if name_length == 0:
        abort('Empty name was given.')
    
    if name_length > 10:
        name_length = 10
    
    diversity = 0.2+(10-name_length)*0.02
    
    matcheds = get_close_matches(name, TOUHOU_NAMES, n=1, cutoff=1.0-diversity)
    if matcheds:
        return TOUHOU_NAME_RELATIONS[matcheds[0]](client, event)
    else:
        embed = Embed('No match', color=BOORU_COLOR)
        matcheds = get_close_matches(name, TOUHOU_NAMES, n=10, cutoff=0.8-diversity)
        if matcheds:
            field_value_parts = []
            for index, matched in enumerate(matcheds, 1):
                field_value_parts.append(str(index))
                field_value_parts.append('.: **')
                field_value_parts.append(matched)
                field_value_parts.append('**')
                name = TOUHOU_NAME_RELATIONS[matched].title
                if matched != name:
                    field_value_parts.append(' [')
                    field_value_parts.append(name)
                    field_value_parts.append(']')
                
                field_value_parts.append('\n')
            
            del field_value_parts[-1]
            
            embed.add_field('Close matches:', ''.join(field_value_parts))
        return embed
Пример #19
0
async def welcome_screen_(client, event):
    """Shows the guild's welcome screen."""
    guild = event.guild
    if guild is None:
        abort('Guild only command.')

    if guild not in client.guild_profiles:
        abort('I must be in the guild to execute this command')

    yield

    welcome_screen = await client.welcome_screen_get(guild)
    if welcome_screen is None:
        yield Embed(
            description=f'**{guild.name}** *has no welcome screen enabled*.')
        return

    description = welcome_screen.description
    if (description is None):
        description = '*TOP THINGS TO DO HERE*'
    else:
        description = f'{welcome_screen.description}\n\n*TOP THINGS TO DO HERE*'

    embed = Embed(f'Welcome to **{guild.name}**', description)

    icon_url = guild.icon_url
    if (icon_url is not None):
        embed.add_thumbnail(icon_url)

    welcome_channels = welcome_screen.welcome_channels
    if (welcome_channels is not None):
        for welcome_channel in welcome_channels:
            embed.add_field(
                f'{welcome_channel.emoji:e} {welcome_channel.description}',
                f'#{welcome_channel.channel:d}')

    yield embed
Пример #20
0
 async def command(client, message, emoji:Emoji, *roles:'role'):
     permissions = message.channel.cached_permissions_for(client)
     if (not permissions.can_manage_emojis) or (not permissions.can_add_reactions):
         await client.message_create(message.channel,
             embed = Embed(description='I have no permissions to edit emojis, or to add reactions.'))
         return
     
     roles = sorted(roles)
     roles_ = emoji.roles
     
     embed = Embed().add_author(emoji.url, emoji.name)
     
     if (roles_ is None) or (not roles_):
         role_text = '*none*'
     else:
         role_text = ', '.join([role.mention for role in roles_])
     
     embed.add_field('Roles before:', role_text)
     
     if (not roles):
         role_text = '*none*'
     else:
         role_text = ', '.join([role.mention for role in roles])
     
     embed.add_field('Roles after:', role_text)
     
     message = await client.message_create(message.channel, embed=embed)
     for emoji_ in ROLE_EMOJI_EMOJIS:
         await client.reaction_add(message, emoji_)
     
     try:
         event = await wait_for_reaction(client, message, _role_emoji_emoji_checker(message.guild), 300.)
     except TimeoutError:
         emoji_ = ROLE_EMOJI_CANCEL
     else:
         emoji_ = event.emoji
     
     if message.channel.cached_permissions_for(client).can_manage_messages:
         try:
             await client.reaction_clear(message)
         except BaseException as err:
             if isinstance(err, ConnectionError):
                 # no internet
                 return
             
             if isinstance(err, DiscordException):
                 if err.code in (
                         ERROR_CODES.invalid_access, # client removed
                         ERROR_CODES.unknown_message, # message deleted
                         ERROR_CODES.invalid_permissions, # permissions changed meanwhile
                             ):
                     return
             
             raise
     
     if emoji_ is ROLE_EMOJI_OK:
         try:
             await client.emoji_edit(emoji, roles=roles)
         except DiscordException as err:
             footer = repr(err)
         else:
             footer = 'Emoji edited succesfully.'
     
     elif emoji_ is ROLE_EMOJI_CANCEL:
         footer = 'Emoji edit cancelled'
     
     else: #should not happen
         return
     
     embed.add_footer(footer)
     
     await client.message_edit(message, embed=embed)
Пример #21
0
 async def command(client, message):
     guild = message.channel.guild
     if (guild is None):
         return
     
     if not guild.cached_permissions_for(client).can_ban_users:
         await client.message_create(message.channel, embed = Embed(
             description = 'I have no permissions at the guild.',
             color=ADMINISTRATION_COLOR))
         return
     
     ban_data = await client.guild_bans(guild)
     
     if not ban_data:
         await client.message_create(message.channel, 'None')
         return
     
     embeds = []
     maintext = f'Guild bans for {guild.name} {guild.id}:'
     limit = len(ban_data)
     index = 0
 
     while True:
         field_count = 0
         embed_length = len(maintext)
         embed = Embed(title=maintext)
         embeds.append(embed)
         while True:
             user, reason = ban_data[index]
             if reason is None:
                 reason = 'Not defined.'
             name = f'{user:f} {user.id}'
             embed_length += len(reason)+len(name)
             if embed_length > 5900:
                 break
             embed.add_field(name,reason)
             field_count += 1
             if field_count == 25:
                 break
             index +=1
             if index == limit:
                 break
         if index == limit:
             break
     
     index = 0
     field_count = 0
     embed_ln = len(embeds)
     result = []
     while True:
         embed = embeds[index]
         index +=1
         embed.add_footer(f'Page: {index}/{embed_ln}. Bans {field_count+1}-{field_count+len(embed.fields)}/{limit}')
         field_count += len(embed.fields)
         
         result.append(embed)
         
         if index == embed_ln:
             break
     
     await Pagination(client, message.channel, result)
Пример #22
0
async def edit_(
    client,
    event,
    sticker_name: ('str', 'The sticker\'s name to delete', 'sticker'),
    new_name: (
        'str',
        'New name for the sticker',
    ) = None,
    new_emoji_value: (str, 'Emoji representation of the sticker.',
                      'new_emoji') = None,
    new_description: (str, 'Description for the sticker.') = None,
):
    """Edits the given sticker. (You must have emoji-council role)"""
    if not event.user.has_role(ROLE__NEKO_DUNGEON__EMOJI_MANAGER):
        abort(
            f'You must have {ROLE__NEKO_DUNGEON__EMOJI_MANAGER:m} role to invoke this command.'
        )

    sticker = event.guild.get_sticker_like(sticker_name)
    if (sticker is None):
        abort(f'No sticker matched the given name: {sticker_name!r}.')

    anything_to_edit = False

    if (new_name is not None):
        if (sticker.name != new_name):
            name_length = len(new_name)
            if (name_length < 2) or (name_length > 32):
                abort(
                    f'Sticker name\'s length can be in range [2:32], got {name_length!r}, {new_name!r}.'
                )

            anything_to_edit = True
        else:
            new_name = None

    if (new_emoji_value is not None):
        new_emoji = parse_emoji(new_emoji_value)

        if new_emoji is None:
            abort(f'{new_emoji_value} cannot be interpreted as an emoji.')

        if new_emoji.is_custom_emoji():
            abort(f'Only unicode can be used, got {new_emoji:e}')

        tags = sticker.tags
        if (tags is None) or (len(tags) != 1) or (next(iter(tags)) !=
                                                  new_emoji.name):
            anything_to_edit = True
        else:
            new_emoji = None
    else:
        new_emoji = None

    if (new_description is not None):
        description_length = len(new_description)
        if (description_length > 100):
            abort(
                f'Sticker description\'s length can be in range [0:100], got {description_length!r}, '
                f'{new_description!r}.')

        if (sticker.description != new_description):
            anything_to_edit = True
        else:
            new_description = None

    if not anything_to_edit:
        abort('No differences were provided.')

    embed = Embed('Confirmation',
                  f'Are you sure to edit {sticker.name!r} sticker?')

    if (new_name is not None):
        embed.add_field('Name', f'{sticker.name} -> {new_name}')

    if (new_emoji is not None):
        embed.add_field('Tags',
                        f'{", ".join(sticker.tags)} -> {new_emoji.name}')

    if (new_description is not None):
        embed.add_field('Description',
                        f'{sticker.description} -> {new_description}')

    message = yield InteractionResponse(embed=embed,
                                        components=STICKER_EDIT_COMPONENTS,
                                        allowed_mentions=None)

    try:
        component_interaction = await wait_for_component_interaction(
            message,
            timeout=300.0,
            check=partial_func(check_sticker_editor, event.user))

    except TimeoutError:
        embed.title = 'Timeout'
        embed.description = f'Sticker {sticker.name!r} was not edited.'

        # Edit the source message with the source interaction
        yield InteractionResponse(embed=embed,
                                  components=None,
                                  allowed_mentions=None,
                                  message=message)
        return

    if component_interaction.interaction == STICKER_EDIT_BUTTON_CANCEL:
        embed.title = 'Cancelled'
        embed.description = f'Sticker {sticker.name!r} was not edited.'

        # Edit the source message with the component interaction
        yield InteractionResponse(embed=embed,
                                  components=None,
                                  allowed_mentions=None,
                                  event=component_interaction)
        return

    # Acknowledge the event
    await client.interaction_component_acknowledge(component_interaction)

    kwargs = {}

    if (new_name is not None):
        kwargs['name'] = new_name

    if (new_emoji is not None):
        kwargs['emoji_representation'] = new_emoji

    if (new_description is not None):
        kwargs['description'] = new_description

    try:
        await client.sticker_guild_edit(sticker, **kwargs)
    except ConnectionError:
        # No internet, let it be
        return

    except DiscordException as err:
        if err.code == ERROR_CODES.unknown_sticker:
            failure = False
        else:
            failure = True
            embed.title = 'Failure'
            embed.description = repr(err)
    else:
        failure = False

    if not failure:
        embed.title = 'Success'
        embed.description = f'Sticker {sticker.name!r} has been successfully edited.'

    # Edit the source message
    yield InteractionResponse(embed=embed, message=message, components=None)
Пример #23
0
async def user_top(
    event,
    user: ('user', 'By who?') = None,
    count: (range(10, 61, 10), 'The maximal amount of emojis to show') = 30,
    months: (range(1, 13), 'The months to get') = 1,
):
    """List the most used stickers at ND by you or by the selected user."""
    if user is None:
        user = event.user

    async with DB_ENGINE.connect() as connector:
        response = await connector.execute(
            select([
                sticker_counter_model.sticker_id,
                alchemy_function.count(sticker_counter_model.sticker_id).label('total'),
            ]). \
            where(and_(
                sticker_counter_model.user_id == user.id,
                sticker_counter_model.timestamp > datetime.utcnow()-RELATIVE_MONTH*months,
            )). \
            limit(count). \
            group_by(sticker_counter_model.sticker_id). \
            order_by(desc('total'))
        )

        results = await response.fetchall()

    embed = Embed(
        f'Most used stickers by {user.full_name}',
        color=user.color_at(GUILD__NEKO_DUNGEON),
    ).add_thumbnail(user.avatar_url)

    if results:
        description_parts = []
        limit = len(results)
        index = 0
        start = 1

        while True:
            sticker_id, count = results[index]

            index += 1

            try:
                sticker = STICKERS[sticker_id]
            except KeyError:
                continue

            description_parts.append(str(index))
            description_parts.append('.: **')
            description_parts.append(str(count))
            description_parts.append('** x ')
            description_parts.append(sticker.name)

            if (not index % 10) or (index == limit):
                description = ''.join(description_parts)
                description_parts.clear()
                embed.add_field(f'{start} - {index}', description, inline=True)

                if (index == limit):
                    break

                start = index + 1
                continue

            description_parts.append('\n')
            continue
    else:
        embed.description = '*No recorded data.*'

    return embed
Пример #24
0
async def store_guild_data(client, guild):
    """
    This function stores the guild data
    
    first it stores the prefixes if they do not exist
    second they stores the member data if the data does not exist
    """
    DATABASE = My_Database.DATABASE
    
    embed = Embed(title = "Database Status", description = 'Storing Every Data')
    message = await client.message_create(BOT_LOGS, embed)
    
    #For the prefix
    with client.keep_typing(BOT_LOGS):
        has_bot_data = bool(await executor(client, DATABASE.child('MelonMintBots').get().val))
        if has_bot_data is None:
            
            bot_data = {
                config.MINT_ID:{'prefix':config.MINT_PREFIX},
                config.MELON_ID:{'prefix':config.MELON_PREFIX},
                config.MELON_MINT_ID:{'prefix':config.MELON_MINT_PREFIX}
            }
            
            await executor(client, DATABASE.child('MelonMintBots').set(bot_data).update)
            value_msg = f"Set to {f'<@{id}> is set to {prefix}' for id, prefix in bot_data.items()}"
        else:
            value_msg = "Prefix Unchanged"
    
    await client.message_edit(message, embed.add_field(name = "Prefix Status", value = value_msg))
    
    #For Users
    with client.keep_typing(BOT_LOGS):
        new_count = 0
        update_count = 0
        
        guild_users = message.guild.users.copy().values()
        member_list = await executor(client, DATABASE.child('members').shallow(). get().val)
        
        for user in guild_users:
            if user.is_bot:
                continue
            user_data = user.guild_profiles.get(guild)
                        
            if member_list is None or str(user.id) not in member_list: #just do it
                new_data = {
                    'joined_at':[str(user_data.joined_at)],
                    'left_at': [],
                    'name':[user.name],
                    'level':0,
                    'reputation':0,
                    'todo':[],
                    'roles': [x.id for x in user_data.roles] if user_data.roles else [] 
                    }
                new_count += 1
            
            else: #update stuff
                new_data = await executor(client, DATABASE.child('members').child(str(user.id)).get().val)
                    
                new_data['joined_at'].append(str(user_data.joined_at))
                new_data['name'].append(user.name)
                
                if new_data.get('roles'):
                    new_data['roles'].extend([x.id for x in user_data.roles] if user_data.roles else [])
                else:
                    new_data['roles'] = [x.id for x in user_data.roles] if user_data.roles else []
                
                for value in ['joined_at','name','roles']:
                    list(set(new_data[value]))
                                
                update_count += 1
            print(f'Added {new_count}/{len(guild.users)}\nUpdated {update_count}/{len(guild.users)}')
            await executor(client, DATABASE.child('members').child(str(user.id)).set(new_data).update)
        embed = embed.add_field(name = "Member Status", value = f'Added {new_count}/{len(guild.users)}\nUpdated {update_count}/{len(guild.users)}')
        await client.message_edit(message, embed)
        await client.message_create(message.channel, 'done')
Пример #25
0
    async def command(client, message, user: Converter(
        'user',
        ConverterFlag.user_default.update_by_keys(everywhere=True,
                                                  profile=True),
        default_code='message.author')):
        guild = message.guild

        embed = Embed(user.full_name)
        embed.add_field(
            'User Information',
            f'Created: {elapsed_time(user.created_at)} ago\n'
            f'Profile: {user:m}\n'
            f'ID: {user.id}')

        if guild is None:
            profile = None
        else:
            profile = user.guild_profiles.get(guild)

        if profile is None:
            if user.avatar_type is ICON_TYPE_NONE:
                color = user.default_avatar.color
            else:
                color = user.avatar_hash & 0xFFFFFF
            embed.color = color

        else:
            embed.color = user.color_at(guild)
            roles = profile.roles
            if roles is None:
                roles = '*none*'
            else:
                roles.sort()
                roles = ', '.join(role.mention for role in reversed(roles))

            text = []
            if profile.nick is not None:
                text.append(f'Nick: {profile.nick}')

            if profile.joined_at is None:
                await client.guild_user_get(user.id)

            text.append(f'Joined: {elapsed_time(profile.joined_at)} ago')

            boosts_since = profile.boosts_since
            if (boosts_since is not None):
                text.append(f'Booster since: {elapsed_time(boosts_since)}')

            text.append(f'Roles: {roles}')
            embed.add_field('In guild profile', '\n'.join(text))

        embed.add_thumbnail(user.avatar_url_as(size=128))

        if user.activity is not ActivityUnknown or user.status is not Status.offline:
            text = []

            if user.status is Status.offline:
                text.append('Status : offline\n')
            elif len(user.statuses) == 1:
                for platform, status in user.statuses.items():
                    text.append(f'Status : {status} ({platform})\n')
            else:
                text.append('Statuses :\n')
                for platform, status in user.statuses.items():
                    text.append(f'**>>** {status} ({platform})\n')

            if user.activity is ActivityUnknown:
                text.append('Activity : *unknown*\n')
            elif len(user.activities) == 1:
                text.append('Activity : ')
                add_activity(text, user.activities[0])
            else:
                text.append('Activities : \n')
                for index, activity in enumerate(user.activities, 1):
                    text.append(f'{index}.: ')
                    add_activity(text, activity)

            embed.add_field('Status and Activity', ''.join(text))
        await client.message_create(message.channel, embed=embed)
Пример #26
0
async def role_(
        client,
        event,
        role: ('role', 'Select the role to show information of.'),
):
    """Shows the information about a role."""
    if role.partial:
        abort('I must be in the guild, where the role is.')

    embed = Embed(f'Role information for: {role.name}', color=role.color)
    embed.add_field('Position', str(role.position), inline=True)
    embed.add_field('Id', str(role.id), inline=True)

    embed.add_field('Separated',
                    'true' if role.separated else 'false',
                    inline=True)
    embed.add_field('Mentionable',
                    'true' if role.mentionable else 'false',
                    inline=True)

    manager_type = role.manager_type
    if manager_type is RoleManagerType.none:
        managed_description = 'false'
    else:
        if manager_type is RoleManagerType.unset:
            await client.sync_roles(role.guild)
            manager_type = role.manager_type

        if manager_type is RoleManagerType.bot:
            managed_description = f'Special role for bot: {role.manager:f}'
        elif manager_type is RoleManagerType.booster:
            managed_description = 'Role for the boosters of the guild.'
        elif manager_type is RoleManagerType.integration:
            managed_description = f'Special role for integration: {role.manager.name}'
        elif manager_type is RoleManagerType.unknown:
            managed_description = 'Some new things.. Never heard of them.'
        else:
            managed_description = 'I have no clue.'

    embed.add_field('Managed', managed_description, inline=True)

    color = role.color
    embed.add_field('color', f'html: {color.as_html}\n'
                    f'rgb: {color.as_rgb}\n'
                    f'int: {color:d}',
                    inline=True)

    created_at = role.created_at
    embed.add_field('Created at', f'{created_at:{DATETIME_FORMAT_CODE}}\n'
                    f'{elapsed_time(created_at)} ago',
                    inline=True)

    return embed
Пример #27
0
async def bans(client, event):
    """Lists the guild's bans."""
    guild = event.guild
    if guild is None:
        abort('Guild only command')

    if guild not in client.guild_profiles:
        abort('I must be in the guild to execute the command.')

    if not event.user_permissions.can_ban_users:
        abort('You must have `ban users` permission to invoke this command.')

    if not guild.cached_permissions_for(client).can_ban_users:
        abort(
            'I must have `ban users` permission invite to execute this command.'
        )

    yield

    ban_data = await client.guild_ban_get_all(guild)

    embeds = []
    main_text = f'Guild bans for {guild.name} {guild.id}:'
    limit = len(ban_data)
    if limit:
        index = 0

        while True:
            field_count = 0
            embed_length = len(main_text)
            embed = Embed(main_text)
            embeds.append(embed)

            while True:
                user, reason = ban_data[index]
                if reason is None:
                    reason = 'Not defined.'
                name = f'{user:f} {user.id}'
                embed_length += len(reason) + len(name)
                if embed_length > 5900:
                    break
                embed.add_field(name, reason)
                field_count += 1
                if field_count == 25:
                    break
                index += 1
                if index == limit:
                    break
            if index == limit:
                break
    else:
        embed = Embed(main_text, '*none*')
        embeds.append(embed)

    index = 0
    field_count = 0
    embed_ln = len(embeds)
    result = []
    while True:
        embed = embeds[index]
        index += 1
        embed.add_footer(
            f'Page: {index}/{embed_ln}. Bans {field_count+1}-{field_count+len(embed.fields)}/{limit}'
        )
        field_count += len(embed.fields)

        result.append(embed)

        if index == embed_ln:
            break

    await Pagination(client, event, result, check=bans_pagination_check)
Пример #28
0
async def user_(
    client,
    event,
    user: ('user', '*spy?*') = None,
):
    """Shows some information about your or about the selected user."""

    if user is None:
        user = event.user

    guild = event.guild

    embed = Embed(user.full_name)
    created_at = user.created_at
    embed.add_field(
        'User Information',
        f'Created: {created_at:{DATETIME_FORMAT_CODE}} [*{elapsed_time(created_at)} ago*]\n'
        f'Profile: {user:m}\n'
        f'ID: {user.id}')

    if guild is None:
        profile = None
    else:
        profile = user.guild_profiles.get(guild, None)

    if profile is None:
        if user.avatar_type is ICON_TYPE_NONE:
            color = user.default_avatar.color
        else:
            color = user.avatar_hash & 0xFFFFFF
        embed.color = color

    else:
        embed.color = user.color_at(guild)
        roles = profile.roles
        if roles is None:
            roles = '*none*'
        else:
            roles.sort()
            roles = ', '.join(role.mention for role in reversed(roles))

        text = []
        if profile.nick is not None:
            text.append(f'Nick: {profile.nick}')

        if profile.joined_at is None:
            await client.guild_user_get(user.id)

        # Joined at can be `None` if the user is in lurking mode.
        joined_at = profile.joined_at
        if joined_at is not None:
            text.append(
                f'Joined: {joined_at:{DATETIME_FORMAT_CODE}} [*{elapsed_time(joined_at)} ago*]'
            )

        boosts_since = profile.boosts_since
        if (boosts_since is not None):
            text.append(
                f'Booster since: {boosts_since:{DATETIME_FORMAT_CODE}} [*{elapsed_time(boosts_since)}*]'
            )

        text.append(f'Roles: {roles}')
        embed.add_field('In guild profile', '\n'.join(text))

    embed.add_thumbnail(user.avatar_url_as(size=128))

    return embed
Пример #29
0
    def create_page_0(self):
        user_count = len(self.source.users)
        win_counts = [0 for _ in range(user_count)]
        lose_counts = win_counts.copy()
        win_firsts = win_counts.copy()
        lose_firsts = win_counts.copy()
        win_times = [[] for _ in range(user_count)]
        lose_times = [[] for _ in range(user_count)]

        for element in self.source.history:
            answer = element.answer
            answers = element.answers
            first_time = CIRCLE_TIME
            first_index = 0
            first_won = True
            for index in range(user_count):
                value, time = answers[index]
                if value == answer:
                    win_counts[index] += 1
                    win_times[index].append(time)
                    if time < first_time:
                        first_time = time
                        first_index = index
                        first_won = True
                else:
                    lose_counts[index] += 1
                    lose_times[index].append(time)
                    if time < first_time:
                        first_time = time
                        first_index = index
                        first_won = False

            if first_time != CIRCLE_TIME:
                if first_won:
                    win_firsts[first_index] += 1
                else:
                    lose_firsts[first_index] += 1

        win_medians = [
            value[len(value) // 2] if value else CIRCLE_TIME
            for value in win_times
        ]
        lose_medians = [
            value[len(value) // 2] if value else CIRCLE_TIME
            for value in lose_times
        ]

        embed = Embed('Statistics', color=KANAKO_COLOR)

        for index, user in enumerate(self.source.users):
            win_count = win_counts[index]
            lose_count = lose_counts[index]
            win_median = win_medians[index]
            lose_median = lose_medians[index]
            win_first = win_firsts[index]
            lose_first = lose_firsts[index]

            total = float(win_count)
            total += (((2**.5) - 1.) -
                      ((((CIRCLE_TIME + win_median) / CIRCLE_TIME)**.5) -
                       1.)) * win_count
            total += win_first / 5.
            total -= (((2**.5) - 1.) -
                      ((((CIRCLE_TIME + lose_median) / CIRCLE_TIME)**.5) -
                       1.)) * lose_count * 2.
            total -= lose_first / 2.5

            embed.add_field(
                f'{user:f} :', f'Correct answers : {win_count}\n'
                f'Bad answers : {lose_count}\n'
                f'Good answer time median : {win_median:.2f} s\n'
                f'Bad answer time median : {lose_median:.2f} s\n'
                f'Answered first: {win_first} GOOD / {lose_first} BAD\n'
                f'Rated : {total:.2f}')

        embed.add_footer(f'Page 1 /  {len(self.cache)}')

        self.cache[0] = embed
Пример #30
0
async def emoji_role(
    client,
    event,
    emoji: ('str', 'Select the emoji to bind to roles.'),
    role_1: ('role', 'Select a role.') = None,
    role_2: ('role', 'Double role!') = None,
    role_3: ('role', 'Triple role!') = None,
    role_4: ('role', 'Quadra role!') = None,
    role_5: ('role', 'Penta role!') = None,
    role_6: ('role', 'Epic!') = None,
    role_7: ('role', 'Legendary!') = None,
    role_8: ('role', 'Mythical!') = None,
    role_9: ('role', 'Lunatic!') = None,
):
    """Binds the given emoji to the selected roles. You must have administrator permission."""
    guild = event.guild
    if guild is None:
        abort('Guild only command.')

    if guild not in client.guild_profiles:
        abort('I must be in the guild to do this.')

    if not event.user_permissions.can_ban_users:
        abort('You must have ban users permission to use this command.')

    permissions = event.channel.cached_permissions_for(client)
    if (not permissions.can_manage_emojis_and_stickers) or (
            not permissions.can_add_reactions):
        abort(
            f'{client.name_at(guild)} requires manage emojis and add reactions permissions for this command.'
        )

    emoji = parse_emoji(emoji)
    if emoji is None:
        abort('That\'s not an emoji.')

    if emoji.is_unicode_emoji():
        abort('Cannot edit unicode emojis.')

    emoji_guild = emoji.guild
    if (emoji_guild is None) or (emoji_guild is not guild):
        abort('Wont edit emojis from an other guild.')

    roles = set()
    for role in role_1, role_2, role_3, role_4, role_5, role_6, role_7, role_8, role_9:
        if role is None:
            continue

        if role.guild is guild:
            roles.add(role)
            continue

        abort(f'Role {role.name}, [{role.id}] is bound to an other guild.')

    roles = sorted(roles)
    roles_ = emoji.roles

    embed = Embed(f'Edit {emoji.name}\'s roles').add_thumbnail(emoji.url)

    if (roles_ is None) or (not roles_):
        role_text = '*none*'
    else:
        role_text = ', '.join([role.mention for role in roles_])

    embed.add_field('Before:', role_text)

    if (not roles):
        role_text = '*none*'
    else:
        role_text = ', '.join([role.mention for role in roles])

    embed.add_field('After:', role_text)

    message = yield InteractionResponse(embed=embed,
                                        components=EMOJI_ROLE_COMPONENTS)

    try:
        component_interaction = await wait_for_component_interaction(
            message, timeout=300.0, check=role_emoji_checker)

    except TimeoutError:
        component_interaction = None
        cancelled = True
    else:
        if component_interaction.interaction == EMOJI_ROLE_BUTTON_CANCEL:
            cancelled = True
        else:
            cancelled = False

    if cancelled:
        description = 'Emoji edit cancelled.'
    else:
        try:
            await client.emoji_edit(emoji, roles=roles)
        except DiscordException as err:
            description = repr(err)
        else:
            description = 'Emoji edited successfully.'

    embed = Embed(f'Edit {emoji.name}\'s roles',
                  description).add_thumbnail(emoji.url)
    yield InteractionResponse(embed=embed,
                              components=None,
                              message=message,
                              event=component_interaction)