Esempio n. 1
0
    async def nick(self, ctx: commands.Context, *, new_nick: str = ""):
        guild = session.query(Guild).filter(
            Guild.guild_id == ctx.guild.id).first()
        if not guild:
            guild = Guild(guild_id=ctx.guild.id)
            session.add(guild)
            session.commit()

        if not guild.custom_nick:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> This server has disabled custom nicknames!"
            )
            return

        discord_user = session.query(DiscordUser).filter(
            DiscordUser.user_id == ctx.author.id).first()
        verified = [acc.username for acc in discord_user.reddit_accounts]

        if new_nick != "":
            end = f"({'unverified' if len(verified) <= 0 else '/u/' + verified[0]})"
            new_nick = f"{new_nick[:32 - len(end) - 1]} {end}"
        else:
            new_nick = f"/u/{verified[0]}" if len(
                verified) > 0 else ctx.author.username

        try:
            await ctx.author.edit(nick=new_nick)
        except discord.errors.Forbidden:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> I don't have the permissions to edit your nickname!"
            )
Esempio n. 2
0
    async def delcat(self, ctx: commands.Context, *, cat: str):
        category = session.query(Category).filter(
            func.lower(Category.name) == cat.lower()).first()

        if not category:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> '{cat}' isn't a category in the Melons!")
            return

        message = await ctx.send(
            f"❓ Are you sure you want to remove {cat} from the Melons?")
        await message.add_reaction(EMOJIS['CHECK'])
        await message.add_reaction(EMOJIS['XMARK'])

        try:
            reaction = await self.bot.wait_for(
                "reaction_add",
                check=lambda r, u: u.id == ctx.author.id and r.message.id ==
                message.id,
                timeout=2 * 60)
        except asyncio.exceptions.TimeoutError:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> That took too long! " +
                "You can restart the process by calling this command again.")
            return
        finally:
            if reaction[0].custom_emoji and reaction[0].emoji.id == int(
                    EMOJIS['CHECK'].split(":")[2]):
                session.delete(category)
                session.commit()
                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Successfully removed '{cat}' as a category in the Melons!"
                )
Esempio n. 3
0
    async def remdefault(self, ctx: commands.Context, emoji: str):
        try:
            await ctx.message.add_reaction(emoji)
        except BaseException:
            await ctx.send(f"<{EMOJIS['XMARK']}> Uh-oh, looks like that emoji doesn't work!")
            return

        channel = session.query(Channel).filter(Channel.channel_id == ctx.channel.id).first()

        if not channel or not channel.poll_channel:
            msg = f"<{EMOJIS['XMARK']}> This channel isn't setup as a poll channel! Please use `!togglepoll` to enable the feature!"
            await ctx.send(msg)
            return

        channel_emoji = session.query(ChannelEmoji).filter(
            and_(
                ChannelEmoji.channel_id == ctx.channel.id,
                ChannelEmoji.emoji == emoji)).first()

        if channel_emoji:
            channel_emoji.delete()
            session.commit()
            await ctx.send(f"<{EMOJIS['CHECK']}> Removed {emoji} from the list of default emojis for this poll channel!", delete_after=3)
            await ctx.message.delete()
        else:
            await ctx.send(f"<{EMOJIS['XMARK']}> {emoji} isn't a default poll emoji in this channel!")
Esempio n. 4
0
    async def addemoji(self, ctx: commands.Context, emoji: str):
        try:
            await ctx.message.add_reaction(emoji)
        except BaseException:
            await ctx.send(f"<{EMOJIS['XMARK']}> Uh-oh, looks like that emoji doesn't work!")
            return

        channel = session.query(Channel).filter(Channel.channel_id == ctx.channel.id).first()

        if not channel or not channel.poll_channel:
            msg = f"<{EMOJIS['XMARK']}> This channel isn't setup as a poll channel! Please use `!togglepoll` to enable the feature!"
            await ctx.send(msg)
            return

        channel_emoji = session.query(ChannelEmoji).filter(
            and_(
                ChannelEmoji.channel_id == ctx.channel.id,
                ChannelEmoji.emoji == emoji)).first()

        if not channel_emoji:
            channel_emoji = ChannelEmoji(channel_id=ctx.channel.id, emoji=emoji)
            session.add(channel_emoji)
            session.commit()
            await ctx.send(f"<{EMOJIS['CHECK']}> Successfully added {emoji} to the list of emojis to add in this channel!", delete_after=3)

            async for msg in ctx.history(limit=None):
                await msg.add_reaction(emoji)
        else:
            await ctx.send(f"<{EMOJIS['XMARK']}> That emoji is already set for this channel!")
