Exemple #1
0
    async def notification(self, ctx, *args):

        prefix = await getCurrentPrefix(ctx)
        """Change confirm notif. to messages or reactions."""
        loadingEmoji = self.client.get_emoji(660250625107296256)
        okayEmoji = self.client.get_emoji(660217963911184384)
        server = str(ctx.message.guild.id)
        best.clear_cache()
        server = str(ctx.message.guild.id)
        channel = best.search(Query().serverid == server)
        if not channel:
            channelid = discord.utils.get(self.client.get_all_channels(),
                                          name='best-of')
            best.upsert(
                {
                    'serverid': server,
                    'channelid': channelid.id,
                    'notification': "message"
                },
                Query().serverid == server)
        notifmode = best.search(Query().serverid == server)
        notifmode = notifmode[0]['notification']
        notifstr = str(notifmode)
        if not args:
            await ctx.send(
                "You're currently using **" + notifstr.capitalize() +
                "** Mode.\n💠 *" + prefix + "notification message* tells " +
                botname +
                " to send a message when someone Stars/Hearts/Crushes a comment. Great for small servers, and shows the Karma that the user currently has.\n💠 *"
                + prefix +
                "notification reaction* sends a reaction when someone Stars/Hearts/Crushes a comment. Great if you don't want to have excess notifications on Mobile, but it doesn't show the Karma the user has.\n💠 *"
                + prefix +
                "notification disabled* deactivates notifications on this server - no messages or reactions when someone Stars/Hearts/Crushes a comment. This isn't recommended unless it's being used in a very heavy server, as it leaves zero feedback that their vote has been counted."
            )
        elif args[0] == "reaction" or args[0] == "reactions":
            best.update({"notification": "reaction"},
                        where('serverid') == server)
            await ctx.send(
                "*Got it!* The server will send confirmations as a reaction.\nNext time someone reacts to a comment, said message will be reacted with "
                + str(okayEmoji) + " for a couple of seconds.")
        elif args[0] == "message" or args[0] == "messages":
            best.update({"notification": "message"},
                        where('serverid') == server)
            await ctx.send(
                "*Got it!* The server will send confirmations as messages.\nNext time someone reacts to a comment, they'll be sent a message as confirmation (which will delete itself after a couple of seconds)."
            )
        elif args[0] == "disabled":
            best.update({"notification": "disabled"},
                        where('serverid') == server)
            await ctx.send(
                "*Got it!* The server will not send confirmations.\nNext time someone reacts to a comment, it will be counted, but there'll be no confirmation of it."
            )
        else:
            await sendErrorEmbed(ctx, "That's not a valid option!")
Exemple #2
0
 async def name(self, ctx, *args):
     """Get the ability to change #best-of's name!"""
     y2k = await ctx.send(
         ":arrows_counterclockwise: Looking up if you're set up already...")
     best.clear_cache()
     server = str(ctx.message.guild.id)
     channel = best.search(Query().serverid == server)
     if (channel):
         await ctx.send(":white_check_mark: **You're already set up!**")
         await ctx.send(
             "If you want to change the name of the #best-of channel, you can edit it on the Discord settings as usual!"
         )
         await y2k.delete()
     else:
         channelid = discord.utils.get(self.client.get_all_channels(),
                                       name='best-of')
         print(channelid.id)
         best.upsert(
             {
                 'serverid': server,
                 'channelid': channelid.id,
                 'notification': "message"
             },
             Query().serverid == server)
         await ctx.send(
             ":raised_hands: **You weren't set up**, so I did it for you.")
         await ctx.send(
             "If you want to change the name of the #best-of channel, you can edit it on the Discord settings as usual!"
         )
         await y2k.delete()
