コード例 #1
0
async def setup(message, args, **kwargs):
    if not message.author.guild_permissions.manage_guild:
        await message.channel.send(
            "You require the `MANAGE_GUILD` permission to use this command!"
        )
        return

    configs = await get_guild_configs(message.guild.id)

    if not args:
        if not (
            message.channel.permissions_for(message.guild.me).embed_links
            and message.channel.permissions_for(message.guild.me).attach_files
        ):
            await message.channel.send(
                "I require the `EMBED_LINKS` and `ATTACH_FILES` permissions to use this command!"
            )
            return

        embed = discord.Embed(color=util.get_color(message.guild.me))

        config_export = "None generated."

        files = []
        if configs.guild_id:
            config_export = configs.export()

        if len(config_export) > 1024:
            b = BytesIO()
            b.write(config_export.encode("utf-8"))
            b.seek(0)
            config_export = (
                "This string was too long to send. Please check the uploaded file."
            )
            files += [discord.File(b, "config_export.txt")]

        embed.add_field(name="Config Export", value=config_export)

        guild_file = None
        guild_export = {
            "roles": [
                [i.name, str(i.id), str(i.color)]
                for i in sorted(
                    message.guild.roles, key=lambda x: x.position, reverse=True
                )
                if i.id != message.guild.id
            ],
            "channels": [
                [i.name, str(i.id)]
                for i in message.guild.text_channels
                if i.permissions_for(message.guild.me).send_messages
            ],
        }

        guild_export = encode(json.dumps(guild_export))

        full_guild_export = guild_export

        if len(guild_export) > 2048:
            b = BytesIO()
            b.write(guild_export.encode("utf-8"))
            b.seek(0)
            guild_export = (
                "This string was too long to send. Please check the uploaded file."
            )
            files += [discord.File(b, "guild_data_export.txt")]

        elif len(guild_export) > 1024:
            embed.title = "Guild Data Export (Full code)"
            embed.description = guild_export
            guild_export = "This string was too long to put in here. Please check the long bit of text above."

        embed.add_field(name="Guild Data Export", value=guild_export)

        ret = "Welcome to the ⌚ setup!\nPlease go to https://sink.discord.bot/⌚ to generate an import code!\nRun this command with the Import config to set up the bot on this guild."
        if len(full_guild_export) <= 2000 and message.author.is_on_mobile():
            ret += "\n\nI am detecting that you are currently on a mobile device. React to this message with ☎ (`telephone`) to receive a DM with the data that can easily be copied."

        msg = await message.channel.send(ret, embed=embed, files=files)

        if len(full_guild_export) <= 2000:

            def check(reaction, user):
                return (
                    reaction.message.id == msg.id
                    and reaction.emoji.strip("\uFE0F\uFE0E") == "☎"
                    and user.id == message.author.id
                )

            try:
                reaction, user = await bot.wait_for("reaction_add", check=check)
            except asyncio.TimeoutError:
                return

            if reaction:
                try:
                    await message.author.send(full_guild_export)
                except:
                    await message.channel.send(
                        "DM failed. Please ensure your DMs are enabled and run the command again."
                    )

        return True

    else:
        if not (
            message.channel.permissions_for(message.guild.me).embed_links
            and message.channel.permissions_for(message.guild.me).add_reactions
        ):
            await message.channel.send(
                "I require the `EMBED_LINKS` and `ADD_REACTIONS` permissions to use this command!"
            )
            return

        channel = None
        try:
            args = json.loads(decode(args))
            args["guild_id"] = message.guild.id
            args["post_channel"] = configs.post_channel
            args["special_roles"] = [int(r) for r in args["roles"]]
            args["prefix"] = args["prefix"].strip()[:32] if args["prefix"] else None
            args["options"] = int(args["options"])
            offset = 0 if not args["offset"] else args["offset"]
            args["_offset"] = max(0, min(2147483647, int(offset)) - 1)

            if not configs.guild_id:
                args["post_channel"] = int(args["channel"])
                channel = message.guild.get_channel(args["post_channel"])
                if not channel:
                    raise ValueError
        except:
            await message.channel.send("Invalid input!")
            return

        if configs:
            args["offset"] = configs.offset

        emotes = ["✅", "❎"]

        args = Configs.from_row(args)

        msg = await message.channel.send(
            "Here are your imported settings! Please react with ✅ to confirm them. (You can check then again later with the `settings` command)",
            embed=args.as_embed(message.guild),
        )

        for e in emotes:
            await msg.add_reaction(e)

        def check(reaction, user):
            return (
                reaction.message.id == msg.id
                and reaction.emoji in emotes
                and user.id == message.author.id
            )

        try:
            reaction, user = await bot.wait_for("reaction_add", check=check)
        except asyncio.TimeoutError:
            return

        if reaction.emoji == "✅":
            await bot.db.execute(
                """
            INSERT INTO guild_configs (
            guild_id, post_channel, prefix, options, latest_event_count, special_roles, recent_events, _offset
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
            ON CONFLICT (guild_id)
            DO UPDATE SET
                prefix = EXCLUDED.prefix,
                options = EXCLUDED.options,
                special_roles = EXCLUDED.special_roles
            ;""",
                *args.db_insert(),
            )

            bot._guild_prefix_cache[message.guild.id] = args.prefix

            await message.channel.send("Your settings have been updated.")
        else:
            await message.channel.send("Process aborted.")

    return True
コード例 #2
0
async def get_guild_configs(guild_id):
    ret = await bot.db.fetchrow(
        "SELECT * FROM guild_configs WHERE guild_id = $1;", guild_id
    )
    ret = ret if ret else {}
    return Configs.from_row(ret)