Esempio n. 5
0
    async def toggle(self, ctx: commands.Context, toggle: str):
        guild = session.query(Guild).filter(
            Guild.guild_id == ctx.guild.id).first()

        if not guild:
            guild = Guild(guild_id=ctx.guild.id)
            session.add(guild)
            session.commit()

        if toggle == "username":
            guild.set_username = not guild.set_username
            session.commit()

            if guild.set_username:
                for member in ctx.guild.members:
                    if discord_user := session.query(DiscordUser).filter(
                            DiscordUser.user_id == member.id).first():
                        await self.bot.update_guild_user(guild, discord_user)
                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Reddit usernames enabled for this server!"
                )
            else:
                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Reddit usernames disabled for this server!"
                )
Esempio n. 6
0
    async def on_guild_join(self, g: discord.Guild):
        guild = session.query(Guild).filter(Guild.guild_id == g.id).first()

        if not guild:
            guild = Guild(guild_id=g.id)
            session.add(guild)
            session.commit()
Esempio n. 7
0
    async def update_guild_user(self, guild: Guild, discord_user: DiscordUser):
        g = bot.get_guild(guild.guild_id)
        if g is None:
            return

        m = g.get_member(discord_user.user_id)
        if m is None:
            return

        verified_accounts = [acc for acc in discord_user.reddit_accounts if acc.verified]

        if guild.set_role:
            role = g.get_role(guild.role)

            if not role:
                role = await g.create_role(name="Verified Redditor",
                                           colour=discord.Colour(0).from_rgb(254, 63, 24),
                                           mentionable=True,
                                           reason="Verified Redditors get this role by the bot.")
                guild.role = role.id
                session.commit()

            if verified_accounts:
                await m.add_roles(role)
            else:
                await m.remove_roles(role)

        if guild.set_username:
            for account in verified_accounts:
                try:
                    await m.edit(nick=f"/u/{account.username}")
                except discord.errors.Forbidden:
                    await self.send_error(f"❗ I don't have the necessary permissions to change {m.mention}'s nickname.")
                finally:
                    break
Esempio n. 8
0
    async def addtags(self, ctx: commands.Context, *, key: str = ""):
        guild = self.bot.get_db_guild(ctx.guild.id)

        if ctx.author.id not in AUTHORIZED_USERS:
            if not guild.melon_role:
                await ctx.send(
                    f"<{EMOJIS['XMARK']}> Custom Melons for this guild haven't been enabled!"
                )
                return

            roles = [role.id for role in ctx.author.roles]
            if guild.melon_role not in roles:
                await ctx.send(
                    f"<{EMOJIS['XMARK']}> You aren't authorized to edit Melons in this guild!"
                )
                return

        if not key:
            key = await self.ask_prompt(
                ctx, "❓ What is the key used for the Melon?")
            if not key:
                return
            else:
                key = key.lower()

        if ctx.author.id in AUTHORIZED_USERS:
            melon = session.query(Melon).filter(
                and_(
                    func.lower(Melon.key) == key,
                    or_(Melon.guild_id == guild.guild_id,
                        Melon.guild_id.is_(None)))).first()
        else:
            melon = session.query(Melon).filter(
                and_(
                    func.lower(Melon.key) == key,
                    Melon.guild_id == guild.guild_id)).first()

        if not melon:
            await ctx.send(f"<{EMOJIS['XMARK']}> Melon '{key}' doesn't exist!")

        tags = await self.ask_prompt(
            ctx, f"❓ Which tags should be added to the Melon '{key}'?")
        if not tags:
            return
        tags = tags.split(" ")
        for t in tags:
            tag = session.query(Tag).filter(
                func.lower(Tag.value) == t.lower()).first()
            if not tag:
                tag = Tag(value=t)
                session.add(tag)
            elif tag in melon.tags:
                continue
            melon.tags.append(tag)
        session.commit()
        await ctx.send(
            f"<{EMOJIS['CHECK']}> Successfully added tags `{', '.join(tags)}` to Melon '{melon.key}'!"
        )