async def reactionAdded(bot, payload):
    if payload.guild_id is None:
        return
    User = Query()
    userid = payload.user_id
    # Misc. definitions.
    # Attempt a get_x command for brevity. If that doesn't work, use fetch_x (slow).
    user = bot.get_user(payload.user_id)
    if not user:
        user = await bot.fetch_user(payload.user_id)
        print("User not found. Trying to fetch it...")
    channel = bot.get_channel(payload.channel_id)
    if not channel:
        channel = await bot.fetch_channel(payload.channel_id)
        print("Channel not found. Trying to fetch it...")
    guild = bot.get_guild(payload.guild_id)
    if not guild:
        guild = await bot.fetch_guild(payload.guild_id)
        print("Guild not found. Trying to fetch it...")
    member = guild.get_member(payload.user_id)
    if not member:
        member = await guild.fetch_member(payload.user_id)
        print("Member not found. Trying to fetch it...")
    # no such thing as "get_message"
    message = await channel.fetch_message(payload.message_id)

    if ((userid != message.author.id) or (debug == True)) and not user.bot:
        if not isinstance(payload.emoji, str):
            # -------------------------
            #	  REACTION = :10:
            # -------------------------

            channel = message.channel
            is_nsfw = channel.is_nsfw()

            if payload.emoji.name == '10':
                if discord.utils.get(member.roles, name="Curator") is None:
                    await message.remove_reaction(payload.emoji, user)
                else:
                    channel = message.channel

                    messageurl = "https://discordapp.com/channels/" + str(
                        message.guild.id) + "/" + str(
                            message.channel.id) + "/" + str(message.id)

                    # Post the message in #best-of

                    contenido = message.content
                    autor = message.author.name
                    foto = message.author.avatar_url
                    if (len(message.attachments) > 0):
                        imagen = message.attachments[0].url

                    color = ""

                    # If there's an embed, set the color of the new embed to it. (first come, first serve)

                    if (message.embeds):
                        embed = message.embeds[0].to_dict()
                        if "color" in embed:
                            color = embed['color']
                    if color:
                        emberino = discord.Embed(description=contenido,
                                                 color=color)
                    else:
                        emberino = discord.Embed(description=contenido)

                    emberino.set_author(name=autor,
                                        url=messageurl,
                                        icon_url=foto)
                    if (len(message.attachments) > 0):
                        emberino.set_image(url=imagen)

                    # Parsing embeds:

                    if (message.embeds):
                        for embed in message.embeds:
                            embed = embed.to_dict()
                            thisEmbed = emberino.to_dict()
                            if (len(message.attachments)
                                    == 0) and not "image" in thisEmbed:
                                if "thumbnail" in embed:
                                    emberino.set_image(
                                        url=embed['thumbnail']['url'])
                                if "image" in embed:
                                    emberino.set_image(
                                        url=embed['image']['url'])
                            if not "footer" in thisEmbed:
                                if "footer" in embed:
                                    emberino.set_footer(
                                        text=embed['footer']['text'])
                                else:
                                    footer = ""
                                    if "provider" in embed:
                                        footer = embed['provider']['name']
                                    if "author" in embed and not "title" in embed:
                                        footer = embed['author']['name']
                                    if footer:
                                        emberino.set_footer(text=footer)
                            title = ""
                            description = ""
                            if "title" in embed:
                                title = embed['title']
                            elif "author" in embed:
                                title = embed['author']['name']
                            if "description" in embed:
                                description = embed['description']
                            if title and description:
                                emberino.add_field(name=title,
                                                   value=description,
                                                   inline=False)
                            if "fields" in embed:
                                for field in embed["fields"]:
                                    emberino.add_field(name=field['name'],
                                                       value=field['value'],
                                                       inline=False)

                    # the difficult challenge of finding the channel to post to

                    best.clear_cache()
                    server = str(message.guild.id)
                    channel = best.search(Query().serverid == server)

                    valuetwo = str(message.id)

                    postexists = post.search(Query().msgid == valuetwo)
                    if postexists:
                        postexists = int(postexists[0]['stars'])
                    else:
                        postexists = 0

                    if (postexists == 0):
                        try:
                            channel = channel[0][
                                'channelid']  # channel id of best-of channel
                            channel = discord.utils.get(message.guild.channels,
                                                        id=channel)
                            if channel == None:
                                channel = discord.utils.get(
                                    message.guild.channels, name="best-of")
                                if channel == None:
                                    # if the bot doesn't find a channel named best-of, the channnel has been deleted. create a new one!
                                    await message.guild.create_text_channel(
                                        'best-of')
                                    channel = discord.utils.get(
                                        message.guild.channels, name="best-of")
                                    best.upsert(
                                        {
                                            'serverid': server,
                                            'channelid': channel.id,
                                            'notification': "message"
                                        },
                                        Query().serverid == server)
                                    channelformsg = message.channel
                                    await channelformsg.send(
                                        "The *Best Of* channel doesn't exist, if the bot has permissions it has been created."
                                    )
                                    channel = best.search(
                                        Query().serverid == server)
                                    channel = channel[0]['channelid']
                                    channel = discord.utils.get(
                                        message.guild.channels, id=channel)
                                else:
                                    # if the bot does find a channel named best-of, the channel needs to be linked to the new db.
                                    # this is for legacy users (1.3.5 and below)
                                    best.upsert(
                                        {
                                            'serverid': server,
                                            'channelid': channel.id,
                                            'notification': "message"
                                        },
                                        Query().serverid == server)
                                    channel = best.search(
                                        Query().serverid == server)
                                    channel = channel[0]['channelid']
                                    channel = discord.utils.get(
                                        message.guild.channels, id=channel)
                        except IndexError:
                            channel = discord.utils.get(message.guild.channels,
                                                        name="best-of")
                            if channel == None:
                                # if the bot doesn't find a channel named best-of, the channnel has been deleted. create a new one!
                                await message.guild.create_text_channel(
                                    'best-of')
                                channel = discord.utils.get(
                                    message.guild.channels, name="best-of")
                                best.upsert(
                                    {
                                        'serverid': server,
                                        'channelid': channel.id,
                                        'notification': "message"
                                    },
                                    Query().serverid == server)
                                channelformsg = message.channel
                                await channelformsg.send(
                                    "The *Best Of* channel doesn't exist, if the bot has permissions it has been created."
                                )
                                channel = best.search(
                                    Query().serverid == server)
                                channel = channel[0]['channelid']
                                channel = discord.utils.get(
                                    message.guild.channels, id=channel)
                            else:
                                # if the bot does find a channel named best-of, the channel needs to be linked to the new db.
                                # this is for legacy users (1.3.5 and below)
                                best.upsert(
                                    {
                                        'serverid': server,
                                        'channelid': channel.id,
                                        'notification': "message"
                                    },
                                    Query().serverid == server)
                                channel = best.search(
                                    Query().serverid == server)
                                channel = channel[0]['channelid']
                                channel = discord.utils.get(
                                    message.guild.channels, id=channel)

                    # Add user to the points table
                    value = str(message.author.id)
                    exists = db.count(Query().username == value)
                    server = str(message.guild.id)
                    if exists == 0:
                        db.insert({
                            'username': value,
                            'points': 10,
                            'servers': [server]
                        })
                    else:
                        User = Query()
                        serverid = str(message.guild.id)
                        existsserver = db.count(
                            (User.servers.any([serverid])) &
                            (User.username == value))  # no funciona
                        if existsserver == 0:
                            db.update(add('points', 10),
                                      where('username') == value)
                            l = str(db.search((User.username == value)))
                            if "servers" not in l:
                                docs = db.search(User.username == value)
                                for doc in docs:
                                    doc['servers'] = [str(server)]
                                db.write_back(docs)
                            else:
                                db.update(add('servers', [server]),
                                          where('username') == value)
                        else:
                            db.update(add('points', 10),
                                      where('username') == value)

                    # Finally, the bot sends the message to the Best-Of channel.

                    if channel == None:
                        channelformsg = message.channel
                        await sendErrorEmbed(
                            channelformsg,
                            "The channel couldn't be sent to the Best Of channel, for some reason. Could you double-check it exists?"
                        )
                    else:
                        if (postexists == 0):
                            await channel.send(embed=emberino)

                    # Log post for post leaderboard

                    priv.clear_cache()
                    privSettings = priv.search(
                        Query().username == message.author.id)
                    if privSettings:
                        privSettings = privSettings[0]

                    username = str(message.author.id)
                    notifmode = best.search(Query().serverid == server)
                    notifmode = notifmode[0]['notification']

                    # ISO 8601!
                    curdate = str(datetime.now())

                    if postexists == 0:
                        if not privSettings or "mode" in privSettings and privSettings[
                                'mode'] == False or not "mode" in privSettings:
                            attachments = ""
                            if (len(message.attachments) > 0):
                                attachments = message.attachments[0].url
                            if (message.embeds):
                                richembeds = [None] * len(message.embeds)
                                i = 0
                                for embed in message.embeds:
                                    richembeds[i] = embed.to_dict()
                                    i = i + 1
                            else:
                                richembeds = ""
                            post.insert({
                                'msgid': valuetwo,
                                'username': username,
                                'points': 10,
                                'servers': server,
                                'content': message.content,
                                'embed': attachments,
                                'richembed': richembeds,
                                'voters': [user.id],
                                'stars': 1,
                                'nsfw': is_nsfw,
                                'timestamp': curdate
                            })
                        else:
                            print("Privacy Mode ENABLED!")
                    else:
                        post.update(add('points', 10),
                                    where('msgid') == valuetwo)
                        post.update(add('voters', [user.id]),
                                    where('msgid') == valuetwo)
                        post.update(add('stars', 1),
                                    where('msgid') == valuetwo)
                        if (notifmode != "reaction") and (notifmode !=
                                                          "disabled"):
                            channel = message.channel
                            result = db.get(Query()['username'] == value)
                            send = await channel.send(
                                "Huzzah! **{}**'s post was so good it got starred more than once. They now have {} points. (+10)"
                                .format(message.author.name,
                                        result.get('points')))

                    # Send a confirmation message

                    channel = message.channel
                    result = db.get(Query()['username'] == value)

                    bestofname = best.search(Query().serverid == server)
                    bestofname = bestofname[0]['channelid']
                    bestofname = discord.utils.get(message.guild.channels,
                                                   id=bestofname)

                    checkM = bot.get_emoji(660217963911184384)
                    if notifmode == "reaction":
                        react = await message.add_reaction(checkM)
                    if (notifmode != "reaction") and (
                            notifmode != "disabled") and (postexists == 0):
                        send = await channel.send(
                            "Congrats, **{}**! Your post will be forever immortalized in the **#{}** channel. You now have {} points. (+10)"
                            .format(message.author.name, bestofname.name,
                                    result.get('points')))

                    # Delete said message
                    if notifmode == "reaction":
                        await asyncio.sleep(1)
                        botid = bot.user
                        await message.remove_reaction(checkM, botid)
                    if (notifmode != "reaction") and (notifmode != "disabled"):
                        await asyncio.sleep(3)
                        await send.delete()

            # -------------------------
            #	  REACTION = :PLUS:
            # -------------------------
            if payload.emoji.name == 'plus':
                botchannel = discord.utils.get(message.guild.text_channels,
                                               name="bot-commands")
                channel = message.channel

                # Add user to the points table
                if channel != botchannel:
                    value = str(message.author.id)
                    exists = db.count(Query().username == value)
                    server = str(message.guild.id)
                    if exists == 0:
                        db.insert({
                            'username': value,
                            'points': 1,
                            'servers': [server]
                        })
                        # Send a confirmation message or reaction
                        notifmode = best.search(Query().serverid == server)
                        notifmode = notifmode[0]['notification']
                        checkM = bot.get_emoji(660217963911184384)
                        if notifmode == "reaction":
                            react = await message.add_reaction(checkM)
                        if (notifmode != "reaction") and (notifmode !=
                                                          "disabled"):
                            result = db.get(Query()['username'] == value)
                            heart = await channel.send(
                                "**Thanked!** {} now has {} thanks. (+1)".
                                format(message.author.name,
                                       result.get('points')))
                        if notifmode == "reaction":
                            await asyncio.sleep(1)
                            botid = bot.user
                            await message.remove_reaction(checkM, botid)
                        if (notifmode != "reaction") and (notifmode !=
                                                          "disabled"):
                            await asyncio.sleep(3)
                            await heart.delete()
                    else:
                        User = Query()
                        serverid = str(message.guild.id)
                        existsserver = db.count(
                            (User.servers.any([serverid])) &
                            (User.username == value))  # no funciona
                        print(str(existsserver))
                        if existsserver == 0:
                            db.update(add('points', 1),
                                      where('username') == value)
                            l = str(db.search((User.username == value)))
                            print(l)
                            if "servers" not in l:
                                docs = db.search(User.username == value)
                                for doc in docs:
                                    doc['servers'] = [str(server)]
                                db.write_back(docs)
                            else:
                                db.update(add('servers', [server]),
                                          where('username') == value)
                        else:
                            db.update(add('points', 1),
                                      where('username') == value)

                        # Log post for post leaderboard

                        priv.clear_cache()
                        privSettings = priv.search(
                            Query().username == message.author.id)
                        if privSettings:
                            privSettings = privSettings[0]

                        valuetwo = str(message.id)
                        username = str(message.author.id)
                        postexists = post.count(Query().msgid == valuetwo)

                        # ISO 8601!
                        curdate = str(datetime.now())

                        if postexists == 0:
                            if not privSettings or "mode" in privSettings and privSettings[
                                    'mode'] == False or not "mode" in privSettings:
                                attachments = ""
                                if (len(message.attachments) > 0):
                                    attachments = message.attachments[0].url
                                if (message.embeds):
                                    richembeds = [None] * len(message.embeds)
                                    i = 0
                                    for embed in message.embeds:
                                        richembeds[i] = embed.to_dict()
                                        i = i + 1
                                else:
                                    richembeds = ""
                                post.insert({
                                    'msgid': valuetwo,
                                    'username': username,
                                    'points': 1,
                                    'servers': server,
                                    'content': message.content,
                                    'embed': attachments,
                                    'richembed': richembeds,
                                    'voters': [user.id],
                                    'stars': 0,
                                    'nsfw': is_nsfw,
                                    'timestamp': curdate
                                })
                            else:
                                print("Privacy Mode ENABLED!")
                        else:
                            post.update(add('points', 1),
                                        where('msgid') == valuetwo)
                            post.update(add('voters', [user.id]),
                                        where('msgid') == valuetwo)

                        best.clear_cache()
                        notifmode = best.search(Query().serverid == server)
                        notifmode = notifmode[0]['notification']
                        checkM = bot.get_emoji(660217963911184384)
                        if notifmode == "reaction":
                            react = await message.add_reaction(checkM)
                        if (notifmode != "reaction") and (notifmode !=
                                                          "disabled"):
                            result = db.get(Query()['username'] == value)
                            heart = await channel.send(
                                "**Thanked!** {} now has {} thanks. (+1)".
                                format(message.author.name,
                                       result.get('points')))

                        # Delete said message
                        if notifmode == "reaction":
                            await asyncio.sleep(1)
                            botid = bot.user
                            await message.remove_reaction(checkM, botid)
                        if (notifmode != "reaction") and (notifmode !=
                                                          "disabled"):
                            await asyncio.sleep(3)
                            await heart.delete()
                else:
                    print("in bot-commands cannot read")
