Beispiel #1
0
async def role_list(bot, context):
    """Lists the available roles for self-assignment."""
    if context.arguments[0]:  # List members that have this role
        role = context.arguments[0]
        if role.is_default():
            raise CBException("Cannot list members with the @everyone role.")
        if not role.members:
            raise CBException("No members have the role {}.".format(role.mention))
        elif len(role.members) > 80:
            name_file = discord.File(
                utilities.get_text_as_file('\n'.join(str(it) for it in role.members)),
                filename='members.txt')
            embed = discord.Embed(
                description='{} members have this role.'.format(len(role.members)))
            return Response(file=name_file, embed=embed)
        else:
            plural = len(role.members) > 1
            return Response(embed=discord.Embed(
                title='{} member{} {} this role:'.format(
                    len(role.members), 's' if plural else '', 'have' if plural else 'has'),
                description=', '.join(it.mention for it in role.members)))

    else:  # List self-assignable roles
        available_roles = _check_roles(bot, context.guild)
        if not available_roles:
            raise CBException("There are no self-assignable roles available.")

        embed = discord.Embed(
            title='Self-assignable roles:',
            description='\n'.join(it.mention for it in available_roles))
        embed.set_footer(text='To join a role, use {}role join'.format(
            utilities.get_invoker(bot, guild=context.guild)))
        return Response(embed=embed)
Beispiel #2
0
async def get_response(bot, context):
    if 'discrank.py' not in bot.plugins:
        raise CBException("Discrank plugin not detected.")
    discrank_plugin = bot.plugins['discrank.py']
    champions, spells = discrank_plugin.CHAMPIONS, discrank_plugin.SPELLS

    chunks = [bot.get_guild(it).emojis for it in configurations.get(bot, __name__, 'guilds')]
    emojis = [it for chunk in chunks for it in chunk]

    final = {
        'champions': {'id': {}, 'name': {}},
        'spells': {'id': {}, 'name': {}},
        'bdt': {'blue': {}, 'red': {}}
    }
    for emoji in emojis:

        if emoji.name.startswith('Champion'):
            clean_name = emoji.name.split('_')[1].lower()
            if clean_name not in champions:
                raise CBException("Champion {} not found.".format(clean_name))
            item_id = champions[clean_name]['id']
            final['champions']['id'][str(item_id)] = str(emoji)
            final['champions']['name'][clean_name] = str(emoji)

        elif emoji.name.startswith('Spell'):
            clean_name = emoji.name.split('_')[1].lower()
            if clean_name not in spells:
                raise CBException("Spell {} not found.".format(clean_name))
            item_id = spells[clean_name]['id']
            final['spells']['id'][str(item_id)] = str(emoji)
            final['spells']['name'][clean_name] = str(emoji)

        elif emoji.name.startswith(('Red', 'Blue')):
            color, name = emoji.name.split('_')
            final['bdt'][color.lower()][name.lower()] = str(emoji)

        else:
            raise CBException("Invalid emoji detected: {}".format(emoji.name))

    final_json = json.dumps(final, sort_keys=True, indent=4)
    json_file = utilities.get_text_as_file(final_json)

    file_url = await utilities.upload_to_discord(
        bot, json_file, filename='lol_emojis.json', close=True)
    embed = discord.Embed(
        description='[Click here to download]({})'.format(file_url),
        colour=discord.Colour(0x4CAF50),
        timestamp=datetime.datetime.utcnow())
    embed.set_footer(text="Updated")

    try:
        update_channel = bot.get_channel(configurations.get(bot, __name__, 'update_channel'))
        message_id = configurations.get(bot, __name__, 'update_message')
        update_message = await update_channel.fetch_message(message_id)
        await update_message.edit(content='', embed=embed)
    except Exception as e:
        raise CBException("Failed to edit the update message.", e=e)

    return Response(content="Updated!")
Beispiel #3
0
async def list_text(bot, context):
    list_lines = []
    for text_type in TYPE_NAMES:
        list_lines.append('\n\n' + text_type)
        cursor = data.db_select(bot, from_arg='txyz_' + text_type)
        for key, value in cursor.fetchall():
            list_lines.append('\t{}: {}'.format(key, value))
    text_file = utilities.get_text_as_file('\n'.join(list_lines))
    discord_file = discord.File(text_file, 'txyz_list.txt')
    return Response(content='Table contents:', file=discord_file)
Beispiel #4
0
async def list_text(bot, context):
    list_lines = []
    for text_type in TYPE_NAMES:
        list_lines.append('\n\n' + text_type)
        cursor = data.db_select(bot, from_arg='txyz_' + text_type)
        for key, value in cursor.fetchall():
            list_lines.append('\t{}: {}'.format(key, value))
    text_file = utilities.get_text_as_file('\n'.join(list_lines))
    discord_file = discord.File(text_file, 'txyz_list.txt')
    return Response(content='Table contents:', file=discord_file)