Esempio n. 9
0
    def get_db_guild(self, guild_id: int) -> Guild:
        guild = session.query(Guild).filter(Guild.guild_id == guild_id).first()

        if not guild:
            categories = session.query(Category).filter(
                Category.default == true()).all()
            guild = Guild(guild_id=guild_id, categories=categories)
            session.add(guild)
            session.commit()

        return guild
Esempio n. 10
0
    async def addcat(self, ctx: commands.Context, *, cat: str):
        category = session.query(Category).filter(
            func.lower(Category.name) == cat.lower()).first()

        if category:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> '{cat}' is already a category in the Melons!"
            )
        else:
            category = Category(name=cat)
            session.add(category)
            session.commit()
            await ctx.send(
                f"<{EMOJIS['CHECK']}> Successfully added '{cat}' as a category in the Melons!"
            )
Esempio n. 11
0
    async def togglepoll(self, ctx: commands.Context):
        channel = session.query(Channel).filter(Channel.channel_id == ctx.channel.id).first()

        if not channel:
            channel = Channel(channel_id=ctx.channel.id, poll_channel=True)
            session.add(channel)
        else:
            channel.poll_channel = not channel.poll_channel

        session.commit()

        if channel.poll_channel:
            await ctx.send(f"<{EMOJIS['CHECK']}> Successfully registered channel as a poll channel!", delete_after=3)
        else:
            await ctx.send(f"<{EMOJIS['CHECK']}> Successfully removed polling feature from this channel!", delete_after=3)
        await ctx.message.delete()
Esempio n. 12
0
    async def setchannelsub(self, ctx: commands.Context, sub: str):
        s = await self.bot.reddit.subreddit(sub)

        channel = session.query(Channel).filter(
            Channel.channel_id == ctx.channel.id).first()

        if not channel:
            channel = Channel(channel_id=ctx.channel.id)
            session.add(channel)

        channel.subreddit = sub

        session.commit()
        await ctx.send(
            f"<{EMOJIS['CHECK']}> Successfully set /r/{sub} as this channels's subreddit!"
        )
Esempio n. 13
0
    async def unverify(self, ctx: commands.Context, user: str):
        if reddit_user := session.query(RedditUser).filter(
                and_(
                    func.lower(RedditUser.username) == user,
                    RedditUser.discord_user == ctx.author.id)).first():
            session.delete(reddit_user)
            session.commit()

            guild = session.query(Guild).filter(
                Guild.guild_id == ctx.guild.id).first()
            if not guild:
                guild = Guild(guild_id=ctx.guild.id)
                session.add(guild)
                session.commit()

            if discord_user := session.query(DiscordUser).filter(
                    DiscordUser.user_id == ctx.author.id).first():
                await self.bot.update_guild_user(guild, discord_user)
Esempio n. 14
0
    async def status(self, ctx: commands.Context):
        guild = session.query(Guild).filter(
            Guild.guild_id == ctx.guild.id).first()

        if not guild:
            guild = Guild(guild_id=ctx.guild.id)
            session.add(guild)
            session.commit()

        set_role = "on" if guild.set_role else "off"
        set_username = "******" if guild.set_username else "off"
        set_nickname = "on" if guild.custom_nick else "off"
        role_name = ctx.guild.get_role(guild.role).name if guild.role else None

        await ctx.channel.send(
            f"Adding '{role_name}' role: {set_role}\n" +
            f"Changing nickname to /u/username: {set_username}\n" +
            f"Allowing custom nicknames: {set_nickname}")
