Example #1
0
async def add_starboard(bot: commands.Bot, channel: discord.TextChannel):
    check_starboard = \
        """SELECT * FROM starboards WHERE id=$1"""
    check_aschannel = \
        """SELECT * FROM aschannels WHERE id=$1"""
    get_starboards = \
        """SELECT * FROM starboards WHERE guild_id=$1"""

    guild = channel.guild
    perms = channel.permissions_for(guild.me)

    if not perms.read_messages:
        raise errors.BotNeedsPerms(
            "I need the `READ MESSAGES` permission in that channel.")
    elif not perms.read_message_history:
        raise errors.BotNeedsPerms(
            "I need the `READ MESSAGE HISTORY` permission in that channel.")
    elif not perms.send_messages:
        raise errors.BotNeedsPerms(
            "I need the `SEND MESSAGES` permission in that channel.")
    elif not perms.embed_links:
        raise errors.BotNeedsPerms(
            "I need the `EMBED LINKS` permission in that channel.")
    elif not perms.add_reactions:
        raise errors.BotNeedsPerms(
            "I need the `ADD REACTIONS` permission in that channel.")

    limit = await functions.get_limit(bot.db, 'starboards', guild)
    conn = bot.db.conn

    async with bot.db.lock:
        async with conn.transaction():
            await functions.check_or_create_existence(bot.db, conn, bot,
                                                      channel.guild.id)

            all_starboards = await conn.fetch(get_starboards, guild.id)

            if len(all_starboards) + 1 > limit:
                raise errors.NoPremiumError(
                    "You have reached your limit for starboards on this server"
                    "\nTo add more starboards, the owner of this server must "
                    "become a patron.")

            sql_starboard = await conn.fetchrow(check_starboard, channel.id)

            if sql_starboard is not None:
                raise errors.AlreadyExists("That is already a starboard!")

            sql_aschannel = await conn.fetchrow(check_aschannel, channel.id)

            if sql_aschannel is not None:
                raise errors.AlreadyExists(
                    "That channel is already an AutoStar channel!\n"
                    "A channel can't be both an AutoStar channel "
                    "and a starboard.")

            await bot.db.q.create_starboard.fetch(channel.id, guild.id)

    await add_starboard_emoji(bot, channel.id, channel.guild, 'тнР')
Example #2
0
async def add_aschannel(bot: commands.Bot, channel: discord.TextChannel):
    check_aschannel = \
        """SELECT * FROM aschannels WHERE id=$1"""
    check_starboard = \
        """SELECT * FROM starboards WHERE id=$1"""
    get_aschannels = \
        """SELECT * FROM aschannels WHERE guild_id=$1"""

    guild = channel.guild
    perms = channel.permissions_for(guild.me)
    limit = await functions.get_limit(bot.db, 'aschannels', guild)
    conn = bot.db.conn

    if not perms.read_messages:
        raise errors.BotNeedsPerms(
            "I need the 'READ MESSAGES' permission in that channel.")
    elif not perms.manage_messages:
        raise errors.BotNeedsPerms(
            "I need the `MANAGE MESSAGES` permission in that channel.")
    elif not perms.add_reactions:
        raise errors.BotNeedsPerms(
            "I need the `ADD REACTIONS` permission in that channel.")

    async with bot.db.lock:
        async with conn.transaction():
            await functions.check_or_create_existence(bot.db,
                                                      conn,
                                                      bot,
                                                      guild_id=guild.id)

            all_aschannels = await conn.fetch(get_aschannels, guild.id)

            if len(all_aschannels) >= limit:
                raise errors.NoPremiumError(
                    "You have reached your limit for AutoStar Channels"
                    " in this server.\nTo add more AutoStar channels, "
                    "the server owner must become a patron.")

            sql_aschannel = await conn.fetchrow(check_aschannel, channel.id)

            if sql_aschannel is not None:
                raise errors.AlreadyExists(
                    "That is already an AutoStar Channel!")

            sql_starboard = await conn.fetchrow(check_starboard, channel.id)

            if sql_starboard is not None:
                raise errors.AlreadyExists(
                    "That channel is already a starboard!\n"
                    "A channel can't be both a starboard and an "
                    "AutoStar channel.")

            await bot.db.q.create_aschannel.fetch(channel.id, guild.id)