Beispiel #5
0
async def _upload_session_data(bot, channel, voice_channel, webhook, tag_dictionary):
    """Uploads the tag dictionary and returns the session code."""
    tag_data = utilities.get_text_as_file(json.dumps({
        'version': DATA_VERSION,
        'bot_id': str(bot.user.id),
        'guild': str(channel.guild.id),
        'guild_name': channel.guild.name,
        'channel': str(channel.id),
        'channel_name': channel.name,
        'voice_channel': str(voice_channel.id),
        'voice_channel_name': voice_channel.name,
        'webhook': [str(webhook.id), webhook.token],
        'tags': tag_dictionary
    }))
    url = await utilities.upload_to_discord(bot, tag_data, filename='remote_data', close=True)
    url_segments = [it[::-1] for it in url[::-1].split('/')[2:0:-1]]
    return '{}:{}'.format(*url_segments)
Beispiel #6
0
async def _create_session(bot, owner, editing=None):
    """Creates a session for character creation or editing"""
    webhook = await DATA_CHANNEL.create_webhook(name='ready:{}'.format(owner.id))

    # Upload data as a single file
    cursor = data.db_select(
        bot, from_arg='characters', where_arg='owner_id=%s', input_args=[owner.id])
    characters = cursor.fetchall() if cursor else []
    create_data = utilities.get_text_as_file(json.dumps({
        "version": DATA_VERSION,
        "webhook": [str(webhook.id), webhook.token],
        "existing_names": list(character.clean_name for character in characters),
        "editing": editing
    }))
    url = await utilities.upload_to_discord(bot, create_data, filename='data', close=True)
    url_segments = [it[::-1] for it in url[::-1].split('/')[2:0:-1]]  # sorry
    session_code = '{}:{}'.format(*url_segments)

    # Track webhook usage
    data.add(bot, __name__, 'tracker', webhook, user_id=owner.id, volatile=True)
    data.add(bot, __name__, 'owner', owner, user_id=webhook.id, volatile=True)
    data.add(bot, __name__, 'stage', 0, user_id=webhook.id, volatile=True)

    # Add webhook ID to global IDs
    global DATA_CHANNEL_WEBHOOK_IDS
    DATA_CHANNEL_WEBHOOK_IDS.append(webhook.id)

    # Send the owner the link
    embed = discord.Embed(
        title='Click here to access the character creator',
        url='https://jkchen2.github.io/character-template/#{}'.format(session_code),
        description='Your session code is:\n`{}`'.format(session_code))
    await owner.send(embed=embed)

    # Schedule a session timeout
    utilities.schedule(
        bot, __name__, time.time() + 7200, _session_timeout_notify,
        search=str(webhook.id), destination='u{}'.format(owner.id),
        info='Character creator session timeout')

    return session_code
Beispiel #7
0
async def get_response(bot, context):
    if 'discrank.py' not in bot.plugins:
        raise CBException("Discrank plugin not detected.")
    discrank_plugin = bot.plugins['discrank.py']
    champions, spells = discrank_plugin.CHAMPIONS, discrank_plugin.SPELLS

    chunks = [
        bot.get_guild(it).emojis
        for it in configurations.get(bot, __name__, 'guilds')
    ]
    emojis = [it for chunk in chunks for it in chunk]

    final = {
        'champions': {
            'id': {},
            'name': {}
        },
        'spells': {
            'id': {},
            'name': {}
        },
        'bdt': {
            'blue': {},
            'red': {}
        }
    }
    for emoji in emojis:

        if emoji.name.startswith('Champion'):
            clean_name = emoji.name.split('_')[1].lower()
            if clean_name not in champions:
                raise CBException("Champion {} not found.".format(clean_name))
            item_id = champions[clean_name]['id']
            final['champions']['id'][str(item_id)] = str(emoji)
            final['champions']['name'][clean_name] = str(emoji)

        elif emoji.name.startswith('Spell'):
            clean_name = emoji.name.split('_')[1].lower()
            if clean_name not in spells:
                raise CBException("Spell {} not found.".format(clean_name))
            item_id = spells[clean_name]['id']
            final['spells']['id'][str(item_id)] = str(emoji)
            final['spells']['name'][clean_name] = str(emoji)

        elif emoji.name.startswith(('Red', 'Blue')):
            color, name = emoji.name.split('_')
            final['bdt'][color.lower()][name.lower()] = str(emoji)

        else:
            raise CBException("Invalid emoji detected: {}".format(emoji.name))

    final_json = json.dumps(final, sort_keys=True, indent=4)
    json_file = utilities.get_text_as_file(final_json)

    file_url = await utilities.upload_to_discord(bot,
                                                 json_file,
                                                 filename='lol_emojis.json',
                                                 close=True)
    embed = discord.Embed(
        description='[Click here to download]({})'.format(file_url),
        colour=discord.Colour(0x4CAF50),
        timestamp=datetime.datetime.utcnow())
    embed.set_footer(text="Updated")

    try:
        update_channel = bot.get_channel(
            configurations.get(bot, __name__, 'update_channel'))
        message_id = configurations.get(bot, __name__, 'update_message')
        update_message = await update_channel.get_message(message_id)
        await update_message.edit(content='', embed=embed)
    except Exception as e:
        raise CBException("Failed to edit the update message.", e=e)

    return Response(content="Updated!")