Esempio n. 15
0
    async def enableguildmelons(self, ctx: commands.Context):
        guild = self.bot.get_db_guild(ctx.guild.id)

        if guild.melon_role:
            await ctx.send(
                "Custom Melons have already been enabled in this guild!")
            return

        role = await ctx.guild.create_role(name="🍉 Melon Editor")
        guild.melon_role = role.id

        await ctx.author.add_roles(role)

        session.commit()

        content = f"Melons have been enabled for this guild! " + \
            f"You were assigned the {role.mention} role which can be assigned to others that allows you to edit Melons!\n\n" + \
            "A more in-depth documentation of the Melon system can be found on Melon's GitHub Wikipage."
        await ctx.send(content)
Esempio n. 16
0
    async def adddefault(self, ctx: commands.Context, emoji: str):
        try:
            await ctx.message.add_reaction(emoji)
        except BaseException:
            await ctx.send(f"<{EMOJIS['XMARK']}> Uh-oh, looks like that emoji doesn't work!")
            return

        channel = session.query(Channel).filter(Channel.channel_id == ctx.channel.id).first()

        if not channel or not channel.poll_channel:
            msg = f"<{EMOJIS['XMARK']}> This channel isn't setup as a poll channel! Please use `!togglepoll` to enable the feature!"
            await ctx.send(msg)
            return

        channel_emoji = ChannelEmoji(channel_id=channel.channel_id, emoji=emoji, default_emoji=True)
        session.add(channel_emoji)
        session.commit()

        await ctx.send(f"<{EMOJIS['CHECK']}> Added {emoji} to the list of default emojis for this poll channel!", delete_after=3)
        await ctx.message.delete()
Esempio n. 17
0
    async def enablecat(self, ctx: commands.Context, *, cat: str):
        category = session.query(Category).filter(
            func.lower(Category.name) == cat.lower()).first()

        if not category:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> Melon category '{cat}' doesn't exist!")
            return

        guild = self.bot.get_db_guild(ctx.guild.id)

        category_ids = [cat.category_id for cat in guild.categories]
        if category.category_id in category_ids:
            await ctx.send(f"❗ Melon category '{cat}' was already enabled!")
        else:
            guild.categories.append(category)
            session.commit()
            await ctx.send(
                f"<{EMOJIS['CHECK']}> Melon category '{cat}' successfully enabled!"
            )
Esempio n. 18
0
    async def setguildsub(self, ctx: commands.Context, sub: str):
        guild = session.query(Guild).filter(
            Guild.guild_id == ctx.guild.id).first()

        if not guild:
            guild = Guild(guild_id=ctx.guild.id)
            session.add(guild)
            session.commit()

        try:
            s = await self.bot.reddit.subreddit(sub)
        except BaseException:
            await ctx.send(
                "❗ /r/{} doesn't exist or isn't visible to me!".format(sub))
        else:
            guild.subreddit = sub
            session.commit()
            await ctx.send(
                f"<{EMOJIS['CHECK']}> Successfully set /r/{sub} as this guild's subreddit!"
            )
Esempio n. 19
0
    async def remoji(self, ctx: commands.Context, emoji: str):
        member = ctx.guild.get_member(bot.user.id)
        try:
            await ctx.message.remove_reaction(emoji, member)
        except BaseException:
            await ctx.send(f"<{EMOJIS['XMARK']}> Uh-oh, looks like that emoji doesn't work!")
            return

        channel_emoji = session.query(ChannelEmoji).filter(
            and_(
                ChannelEmoji.channel_id == ctx.channel.id,
                ChannelEmoji.emoji == emoji)).first()

        if channel_emoji:
            channel_emoji.delete()
            session.commit()
            await ctx.send(f"<{EMOJIS['CHECK']}> Successfully removed {emoji} from the list of emojis to add in this channel!", delete_after=3)
        else:
            await ctx.send(f"<{EMOJIS['XMARK']}> Couldn't find {emoji} in the list of emojis to add in this channel!")

        async for msg in ctx.history(limit=None):
            await msg.remove_reaction(emoji, member)