Example #3
0
async def add_role_blacklist(
    bot: commands.Bot,
    role_id: int,
    starboard_id: int,
    guild_id: int,
    is_whitelist: bool = False
) -> None:
    check_exists = \
        """SELECT * FROM rolebl WHERE role_id=$1 AND starboard_id=$2"""
    check_starboard = \
        """SELECT * FROM starboards WHERE id=$1 AND guild_id=$2"""

    conn = bot.db.conn

    async with bot.db.lock:
        async with conn.transaction():
            sql_rolebl = await conn.fetchrow(
                check_exists, role_id, starboard_id
            )
            if sql_rolebl is not None:
                raise errors.AlreadyExists(
                    "That role is already whitelisted/blacklisted"
                )
            sql_starboard = await conn.fetchrow(
                check_starboard, starboard_id, guild_id
            )
            if sql_starboard is None:
                raise errors.DoesNotExist(
                    "That is not a starboard!"
                )

            await bot.db.q.create_rolebl.fetch(
                starboard_id, role_id, guild_id, is_whitelist
            )
Example #4
0
async def add_starboard_emoji(
    bot: commands.Bot,
    starboard_id: int,
    guild: discord.Guild,
    emoji: Union[discord.Emoji, str]
) -> None:
    check_sbemoji = \
        """SELECT * FROM sbemojis WHERE name=$1 AND starboard_id=$2"""
    get_all_sbemojis = \
        """SELECT * FROM sbemojis WHERE starboard_id=$1"""
    check_starboard = \
        """SELECT * FROM starboards WHERE id=$1"""

    if not isinstance(emoji, discord.Emoji):
        if not functions.is_emoji(emoji):
            raise errors.InvalidArgument(
                "I don't recognize that emoji. If it is a custom "
                "emoji, it has to be in this server."
            )

    emoji_name = str(emoji.id) if isinstance(
        emoji, discord.Emoji) else str(emoji)
    emoji_id = emoji.id if isinstance(
        emoji, discord.Emoji) else None

    limit = await functions.get_limit(bot, 'emojis', guild.id)
    conn = bot.db.conn

    async with bot.db.lock:
        async with conn.transaction():
            sql_starboard = await conn.fetchrow(
                check_starboard, starboard_id
            )

            if sql_starboard is None:
                raise errors.DoesNotExist("That is not a starboard!")

            all_sbemojis = await conn.fetch(
                get_all_sbemojis, starboard_id
            )

            if len(all_sbemojis) + 1 > limit:
                raise errors.NoPremiumError(
                    "You have reached your limit for emojis "
                    "on this starboard.\nSee the last page of "
                    "`sb!tutorial` for more info."
                )

            sbemoji = await conn.fetchrow(
                check_sbemoji, emoji_name, starboard_id
            )

            if sbemoji is not None:
                raise errors.AlreadyExists(
                    "That is already a starboard emoji!"
                )

            await bot.db.q.create_sbemoji.fetch(
                emoji_id, starboard_id, emoji_name, False
            )
