예제 #1
0
def get_botadmin_role(ctx):
    role_id = sql.guild_get_by_id(ctx.guild.id).bot_admin
    r = dget(ctx.guild.roles, id=role_id)
    if role_id and not r:
        sql.guild_update(ctx.guild.id, bot_admin=None)
        return None
    return r
예제 #2
0
def get_templateadder_role(ctx):
    role_id = sql.guild_get_by_id(ctx.guild.id).template_adder
    r = dget(ctx.guild.roles, id=role_id)
    if role_id and not r:
        sql.guild_update(ctx.guild.id, template_adder=None)
        return None
    return r
예제 #3
0
    async def factioninfo(self, ctx, other=None):
        g = sql.guild_get_by_faction_name_or_alias(other) if other else sql.guild_get_by_id(ctx.guild.id)
        if not g:
            await ctx.send(ctx.s("error.faction_not_found"))
            return
        if not g.faction_name:
            await ctx.send(ctx.s("faction.not_a_faction_yet"))
            return

        templates = sql.template_get_all_public_by_guild_id(g.id)
        canvas_list = set()
        for t in templates:
            canvas_list.add(t.canvas)

        canvases_pretty = []
        for c in canvas_list:
            canvases_pretty.append(canvases.pretty_print[c])
        canvases_pretty.sort()
        canvas_list = '\n'.join(canvases_pretty)

        e = discord.Embed(color=g.faction_color)
        if canvas_list:
            e.add_field(name=ctx.s("bot.canvases"), value='\n'.join(canvases_pretty))
        if g.faction_invite:
            icon_url = self.bot.get_guild(g.id).icon_url
            e.set_author(name=g.faction_name, url=g.faction_invite, icon_url=icon_url)
        else:
            e.set_author(name=g.faction_name)
        e.description = g.faction_desc if g.faction_desc else ""
        if g.faction_alias:
            e.description = "**{}:** {}\n".format(ctx.s("bot.alias"), g.faction_alias) + e.description
        if g.faction_emblem:
            e.set_thumbnail(url=g.faction_emblem)

        await ctx.send(embed=e)
예제 #4
0
 async def alertchannel(self, ctx):
     channel = dget(ctx.guild.channels,
                    id=sql.guild_get_by_id(ctx.guild.id).alert_channel)
     if channel:
         await ctx.send("Alert channel is currently set to {0}.".format(
             channel.mention))
     else:
         await ctx.send("No alert channel has been set.")
 async def alertchannel(self, ctx):
     channel = dget(ctx.guild.channels,
                    id=sql.guild_get_by_id(ctx.guild.id).alert_channel)
     if channel:
         await ctx.send(
             ctx.s("configuration.alert_channel_current").format(
                 channel.mention))
     else:
         await ctx.send(ctx.s("configuration.alert_channel_none"))
예제 #6
0
 async def faction_emblem(self, ctx):
     if not sql.guild_is_faction(ctx.guild.id):
         await ctx.send(ctx.s("faction.must_be_a_faction"))
         return
     if not ctx.invoked_subcommand or ctx.invoked_subcommand.name == "emblem":
         emblem = sql.guild_get_by_id(ctx.guild.id).faction_emblem
         if emblem:
             await ctx.send(emblem)
         else:
             await ctx.send(ctx.s("faction.no_emblem"))
예제 #7
0
 async def faction_invite(self, ctx):
     if not sql.guild_is_faction(ctx.guild.id):
         await ctx.send(ctx.s("faction.must_be_a_faction"))
         return
     if not ctx.invoked_subcommand or ctx.invoked_subcommand.name == "invite":
         invite = sql.guild_get_by_id(ctx.guild.id).faction_invite
         if invite:
             await ctx.send(invite)
         else:
             await ctx.send(ctx.s("faction.no_invite"))
예제 #8
0
 async def faction_alias(self, ctx):
     if not sql.guild_is_faction(ctx.guild.id):
         await ctx.send(ctx.s("faction.must_be_a_faction"))
         return
     if not ctx.invoked_subcommand or ctx.invoked_subcommand.name == "alias":
         alias = sql.guild_get_by_id(ctx.guild.id).faction_alias
         if alias:
             await ctx.send(alias)
         else:
             await ctx.send(ctx.s("faction.no_alias"))