Esempio n. 20
0
    async def disablecat(self, ctx, cat):
        category = session.query(Category).filter(
            func.lower(Category.name) == cat.lower()).first()

        if not category:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> Melon category '{cat}' doesn't exist!")
            return

        guild = self.bot.get_db_guild(ctx.guild.id)

        category_ids = [cat.category_id for cat in guild.categories]
        if category.category_id in category_ids:
            guild.categories.remove(category)
            session.commit()
            await ctx.send(
                f"<{EMOJIS['CHECK']}> Melon category '{cat}' successfully disabled!"
            )
        else:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> Melon category '{cat}' was never enabled in this guild!"
            )
Esempio n. 21
0
    async def verify(self, ctx: commands.Context, user: str):
        user = user.replace("u/", "").replace("/", "").strip().lower()

        discord_user = session.query(DiscordUser).filter(
            DiscordUser.user_id == ctx.author.id).first()

        if not discord_user:
            discord_user = DiscordUser(user_id=ctx.author.id)
            session.add(discord_user)
            session.commit()

        if session.query(RedditUser).filter(
                and_(
                    func.lower(RedditUser.username) == user,
                    RedditUser.discord_user != ctx.author.id)).first():
            await ctx.message.channel.send(
                f"❗ /u/{user} is already linked to another Discord account! " +
                f"If you believe this is an error, please contact {MAINTAINER}."
            )
            return

        if session.query(RedditUser).filter(
                and_(
                    func.lower(RedditUser.username) == user,
                    RedditUser.discord_user == ctx.author.id)).first():
            await ctx.message.channel.send(
                f"❗ /u/{user} is already linked to your Discord account!")
            return

        if reddit_user := session.query(RedditUser).filter(
                and_(RedditUser.discord_user == ctx.author.id,
                     RedditUser.verified == false())).first():
            await ctx.message.channel.send(
                f"❗ /u/{reddit_user.username} is still awaiting verification on Reddit. "
                +
                f"If you would like to unlink it, use `!unverify {reddit_user.username}`."
            )
            return
Esempio n. 22
0
class UserCog(commands.Cog):
    def __init__(self, bot: 'Reddify'):
        self.bot = bot

    @commands.command(
        help=
        "Sends a PM to the Reddit user to await confirmation of the account ownership."
    )
    async def verify(self, ctx: commands.Context, user: str):
        user = user.replace("u/", "").replace("/", "").strip().lower()

        discord_user = session.query(DiscordUser).filter(
            DiscordUser.user_id == ctx.author.id).first()

        if not discord_user:
            discord_user = DiscordUser(user_id=ctx.author.id)
            session.add(discord_user)
            session.commit()

        if session.query(RedditUser).filter(
                and_(
                    func.lower(RedditUser.username) == user,
                    RedditUser.discord_user != ctx.author.id)).first():
            await ctx.message.channel.send(
                f"❗ /u/{user} is already linked to another Discord account! " +
                f"If you believe this is an error, please contact {MAINTAINER}."
            )
            return

        if session.query(RedditUser).filter(
                and_(
                    func.lower(RedditUser.username) == user,
                    RedditUser.discord_user == ctx.author.id)).first():
            await ctx.message.channel.send(
                f"❗ /u/{user} is already linked to your Discord account!")
            return

        if reddit_user := session.query(RedditUser).filter(
                and_(RedditUser.discord_user == ctx.author.id,
                     RedditUser.verified == false())).first():
            await ctx.message.channel.send(
                f"❗ /u/{reddit_user.username} is still awaiting verification on Reddit. "
                +
                f"If you would like to unlink it, use `!unverify {reddit_user.username}`."
            )
            return

        try:
            redditor = await self.bot.reddit.redditor(user)
        except Exception as e:
            await ctx.message.channel.send(
                f"❌ Redditor /u/{user} doesn't exist!\n\nError:{e}")
        else:
            await redditor.message(
                "Account Ownership Confirmation",
                f"Please reply to this message with 'verify' to confirm that you are Discord user '{ctx.message.author}'."
            )
            msg = await ctx.message.channel.send(
                f"Check your Reddit PMs to verify you are the owner of /u/{redditor.name} by responding with `verify`!"
            )

            reddit_user = RedditUser(user_id=redditor.fullname,
                                     discord_user=ctx.author.id,
                                     username=redditor.name)
            session.add(reddit_user)

            auth_user = await self.bot.reddit.user.me()
            async for message in auth_user.unread.stream(skip_existing=True):
                if not isinstance(message, apraw.models.Message):
                    continue
                if not "Account Ownership Confirmation" in message.subject:
                    continue

                try:
                    author = await message.author()
                    if author.name.lower() != reddit_user.username.lower():
                        continue
                except Exception as e:
                    await self.bot.send_error(e)

                if "verify" in message.body.lower(
                ) and not "unverify" in message.body.lower():
                    reddit_user.verified = True
                    user = self.bot.get_user(reddit_user.discord_user)
                    if user:
                        await msg.add_reaction(EMOJIS["CHECK"])
                        rep = await message.reply(
                            f"Confirmation of {user} successful!")

                        for guild in session.query(Guild).all():
                            await self.bot.update_guild_user(
                                guild, discord_user)
                else:
                    message.reply(
                        "Discord user unlinked from your Reddit account. " +
                        "Please run `!verify` again if this is an error and respond to the new PM."
                    )
                    session.delete(reddit_user)

                break

            session.commit()