async def reactionRemoved(bot, payload):
    if payload.guild_id is None:
        return
    User = Query()
    userid = payload.user_id

    # Misc. definitions.
    # Attempt a get_x command for brevity. If that doesn't work, use fetch_x (slow).
    user = bot.get_user(payload.user_id)
    if not user:
        user = await bot.fetch_user(payload.user_id)
        print("User not found. Trying to fetch it...")
    channel = bot.get_channel(payload.channel_id)
    if not channel:
        channel = await bot.fetch_channel(payload.channel_id)
        print("Channel not found. Trying to fetch it...")
    guild = bot.get_guild(payload.guild_id)
    if not guild:
        guild = await bot.fetch_guild(payload.guild_id)
        print("Guild not found. Trying to fetch it...")
    member = guild.get_member(payload.user_id)
    if not member:
        member = await guild.fetch_member(payload.user_id)
        print("Member not found. Trying to fetch it...")
    # no such thing as "get_message"
    message = await channel.fetch_message(payload.message_id)

    if ((userid != message.author.id) or (debug == True)) and not user.bot:
        if not isinstance(payload.emoji, str):

            channel = message.channel

            removable = None
            if payload.emoji.name == '10':
                # the bot auto-removes stars given out by non-curators.
                # if this is from a non-curator, ignore all this code! otherwise we're just removing points without adding them first.
                if discord.utils.get(member.roles, name="Curator") is None:
                    return
                removable = 10
            if payload.emoji.name == 'plus':
                removable = 1
            if payload.emoji.name == 'minus':
                removable = -1

            if removable:
                # Remove the user's karma.
                value = message.author.id
                exists = db.count(Query().username == str(value))
                if not (exists == 0):
                    db.update(subtract('points', removable),
                              where('username') == str(value))
                # Remove the comment's karma.
                valuetwo = str(message.id)
                postexists = post.count(Query().msgid == str(valuetwo))
                if not (postexists == 0):
                    post.update(subtract('points', removable),
                                where('msgid') == str(valuetwo))
                    #post.update(subtract('voters',[user.id]), where('msgid') == str(valuetwo))
                    if payload.emoji.name == '10':
                        post.update(subtract('stars', 1),
                                    where('msgid') == str(valuetwo))

                # todo (if possible): remove the message from the best of channel if there are 0 :10: reactions

                # we shouldn't send a message if someone un-reacted, that'd be mean.
                # instead, we send a reaction unless notifications are disabled
                server = str(message.guild.id)
                checkM = bot.get_emoji(660217963911184384)
                notifmode = best.search(Query().serverid == server)
                notifmode = notifmode[0]['notification']
                if notifmode != "disabled":
                    react = await message.add_reaction(checkM)
                    await asyncio.sleep(1)
                    botid = bot.user
                    await message.remove_reaction(checkM, botid)