Example #5
0
async def add_asemoji(
    bot: commands.Bot,
    aschannel: discord.TextChannel,
    name: str
) -> None:
    check_aschannel = \
        """SELECT * FROM aschannels WHERE id=$1"""
    check_asemoji = \
        """SELECT * FROM asemojis WHERE name=$1 and aschannel_id=$2"""

    conn = bot.db.conn

    async with bot.db.lock:
        async with conn.transaction():
            sasc = await conn.fetchrow(
                check_aschannel, aschannel.id
            )
            if sasc is None:
                raise errors.DoesNotExist("That is not an AutoStar Channel!")

            se = await conn.fetchrow(
                check_asemoji, name, aschannel.id
            )
            if se is not None:
                raise errors.AlreadyExists(
                    "That emoji is already on this AutoStar Channel!"
                )

            await bot.db.q.create_asemoji.fetch(
                aschannel.id, name
            )
                    _(u"Unable to connect to server: %(error)s") %
                    {'error': err})
            except M2Crypto.BIO.BIOError, err:
                raise errors.CouldNotConnect(
                    _(u"Unable to connect to server: %(error)s") %
                    {'error': err})
            except zanshin.http.HTTPError, err:
                logger.error('Received status %d attempting to create %s',
                             err.status, self.getLocation())

                if err.status == twisted.web.http.NOT_ALLOWED:
                    # already exists
                    message = _(u"Collection at %(url)s already exists.") % {
                        'url': url
                    }
                    raise errors.AlreadyExists(message)

                if err.status == twisted.web.http.UNAUTHORIZED:
                    # not authorized
                    message = _(
                        u"Not authorized to create collection %(url)s.") % {
                            'url': url
                        }
                    raise errors.NotAllowed(message)

                if err.status == twisted.web.http.CONFLICT:
                    # this happens if you try to create a collection within a
                    # nonexistent collection
                    (host, port, sharePath, username, password, useSSL) = \
                        self._getSettings(withPassword=False)
                    message = _(
Example #7
0
    def put(self, text):
        path = self.getMorsecodePath()

        if self.syncToken:
            method = 'POST'
        else:
            method = 'PUT'

        tries = 3
        resp = self._send(method, path, text)
        while resp.status == 503:
            tries -= 1
            if tries == 0:
                msg = _(u"Server busy.  Try again later. (HTTP status 503)")
                raise errors.SharingError(msg)
            resp = self._send(method, path, text)

        if resp.status in (205, 423):
            # The collection has either been updated by someone else since
            # we last did a GET (205) or the collection is in the process of
            # being updated right now and is locked (423).  In each case, our
            # reaction is the same -- abort the sync.
            # TODO: We should try to sync again soon
            raise errors.TokenMismatch(
                _(u"Collection updated by someone else."))

        elif resp.status in (403, 409):
            # Either a collection already exists with the UUID or we've got
            # multiple items with the same icaluid.  Need to parse the response
            # body to find out
            rootElement = self.raiseCosmoError(resp.body)

            # Find out if it's ours:
            shares = self.account.getPublishedShares(blocking=True)
            toRaise = errors.AlreadyExists(
                "%s (HTTP status %d)" % (resp.message, resp.status),
                details="Collection already exists on server")
            toRaise.mine = False
            for name, uuid, href, tickets, unsubscribed in shares:
                if uuid == self.share.contents.itsUUID.str16():
                    toRaise.mine = True
            raise toRaise

        elif resp.status == 401:
            raise errors.NotAllowed(
                _(u"Please verify your username and password"),
                details="Received [%s]" % resp.body)

        elif resp.status not in (201, 204):
            raise errors.SharingError(
                "%s (HTTP status %d)" % (resp.message, resp.status),
                details="Sent [%s], Received [%s]" % (text, resp.body))

        syncTokenHeaders = resp.headers.getHeader('X-MorseCode-SyncToken')
        if syncTokenHeaders:
            self.syncToken = syncTokenHeaders[0]
        # # @@@MOR what if this header is missing?

        if method == 'PUT':
            ticketHeaders = resp.headers.getHeader('X-MorseCode-Ticket')
            if ticketHeaders:
                for ticketHeader in ticketHeaders:
                    mode, ticket = ticketHeader.split('=')
                    if mode == 'read-only':
                        self.ticketReadOnly = ticket
                    if mode == 'read-write':
                        self.ticketReadWrite = ticket
Example #8
0
async def add_aschannel(
    bot: commands.Bot,
    channel: discord.TextChannel
) -> None:
    check_aschannel = \
        """SELECT * FROM aschannels WHERE id=$1"""
    check_starboard = \
        """SELECT * FROM starboards WHERE id=$1"""
    get_aschannels = \
        """SELECT * FROM aschannels WHERE guild_id=$1"""

    # just in case we messed something up earlier and it's already in there
    if channel.id not in bot.db.as_cache:
        bot.db.as_cache.add(channel.id)

    guild = channel.guild
    perms = channel.permissions_for(guild.me)
    limit = await functions.get_limit(
        bot, 'aschannels', guild.id
    )
    conn = bot.db.conn

    if not perms.read_messages:
        raise errors.BotNeedsPerms(
            "I need the 'READ MESSAGES' permission in that channel."
        )
    elif not perms.manage_messages:
        raise errors.BotNeedsPerms(
            "I need the `MANAGE MESSAGES` permission in that channel."
        )
    elif not perms.add_reactions:
        raise errors.BotNeedsPerms(
            "I need the `ADD REACTIONS` permission in that channel."
        )

    await functions.check_or_create_existence(
        bot, guild_id=guild.id
    )

    async with bot.db.lock:
        async with conn.transaction():
            all_aschannels = await conn.fetch(
                get_aschannels, guild.id
            )

            if len(all_aschannels) >= limit:
                raise errors.NoPremiumError(
                    "You have reached your limit for AutoStar Channels"
                    " in this server.\nSee the last page of `sb!tutorial` "
                    "for more info."
                )

            sql_aschannel = await conn.fetchrow(
                check_aschannel, channel.id
            )

            if sql_aschannel is not None:
                raise errors.AlreadyExists(
                    "That is already an AutoStar Channel!"
                )

            sql_starboard = await conn.fetchrow(
                check_starboard, channel.id
            )

            if sql_starboard is not None:
                raise errors.AlreadyExists(
                    "That channel is already a starboard!\n"
                    "A channel can't be both a starboard and an "
                    "AutoStar channel."
                )

            await bot.db.q.create_aschannel.fetch(
                channel.id, guild.id
            )