Esempio n. 23
0
 def update(self):
     session.commit()
     return self
Esempio n. 24
0
    async def melon(self, ctx: commands.Context, *, search=""):
        guild = self.bot.get_db_guild(ctx.guild.id)
        melons = session.query(Melon).filter(
            or_(Melon.guild_id == guild.guild_id,
                Melon.category_id.in_(c.category_id
                                      for c in guild.categories))).all()

        if len(melons) == 0:
            await ctx.send(
                "Your guild has no enabled Melon categories. Please contact an admin to enable them."
            )
            return

        if search == "":
            popular, new, others = self.order_melons(melons)

            await ctx.send(
                "You can search for a Melon by typing `!melon [search]`." +
                "There are many available Melons.\n\n" +
                f"**Popular Melons: **{', '.join(popular)}\n" +
                f"**New Melons: **{', '.join(new)}\n" +
                f"**Other Melons: **{', '.join(others)}")
            return

        results = fuzzle.find([melon.to_dict() for melon in melons],
                              search,
                              return_all=True)

        if not results:
            await ctx.send(
                f"We couldn't find any Melons or Tags with the search '{search}'."
            )
        elif len(results) == 1 and results[0]["match"]:
            melon = session.query(Melon).filter(
                Melon.melon_id == results[0]["id"]).first()
            melon.uses += 1
            session.commit()
            await ctx.send(self.get_melon_string(ctx, search, results[0]))
        else:
            max_results = min(3, len(results))
            emojis = [
                "1\N{combining enclosing keycap}",
                "2\N{combining enclosing keycap}",
                "3\N{combining enclosing keycap}",
                "4\N{combining enclosing keycap}",
                "5\N{combining enclosing keycap}"
            ][:3]
            similar = [
                f"{emojis[i]} {results[i]['key']}" for i in range(max_results)
            ]
            keys = set()

            if results[0]["match"]:
                result = results[0]
                key = result["key"]

                similar = [
                    f"{emojis[i]} {results[i]['key']}"
                    for i in range(1, max_results)
                ]
                similar = f"\n\n**Not what you were looking for? Try** {', '.join(similar)}**.**" if similar else ""

                melon = session.query(Melon).filter(
                    Melon.melon_id == result["id"]).first()
                melon.uses += 1
                session.commit()

                keys.add(key)
                content = f"**__{key}__**\n\n{self.get_melon_string(ctx, search, result)}{similar}"
                msg = await ctx.send(content)
            else:
                similar = '\n'.join(similar)
                content = f"We couldn't find any results. Maybe you meant?\n\n{similar}\n\n*Powered by Fuzzle™.*"
                msg = await ctx.send(content)

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

            seconds = 0
            while seconds < 120:
                try:
                    time_started = datetime.now()

                    def check(r, u):
                        return u.id == ctx.author.id and r.message.id == msg.id and r.emoji in emojis

                    reaction = await self.bot.wait_for("reaction_add",
                                                       check=check,
                                                       timeout=120 - seconds)

                    j = emojis.index(reaction[0].emoji)
                    result = results[j]
                    key = result["key"]

                    similar = [
                        f"{emojis[i]} {results[i]['key']}"
                        for i in range(max_results) if i != j
                    ]
                    similar = f"\n\n**Not what you were looking for? Try** {', '.join(similar)}**.**" if similar else ""

                    if key not in keys:
                        melon = session.query(Melon).filter(
                            Melon.melon_id == result["id"]).first()
                        melon.uses += 1
                        session.commit()
                        keys.add(key)

                    content = f"**__{key}__**\n\n{self.get_melon_string(ctx, search, result)}{similar}"
                    await msg.edit(content=content)
                except asyncio.exceptions.TimeoutError:
                    pass
                except Exception as e:
                    await self.bot.send_error(e)
                finally:
                    seconds += (datetime.now() - time_started).seconds