예제 #9
0
 async def faction_desc(self, ctx):
     if not sql.guild_is_faction(ctx.guild.id):
         await ctx.send(ctx.s("faction.must_be_a_faction"))
         return
     if not ctx.invoked_subcommand or ctx.invoked_subcommand.name == "desc":
         desc = sql.guild_get_by_id(ctx.guild.id).faction_desc
         if desc:
             await ctx.send(desc)
         else:
             await ctx.send(ctx.s("faction.no_description"))
예제 #10
0
 async def faction_color(self, ctx):
     if not sql.guild_is_faction(ctx.guild.id):
         await ctx.send(ctx.s("faction.must_be_a_faction"))
         return
     if not ctx.invoked_subcommand or ctx.invoked_subcommand.name == "color":
         color = sql.guild_get_by_id(ctx.guild.id).faction_color
         img = Image.new('RGB', (32, 32), color)
         with io.BytesIO() as bio:
             img.save(bio, format="PNG")
             bio.seek(0)
             f = discord.File(bio, "color.png")
             await ctx.send('0x{0:06X}'.format(color), file=f)
예제 #11
0
    async def template_info(self, ctx, *args):
        # Order Parsing
        try:
            name = args[0]
        except TypeError:
            await ctx.send("Error: no arguments were provided.")
            return

        if re.match("-\D+", name) != None:
            name = args[-1]
            args = args[:-1]
        else:
            args = args[1:]

        # Argument Parsing
        parser = GlimmerArgumentParser(ctx)
        parser.add_argument("-r", "--raw", action="store_true")
        parser.add_argument("-f",
                            "--faction",
                            default=None,
                            action=FactionAction)
        parser.add_argument("-z", "--zoom", default=1)
        try:
            args = vars(parser.parse_args(args))
        except TypeError:
            return

        image_only = args["raw"]
        f = args["faction"]
        try:
            gid, faction = f.id, f
        except AttributeError:
            gid, faction = ctx.guild.id, sql.guild_get_by_id(ctx.guild.id)
        zoom = args["zoom"]

        t = sql.template_get_by_name(gid, name)
        if not t:
            raise TemplateNotFoundError(gid, name)

        if image_only:
            try:
                if type(zoom) is not int:
                    if zoom.startswith("#"):
                        zoom = zoom[1:]
                    zoom = int(zoom)
            except ValueError:
                zoom = 1
            max_zoom = int(math.sqrt(4000000 // (t.width * t.height)))
            zoom = max(1, min(zoom, max_zoom))

            img = render.zoom(await http.get_template(t.url, t.name), zoom)

            with io.BytesIO() as bio:
                img.save(bio, format="PNG")
                bio.seek(0)
                f = discord.File(bio, t.name + ".png")
                await ctx.send(file=f)
            return

        canvas_name = canvases.pretty_print[t.canvas]
        coords = "{}, {}".format(t.x, t.y)
        dimensions = "{} x {}".format(t.width, t.height)
        size = t.size
        visibility = ctx.s("bot.private") if bool(
            t.private) else ctx.s("bot.public")
        owner = self.bot.get_user(t.owner_id)
        if owner is None:
            added_by = ctx.s("error.account_deleted")
        else:
            added_by = owner.name + "#" + owner.discriminator
        date_added = datetime.date.fromtimestamp(
            t.date_created).strftime("%d %b, %Y")
        date_modified = datetime.date.fromtimestamp(
            t.date_updated).strftime("%d %b, %Y")
        color = faction.faction_color
        description = "[__{}__]({})".format(
            ctx.s("template.link_to_canvas"),
            canvases.url_templates[t.canvas].format(*t.center()))

        if size == 0:
            t.size = await render.calculate_size(await http.get_template(
                t.url, t.name))
            sql.template_update(t)

        e = discord.Embed(title=t.name, color=color, description=description) \
            .set_image(url=t.url) \
            .add_field(name=ctx.s("bot.canvas"), value=canvas_name, inline=True) \
            .add_field(name=ctx.s("bot.coordinates"), value=coords, inline=True) \
            .add_field(name=ctx.s("bot.dimensions"), value=dimensions, inline=True) \
            .add_field(name=ctx.s("bot.size"), value=size, inline=True) \
            .add_field(name=ctx.s("bot.visibility"), value=visibility, inline=True) \
            .add_field(name=ctx.s("bot.added_by"), value=added_by, inline=True) \
            .add_field(name=ctx.s("bot.date_added"), value=date_added, inline=True) \
            .add_field(name=ctx.s("bot.date_modified"), value=date_modified, inline=True)

        if faction.id != ctx.guild.id and faction.faction_name:
            e = e.set_author(name=faction.faction_name,
                             icon_url=faction.faction_emblem
                             or discord.Embed.Empty)

        await ctx.send(embed=e)
예제 #12
0
def is_template_admin(ctx):
    role_id = sql.guild_get_by_id(ctx.guild.id).template_admin
    r = dget(ctx.author.roles, id=role_id)
    return bool(r)
예제 #13
0
async def on_ready():
    log.info("Starting Starlight Glimmer v{}!".format(VERSION))
    if sql.version_get() is None:
        sql.version_init(VERSION)
        is_new_version = False
    else:
        old_version = sql.version_get()
        is_new_version = old_version != VERSION and old_version is not None
        if is_new_version:
            log.info("Database is a previous version. Updating...")
            sql.version_update(VERSION)
            if old_version < 1.6 <= VERSION:
                # Fix legacy templates not having a size
                for t in sql.template_get_all():
                    try:
                        t.size = await render.calculate_size(
                            await http.get_template(t.url))
                        sql.template_update(t)
                    except errors.TemplateHttpError:
                        log.error(
                            "Error retrieving template {0.name}. Skipping...".
                            format(t))

    log.info("Loading extensions...")
    for extension in extensions:
        try:
            bot.load_extension(extension)
        except Exception as e:
            log.error("Failed to load extension {}\n{}: {}".format(
                extension,
                type(e).__name__, e))

    log.info("Performing guilds check...")
    for g in bot.guilds:
        log.info("'{0.name}' (ID: {0.id})".format(g))
        db_g = sql.guild_get_by_id(g.id)
        if db_g:
            prefix = db_g.prefix if db_g.prefix else cfg.prefix
            if g.name != db_g.name:
                await ch_log.log(
                    "Guild **{1}** is now known as **{0.name}** `(ID:{0.id})`".
                    format(g, db_g.name))
                sql.guild_update(g.id, name=g.name)
            if is_new_version:
                ch = next(
                    (x for x in g.channels if x.id == db_g.alert_channel),
                    None)
                if ch:
                    data = await http.get_changelog(VERSION)
                    if data:
                        e = discord.Embed(title=data['name'], url=data['url'], color=13594340,
                                          description=data['body']) \
                            .set_author(name=data['author']['login']) \
                            .set_thumbnail(url=data['author']['avatar_url']) \
                            .set_footer(text="Released " + data['published_at'])
                        await ch.send(GlimContext.get_from_guild(
                            g, "bot.update").format(VERSION, prefix),
                                      embed=e)
                    else:
                        await ch.send(
                            GlimContext.get_from_guild(
                                g, "bot.update_no_changelog").format(
                                    VERSION, prefix))
                    log.info("- Sent update message")
                else:
                    log.info(
                        "- Could not send update message: alert channel not found."
                    )
        else:
            j = g.me.joined_at
            await ch_log.log("Joined guild **{0.name}** (ID: `{0.id}`)".format(
                g, j.isoformat(' ')))
            log.info(
                "Joined guild '{0.name}' (ID: {0.id}) between sessions at {1}".
                format(g, j.timestamp()))
            sql.guild_add(g.id, g.name, int(j.timestamp()))
            await print_welcome_message(g)

    db_guilds = sql.guild_get_all()
    if len(bot.guilds) != len(db_guilds):
        for g in db_guilds:
            if not any(x for x in bot.guilds if x.id == g.id):
                log.info("Kicked from guild '{0}' (ID: {1}) between sessions".
                         format(g.name, g.id))
                await ch_log.log(
                    "Kicked from guild **{0}** (ID: `{1}`)".format(
                        g.name, g.id))
                sql.guild_delete(g.id)

    log.info('I am ready!')
    await ch_log.log("I am ready!")
    print("I am ready!")
예제 #14
0
 async def faction_name(self, ctx):
     if not sql.guild_is_faction(ctx.guild.id):
         await ctx.send(ctx.s("faction.must_be_a_faction"))
         return
     if not ctx.invoked_subcommand or ctx.invoked_subcommand.name == "name":
         await ctx.send(sql.guild_get_by_id(ctx.guild.id).faction_name)
예제 #15
0
def is_template_adder(ctx):
    role_id = sql.guild_get_by_id(ctx.guild.id).template_adder
    r = dget(ctx.author.roles, id=role_id)
    return bool(not role_id or r)
예제 #16
0
def is_admin(ctx):
    role_id = sql.guild_get_by_id(ctx.guild.id).bot_admin
    r = dget(ctx.author.roles, id=role_id)
    return bool(r) or ctx.author.permissions_in(ctx.channel).administrator
예제 #17
0
    async def template_info(self, ctx, *args):
        gid = ctx.guild.id
        iter_args = iter(args)
        name = next(iter_args, 1)
        image_only = False
        if name == "-r":
            image_only = True
            name = next(iter_args, 1)
        if name == "-f":
            fac = next(iter_args, None)
            if fac is None:
                await ctx.send(ctx.s("error.missing_arg_faction"))
                return
            faction = sql.guild_get_by_faction_name_or_alias(fac)
            if not faction:
                raise FactionNotFoundError
            gid = faction.id
            name = next(iter_args, 1)
        else:
            faction = sql.guild_get_by_id(gid)
        t = sql.template_get_by_name(gid, name)
        if not t:
            raise TemplateNotFoundError

        if image_only:
            zoom = next(iter_args, 1)
            try:
                if type(zoom) is not int:
                    if zoom.startswith("#"):
                        zoom = zoom[1:]
                    zoom = int(zoom)
            except ValueError:
                zoom = 1
            max_zoom = int(math.sqrt(4000000 // (t.width * t.height)))
            zoom = max(1, min(zoom, max_zoom))

            img = render.zoom(await http.get_template(t.url, t.name), zoom)

            with io.BytesIO() as bio:
                img.save(bio, format="PNG")
                bio.seek(0)
                f = discord.File(bio, t.name + ".png")
                await ctx.send(file=f)
            return

        canvas_name = canvases.pretty_print[t.canvas]
        coords = "({}, {})".format(t.x, t.y)
        dimensions = "{} x {}".format(t.width, t.height)
        size = t.size
        visibility = ctx.s("bot.private") if bool(
            t.private) else ctx.s("bot.public")
        owner = self.bot.get_user(t.owner_id)
        if owner is None:
            added_by = ctx.s("error.account_deleted")
        else:
            added_by = owner.name + "#" + owner.discriminator
        date_added = datetime.date.fromtimestamp(
            t.date_created).strftime("%d %b, %Y")
        date_modified = datetime.date.fromtimestamp(
            t.date_updated).strftime("%d %b, %Y")
        color = faction.faction_color
        description = "[__{}__]({})".format(
            ctx.s("template.link_to_canvas"),
            canvases.url_templates[t.canvas].format(*t.center()))

        if size == 0:
            t.size = await render.calculate_size(await http.get_template(
                t.url, t.name))
            sql.template_update(t)

        e = discord.Embed(title=t.name, color=color, description=description) \
            .set_image(url=t.url) \
            .add_field(name=ctx.s("bot.canvas"), value=canvas_name, inline=True) \
            .add_field(name=ctx.s("bot.coordinates"), value=coords, inline=True) \
            .add_field(name=ctx.s("bot.dimensions"), value=dimensions, inline=True) \
            .add_field(name=ctx.s("bot.size"), value=size, inline=True) \
            .add_field(name=ctx.s("bot.visibility"), value=visibility, inline=True) \
            .add_field(name=ctx.s("bot.added_by"), value=added_by, inline=True) \
            .add_field(name=ctx.s("bot.date_added"), value=date_added, inline=True) \
            .add_field(name=ctx.s("bot.date_modified"), value=date_modified, inline=True)

        if faction.id != ctx.guild.id and faction.faction_name:
            e = e.set_author(name=faction.faction_name,
                             icon_url=faction.faction_emblem
                             or discord.Embed.Empty)

        await ctx.send(embed=e)