Example #1
0
    async def commentDeleter(self):
        # Running Reto in an unverified bot (100 servers or less)? You can get rid of this function.
        if self.isDeletingComments == False and self.isFirstTime == False:
            print(
                "Running the COMMENT DELETER...\nThis checks every 12 hours for saved comments that are 30 days old and deletes them from the comments.reto file,\nper Discord's verification rules. Do not stop "
                + botname + " while this is running!")
            postLength = len(post)
            self.isDeletingComments = True  # Don't run it twice at the same time!
            i = 0
            totalDeleted = 0
            for postelement in post:
                i = i + 1
                print("Scanning the comments... (" + str(i) + "/" +
                      str(postLength) + ")",
                      end="\r")
                if not "timestamp" in postelement:
                    post.update({"timestamp": str(datetime.now())},
                                where('msgid') == postelement['msgid'])
                    postelement['timestamp'] = str(datetime.now())
                parsedTimestamp = datetime.strptime(postelement['timestamp'],
                                                    '%Y-%m-%d %H:%M:%S.%f')
                delta = datetime.now() - parsedTimestamp

                # permastorage
                privSettings = priv.search(
                    Query().username == int(postelement['username']))
                if privSettings:
                    privSettings = privSettings[0]
                if not privSettings or "storage" in privSettings and privSettings[
                        'storage'] == False or not "storage" in privSettings:
                    if delta.days >= 30:
                        totalDeleted = totalDeleted + 1
                        post.remove(where('msgid') == postelement['msgid'])
            print("\nAll set! " + str(totalDeleted) +
                  " comments were deleted.\n")
            self.isDeletingComments = False
        self.isFirstTime = False
Example #2
0
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")
Example #3
0
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)