Esempio n. 25
0
    async def addmelon(self, ctx: commands.Context, *, arg: str = ""):
        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        if arg and ctx.author.id in AUTHORIZED_USERS:
            category = session.query(Category).filter(
                func.lower(Category.name) == arg.lower()).first()
            if not category:
                msg = await ctx.send(
                    f"<{EMOJIS['XMARK']}> Category '{arg}' doesn't exist! Would you like to create it?"
                )
                await msg.add_reaction(f"<{EMOJIS['CHECK']}>")
                await msg.add_reaction(f"<{EMOJIS['XMARK']}>")

                try:
                    reaction = await bot.wait_for("reaction_add",
                                                  check=check,
                                                  timeout=2 * 60)
                    if reaction[0].custom_emoji and reaction[
                            0].emoji.id == int(EMOJIS['CHECK'].split(":")[2]):
                        category = Category(name=arg)
                        session.add(category)
                        await ctx.send(
                            f"<{EMOJIS['CHECK']}> Category '{arg}' successfully created!"
                        )
                except asyncio.exceptions.TimeoutError:
                    await ctx.send(
                        f"<{EMOJIS['XMARK']}> That took too long! " +
                        "You can restart the process by calling this command again."
                    )
                    return

            key = await self.ask_prompt(
                ctx, "❓ What should the key of the Melon be?")
            if not key:
                return
            else:
                key = key.lower()

            melon = session.query(Melon).filter(
                and_(
                    func.lower(Melon.key) == key,
                    Melon.category_id == category.category_id)).first()
            if melon:
                await ctx.send(
                    f"❗ A Melon with that key already exists in {arg}! " +
                    "You can edit it with `!editmelon`.")
                return

            await ctx.send(f"❓ What should the value of {key} be?")
            message = await self.bot.wait_for("message", check=check)

            melon = Melon(key=key,
                          category=category,
                          value=message.content,
                          created_by=ctx.author.id)
            session.add(melon)
            session.commit()

            await ctx.send(
                f"<{EMOJIS['CHECK']}> Successfully added Melon '{key}' to the global Melons!"
            )
        else:
            guild = self.bot.get_db_guild(ctx.guild.id)

            if not guild.melon_role:
                await ctx.send(
                    f"<{EMOJIS['XMARK']}> Custom Melons for this guild haven't been enabled!"
                )
                return

            roles = [role.id for role in ctx.author.roles]
            if guild.melon_role not in roles:
                await ctx.send(
                    f"<{EMOJIS['XMARK']}> You aren't authorized to edit Melons in this guild!"
                )
                return

            if not arg:
                key = await self.ask_prompt(
                    ctx, "❓ What should the key of the Melon be?")
                if not key:
                    return
                else:
                    key = key.lower()
            else:
                key = arg.lower()

            melon = session.query(Melon).filter(
                and_(
                    func.lower(Melon.key) == key,
                    Melon.guild_id == guild.guild_id)).first()
            if melon:
                await ctx.send(
                    f"❗ A Melon with that key already exists in this guild! " +
                    "You can edit it with `!editmelon`.")
                return

            await ctx.send(f"❓ What should the value of {key} be?")
            message = await self.bot.wait_for("message", check=check)

            melon = Melon(key=key,
                          guild=guild,
                          value=message.content,
                          created_by=ctx.author.id)
            session.add(melon)
            session.commit()

            await ctx.send(
                f"<{EMOJIS['CHECK']}> Successfully added Melon '{key}' to the guild Melons!"
            )
Esempio n. 26
0
    async def delmelon(self, ctx: commands.Context, *, key: str):
        guild = self.bot.get_db_guild(ctx.guild.id)

        if ctx.author.id not in AUTHORIZED_USERS:
            if not guild.melon_role:
                await ctx.send(
                    f"<{EMOJIS['XMARK']}> Custom Melons for this guild haven't been enabled!"
                )
                return

            roles = [role.id for role in ctx.author.roles]
            if guild.melon_role not in roles:
                await ctx.send(
                    f"<{EMOJIS['XMARK']}> You aren't authorized to delete Melons in this guild!"
                )
                return

        if not key:
            key = await self.ask_prompt(
                ctx, "❓ What is the key used for the Melon?")
            if not key:
                return
            else:
                key = key.lower()

        if ctx.author.id in AUTHORIZED_USERS:
            melon = session.query(Melon).filter(
                and_(
                    func.lower(Melon.key) == key,
                    or_(Melon.guild_id == guild.guild_id,
                        Melon.guild_id.is_(None)))).first()
        else:
            melon = session.query(Melon).filter(
                and_(
                    func.lower(Melon.key) == key,
                    Melon.guild_id == guild.guild_id)).first()

        if not melon:
            await ctx.send(f"<{EMOJIS['XMARK']}> Melon '{key}' doesn't exist!")
            return

        message = await ctx.send(
            f"❓ Are you sure you want to remove {melon} from the Melons?")
        await message.add_reaction(EMOJIS['CHECK'])
        await message.add_reaction(EMOJIS['XMARK'])

        try:
            reaction = await self.bot.wait_for(
                "reaction_add",
                check=lambda r, u: u.id == ctx.author.id and r.message.id ==
                message.id,
                timeout=2 * 60)
        except asyncio.exceptions.TimeoutError:
            await ctx.send(
                f"<{EMOJIS['XMARK']}> That took too long! " +
                "You can restart the process by calling this command again.")
            return
        finally:
            if reaction[0].custom_emoji and reaction[0].emoji.id == int(
                    EMOJIS['CHECK'].split(":")[2]):
                melon.delete()
                session.commit()
                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Successfully removed Melon '{melon}'!"
                )
Esempio n. 27
0
 def create(self):
     session.add(self)
     session.commit()
     return self
Esempio n. 28
0
 def delete(self):
     self.deleted = True
     session.commit()
     return self
Esempio n. 29
0
def add():
    import pdb; pdb.set_trace()
    m = Movie(**{x: y for x, y in request.form.iteritems()})
    session.add(m)
    session.commit()
    return 'Movie "%s" was added.\n' % (m.title)
Esempio n. 30
0
                    guild.role = role.id

                for member in ctx.guild.members:
                    if discord_user := session.query(DiscordUser).filter(
                            DiscordUser.user_id == member.id).first():
                        await self.bot.update_guild_user(guild, discord_user)

                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Custom roles enabled for this server!"
                )
            else:
                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Custom roles disabled for this server!"
                )

            session.commit()
        elif toggle == "nick":
            guild.custom_nick = not guild.custom_nick
            session.commit()

            if guild.custom_nick:
                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Custom nicknames enabled for this server!"
                )
            else:
                await ctx.send(
                    f"<{EMOJIS['CHECK']}> Custom nicknames disabled for this server!"
                )
        else:
            await ctx.message.channel.send(
                "❗ Invalid argument. Toggle `role`, `username` or `nick`.")