Exemple #1
0
async def process_message(message, is_edit=False):
    #Anime/Manga requests that are found go into separate arrays
    animeArray = []
    mangaArray = []
    lnArray = []

    #ignores all "code" markup (i.e. anything between backticks)
    cleanMessage = re.sub(r"\`(?s)(.*?)\`", "", message.clean_content)

    sender = re.search('[@]([A-Za-z0-9_-]+?)(>|}|$)', cleanMessage, re.S)

    if re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)',
                 cleanMessage, re.S) is not None and sender is not None:
        messageReply = CommentBuilder.buildStatsComment(
            username=sender.group(1))
    if re.search('({!sstats.*?}|{{!sstats.*?}}|<!sstats.*?>|<<!sstats.*?>>)',
                 cleanMessage, re.S) is not None:
        server = re.search('([A-Za-z0-9_]+?)(>|}|$)', cleanMessage, re.S)
        messageReply = CommentBuilder.buildStatsComment(server=server.group(1))
    elif re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)',
                   cleanMessage, re.S) is not None:
        messageReply = CommentBuilder.buildStatsComment()
    else:

        #The basic algorithm here is:
        #If it's an expanded request, build a reply using the data in the braces, clear the arrays, add the reply to the relevant array and ignore everything else.
        #If it's a normal request, build a reply using the data in the braces, add the reply to the relevant array.

        #Counts the number of expanded results vs total results. If it's not just a single expanded result, they all get turned into normal requests.
        numOfRequest = 0
        numOfExpandedRequest = 0
        forceNormal = False
        for match in re.finditer("\{{2}([^}]*)\}{2}|\<{2}([^>]*)\>{2}",
                                 cleanMessage, re.S):
            numOfRequest += 1
            numOfExpandedRequest += 1

        for match in re.finditer(
                "(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))|(?<=(?<!\<)\<)([^\<\>]*)(?=\>(?!\>))",
                cleanMessage, re.S):
            numOfRequest += 1

        if (numOfExpandedRequest >= 1) and (numOfRequest > 1):
            forceNormal = True

        #Expanded Anime
        for match in re.finditer("\{{2}([^}]*)\}{2}", cleanMessage, re.S):
            reply = ''
            if (forceNormal) or (str(message.channel).lower()
                                 in disableexpanded):
                reply = DiscordoragiSearch.buildAnimeReply(
                    match.group(1), message, False)
            else:
                reply = DiscordoragiSearch.buildAnimeReply(
                    match.group(1), message, True)

            if (reply is not None):
                animeArray.append(reply)

        #Normal Anime
        for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))",
                                 cleanMessage, re.S):
            reply = DiscordoragiSearch.buildAnimeReply(match.group(1), message,
                                                       False)

            if (reply is not None):
                animeArray.append(reply)

        #Expanded Manga
        #NORMAL EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}(?!(:|\>))", cleanMessage,
                                 re.S):
            reply = ''

            if (forceNormal) or (str(message.channel).lower()
                                 in disableexpanded):
                reply = DiscordoragiSearch.buildMangaReply(
                    match.group(1), message, False)
            else:
                reply = DiscordoragiSearch.buildMangaReply(
                    match.group(1), message, True)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}:\(([^)]+)\)", cleanMessage,
                                 re.S):
            reply = ''

            if (forceNormal) or (str(message.server).lower()
                                 in disableexpanded):
                reply = DiscordoragiSearch.buildMangaReplyWithAuthor(
                    match.group(1), match.group(2), message, False)
            else:
                reply = DiscordoragiSearch.buildMangaReplyWithAuthor(
                    match.group(1), match.group(2), message, True)

            if (reply is not None):
                mangaArray.append(reply)

        #Normal Manga
        #NORMAL
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]+)\>(?!(:|\>))",
                                 cleanMessage, re.S):
            reply = DiscordoragiSearch.buildMangaReply(match.group(1), message,
                                                       False)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]*)\>:\(([^)]+)\)",
                                 cleanMessage, re.S):
            reply = DiscordoragiSearch.buildMangaReplyWithAuthor(
                match.group(1), match.group(2), message, False)

            if (reply is not None):
                mangaArray.append(reply)

        #Expanded LN
        for match in re.finditer("\]{2}([^]]*)\[{2}", cleanMessage, re.S):
            reply = ''

            if (forceNormal) or (str(message.server).lower()
                                 in disableexpanded):
                reply = DiscordoragiSearch.buildLightNovelReply(
                    match.group(1), False, message)
            else:
                reply = DiscordoragiSearch.buildLightNovelReply(
                    match.group(1), True, message)

            if (reply is not None):
                lnArray.append(reply)

        #Normal LN
        for match in re.finditer("(?<=(?<!\])\])([^\]\[]*)(?=\[(?!\[))",
                                 cleanMessage, re.S):
            reply = DiscordoragiSearch.buildLightNovelReply(
                match.group(1), False, message)

            if (reply is not None):
                lnArray.append(reply)

        #Here is where we create the final reply to be posted

        #The final message reply. We add stuff to this progressively.
        messageReply = ''

        #Basically just to keep track of people posting the same title multiple times (e.g. {Nisekoi}{Nisekoi}{Nisekoi})
        postedAnimeTitles = []
        postedMangaTitles = []
        postedLNTitles = []

        #Adding all the anime to the final message. If there's manga too we split up all the paragraphs and indent them in Reddit markup by adding a '>', then recombine them
        for i, animeReply in enumerate(animeArray):
            if not (i is 0):
                messageReply += '\n\n'

            if not (animeReply['title'] in postedAnimeTitles):
                postedAnimeTitles.append(animeReply['title'])
                messageReply += animeReply['comment']

        if mangaArray:
            messageReply += '\n\n'

        #Adding all the manga to the final message
        for i, mangaReply in enumerate(mangaArray):
            if not (i is 0):
                messageReply += '\n\n'

            if not (mangaReply['title'] in postedMangaTitles):
                postedMangaTitles.append(mangaReply['title'])
                messageReply += mangaReply['comment']

        if lnArray:
            messageReply += '\n\n'

        #Adding all the manga to the final comment
        for i, lnReply in enumerate(lnArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (lnReply['title'] in postedLNTitles):
                postedLNTitles.append(lnReply['title'])
                messageReply += lnReply['comment']

        #If there are more than 10 requests, shorten them all
        if not (messageReply is '') and (len(animeArray) + len(mangaArray) >=
                                         10):
            messageReply = re.sub(r"\^\((.*?)\)", "", messageReply, flags=re.M)

    #If there was actually something found, add the signature and post the message to Reddit. Then, add the message to the "already seen" database.
    if not (messageReply is ''):
        messageReply += Config.getSignature()

        if is_edit:
            await Discord.client.send_message(message.channel, messageReply)
        else:
            try:
                print("Message created.\n")
                await Discord.client.send_message(message.channel,
                                                  messageReply)
            except discord.errors.Forbidden:
                print('Request from banned channel: ' + str(message.channel) +
                      '\n')
            except Exception:
                traceback.print_exc()

            try:
                DatabaseHandler.addMessage(message.id, message.author.id,
                                           message.server.id, True)
            except:
                traceback.print_exc()
    else:
        try:
            if is_edit:
                return None
            else:
                DatabaseHandler.addMessage(message.id, message.author.id,
                                           message.server.id, False)
        except:
            traceback.print_exc()
Exemple #2
0
def start():
    print('Starting comment stream:')

    #This opens a constant stream of comments. It will loop until there's a major error (usually this means the Reddit access token needs refreshing)
    comment_stream = praw.helpers.comment_stream(reddit, subredditlist, limit=250, verbosity=0)

    for comment in comment_stream:

        #Is the comment valid (i.e. it's not made by Roboragi and I haven't seen it already). If no, try to add it to the "already seen pile" and skip to the next comment. If yes, keep going.
        if not (Search.isValidComment(comment, reddit)):
            try:
                if not (DatabaseHandler.commentExists(comment.id)):
                    DatabaseHandler.addComment(comment.id, comment.author.name, comment.subreddit, False)
            except:
                pass
            continue

        #Anime/Manga requests that are found go into separate arrays
        animeArray = []
        mangaArray = []

        #The "hasExpandedRequest" variable puts a stop on any other requests (since you can only have one expanded request in a comment)
        hasExpandedRequest = False

        #ignores all "code" markup (i.e. anything between backticks)
        comment.body = re.sub(r"\`(?s)(.*?)\`", "", comment.body)
        
        #This checks for requests. First up we check all known tags for the !stats request
        # Assumes tag begins and ends with a whitespace OR at the string beginning/end
        if re.search('(^|\s)({!stats}|{{!stats}}|<!stats>|<<!stats>>)($|\s|.)', comment.body, re.S) is not None:
            commentReply = CommentBuilder.buildStatsComment(comment.subreddit)
        else:

            #The basic algorithm here is:
            #If it's an expanded request, build a reply using the data in the braces, clear the arrays, add the reply to the relevant array and ignore everything else.
            #If it's a normal request, build a reply using the data in the braces, add the reply to the relevant array.

            #Expanded Anime
            for match in re.finditer("\{{2}([^}]*)\}{2}", comment.body, re.S):
                if (str(comment.subreddit).lower() not in disableexpanded):
                    if hasExpandedRequest:
                        break
                    reply = Search.buildAnimeReply(match.group(1), True, comment)

                    if not (reply is None):
                        hasExpandedRequest = True
                        animeArray = [reply]
                        mangaArray = []
                else:
                    if hasExpandedRequest:
                        break
                    reply = Search.buildAnimeReply(match.group(1), False, comment)

                    if (reply is not None) and (len(animeArray) + len(mangaArray) < 10):
                        animeArray.append(reply)

            #Normal Anime  
            for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))", comment.body, re.S):
                if hasExpandedRequest:
                    break
                reply = Search.buildAnimeReply(match.group(1), False, comment)

                if (reply is not None) and (len(animeArray) + len(mangaArray) < 10):
                    animeArray.append(reply)

            #Expanded Manga
            for match in re.finditer("\<{2}([^>]*)\>{2}", comment.body, re.S):
                if (str(comment.subreddit).lower() not in disableexpanded):
                    if hasExpandedRequest:
                        break;
                    reply = Search.buildMangaReply(match.group(1), True, comment)

                    if not (reply is None):
                        hasExpandedRequest = True
                        animeArray = []
                        mangaArray = [reply]
                else:
                    if hasExpandedRequest:
                        break
                    reply = Search.buildMangaReply(match.group(1), False, comment)

                    if (reply is not None) and (len(animeArray) + len(mangaArray) < 10):
                        mangaArray.append(reply)

            #Normal Manga
            for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]*)(?=\>(?!\>))", comment.body, re.S):
                if hasExpandedRequest:
                    break
                reply = Search.buildMangaReply(match.group(1), False, comment)

                if (reply is not None) and (len(animeArray) + len(mangaArray) < 10):
                    mangaArray.append(reply)

                
            #Here is where we create the final reply to be posted

            #The final comment reply. We add stuff to this progressively.
            commentReply = ''

            #If we have anime AND manga in one reply we format stuff a little differently
            multipleTypes = False

            #Basically just to keep track of people posting the same title multiple times (e.g. {Nisekoi}{Nisekoi}{Nisekoi})
            postedAnimeTitles = []
            postedMangaTitles = []
            
            if (len(animeArray) > 0) and (len(mangaArray) > 0):
                multipleTypes = True
                commentReply += '**Anime**\n\n'

            #Adding all the anime to the final comment. If there's manga too we split up all the paragraphs and indent them in Reddit markup by adding a '>', then recombine them
            for i, animeReply in enumerate(animeArray):
                if not (i is 0):
                    commentReply += '\n\n'
                    
                if multipleTypes:
                    splitSections = re.split('\s{2,}',animeReply['comment'])
                    newSections = []
                    for section in splitSections:
                        newSections.append('>' + section)
                    animeReply['comment'] = '\n\n'.join(newSections)

                if not (animeReply['title'] in postedAnimeTitles):
                    postedAnimeTitles.append(animeReply['title'])
                    commentReply += animeReply['comment']
                

            if multipleTypes:
                commentReply += '\n\n**Manga**\n\n'

            #Adding all the manga to the final comment
            for i, mangaReply in enumerate(mangaArray):
                if not (i is 0):
                    commentReply += '\n\n'

                if multipleTypes:
                    splitSections = re.split('\s{2,}',mangaReply['comment'])
                    newSections = []
                    for section in splitSections:
                        newSections.append('>' + section)
                    mangaReply['comment'] = '\n\n'.join(newSections)
                
                if not (mangaReply['title'] in postedMangaTitles):
                    postedMangaTitles.append(mangaReply['title'])
                    commentReply += mangaReply['comment']

        #If there was actually something found, add the signature and post the comment to Reddit. Then, add the comment to the "already seen" database.
        if not (commentReply is ''):
            commentReply += '\n\n---\n\n [^How ^to ^use](http://www.reddit.com/r/Roboragi/wiki/index#wiki_how_do_i_use_it.3F) ^| ^[FAQ](http://www.reddit.com/r/Roboragi/wiki/index) ^| ^[Subreddit](http://www.reddit.com/r/Roboragi/) ^| ^[Issue/mistake?](http://www.reddit.com/r/Roboragi/submit?selftext=true&title=[ISSUE]&text=' + comment.permalink + ') ^| ^[Source](https://github.com/Nihilate/Roboragi)'

            try:
                comment.reply(commentReply)
                print("Comment made.\n")

                try:
                    DatabaseHandler.addComment(comment.id, comment.author.name, comment.subreddit, True)
                except:
                    traceback.print_exc()
            except:
                traceback.print_exc()
        else:
            try:
                DatabaseHandler.addComment(comment.id, comment.author.name, comment.subreddit, False)
            except:
                traceback.print_exc()
Exemple #3
0
def process_comment(comment, is_edit=False):
    """ process dat comment """
    # Anime/Manga requests that are found go into separate arrays
    animeArray = []
    mangaArray = []
    lnArray = []
    vnArray = []

    # ignores all "code" markup (i.e. anything between backticks)
    comment.body = re.sub(r"\`[{<\[]+(.*?)[}>\]]+\`", "", comment.body)

    num_so_far = 0

    numOfRequest = 0
    numOfExpandedRequest = 0

    # Ignore any blacklisted users
    if (comment.author.name.lower() in user_blacklist):
        print('User in blacklist: ' + comment.author.name)
        commentReply = ''
    # This checks for requests. First up we check all known tags for the !stats request
    elif re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)', comment.body, re.S) is not None:
        username = USERNAME_PATTERN.search(comment.body)
        subreddit = SUBREDDIT_PATTERN.search(comment.body)

        if username:
            commentReply = CommentBuilder.buildStatsComment(
                username=username.group(1)
            )
        elif subreddit:
            commentReply = CommentBuilder.buildStatsComment(
                subreddit=subreddit.group(1)
            )
        else:
            commentReply = CommentBuilder.buildStatsComment()
    else:

        # The basic algorithm here is:
        # If it's an expanded request, build a reply using the data in the
        # braces, clear the arrays, add the reply to the relevant array and
        # ignore everything else. If it's a normal request, build a reply using
        # the data in the braces, add the reply to the relevant array.

        # Counts the number of expanded results vs total results. If it's not
        # just a single expanded result, they all get turned into normal
        # requests.

        forceNormal = False

        for match in find_requests('all', comment.body, expanded=True):
            numOfRequest += 1
            numOfExpandedRequest += 1

        for match in find_requests('all', comment.body):
            numOfRequest += 1

        if (numOfExpandedRequest >= 1) and (numOfRequest > 1):
            forceNormal = True

        # Determine whether we'll build an expanded reply just once.
        subredditName = str(comment.subreddit).lower()
        isExpanded = False if (forceNormal or (subredditName in disableexpanded)) else True

        # The final comment reply. We add stuff to this progressively.
        commentReply = ''

        # Expanded Anime
        for match in find_requests('anime', comment.body, expanded=True):
            if num_so_far < 30:
                reply = Search.buildAnimeReply(match, isExpanded, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    animeArray.append(reply)

        # Normal Anime
        for match in find_requests('anime', comment.body):
            if num_so_far < 30:
                reply = Search.buildAnimeReply(match, False, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    animeArray.append(reply)

        # Expanded Manga
        # NORMAL EXPANDED
        for match in find_requests('manga', comment.body, expanded=True):
            if num_so_far < 30:
                reply = Search.buildMangaReply(match, isExpanded, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    mangaArray.append(reply)

        # Normal Manga
        # NORMAL
        for match in find_requests('manga', comment.body):
            if num_so_far < 30:
                reply = Search.buildMangaReply(match, False, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    mangaArray.append(reply)

        # Expanded LN
        for match in find_requests('light_novel', comment.body, expanded=True):
            if num_so_far < 30:
                reply = Search.buildLightNovelReply(match, isExpanded, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    lnArray.append(reply)

        # Normal LN
        for match in find_requests('light_novel', comment.body):
            if num_so_far < 30:
                reply = Search.buildLightNovelReply(match, False, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    lnArray.append(reply)

        # Expanded VN
        for match in find_requests('visual_novel', comment.body, expanded=True):
            if num_so_far < 30:
                reply = Search.buildVisualNovelReply(match, isExpanded, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    vnArray.append(reply)

        # Normal VN
        for match in find_requests('visual_novel', comment.body):
            if num_so_far < 30:
                reply = Search.buildVisualNovelReply(match, False, comment)

                if (reply is not None):
                    num_so_far = num_so_far + 1
                    vnArray.append(reply)

        # Here is where we create the final reply to be posted

        # Basically just to keep track of people posting the same title
        # multiple times (e.g. {Nisekoi}{Nisekoi}{Nisekoi})
        postedAnimeTitles = []
        postedMangaTitles = []
        postedLNTitles = []
        postedVNTitles = []

        # Adding all the anime to the final comment. If there's manga too we
        # split up all the paragraphs and indent them in Reddit markup by
        # adding a '>', then recombine them
        for i, animeReply in enumerate(animeArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (animeReply['title'] in postedAnimeTitles):
                postedAnimeTitles.append(animeReply['title'])
                commentReply += animeReply['comment']

        if mangaArray:
            commentReply += '\n\n'

        # Adding all the manga to the final comment
        for i, mangaReply in enumerate(mangaArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (mangaReply['title'] in postedMangaTitles):
                postedMangaTitles.append(mangaReply['title'])
                commentReply += mangaReply['comment']

        if lnArray:
            commentReply += '\n\n'

        # Adding all the light novels to the final comment
        for i, lnReply in enumerate(lnArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (lnReply['title'] in postedLNTitles):
                postedLNTitles.append(lnReply['title'])
                commentReply += lnReply['comment']

        if vnArray:
            commentReply += '\n\n'

        # Adding all the visual novels to the final comment
        for i, vnReply in enumerate(vnArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (vnReply['title'] in postedVNTitles):
                postedVNTitles.append(vnReply['title'])
                commentReply += vnReply['comment']

        # If there are more than 10 requests, shorten them all
        lenRequests = sum(map(len, (animeArray, mangaArray, lnArray, vnArray)))
        if not (commentReply is '') and (lenRequests >= 10):
            commentReply = re.sub(r"\^\((.*?)\)", "", commentReply, flags=re.M)

    # If there was actually something found, add the signature and post the
    # comment to Reddit. Then, add the comment to the "already seen" database.
    if commentReply is not '':

        if num_so_far >= 30:
            commentReply += ("\n\nI'm limited to 30 requests at once and have "
                             "had to cut off some, sorry for the "
                             "inconvenience!\n\n")

        commentReply += Config.getSignature(comment.permalink)

        commentReply += Reference.get_bling(comment.author.name)

        total_expected = int(numOfRequest)
        total_found = sum(map(len, (animeArray, mangaArray, lnArray, vnArray)))

        if total_found != total_expected:
            commentReply += '&#32;|&#32;({0}/{1})'.format(total_found,
                                                          total_expected)

        if is_edit:
            return commentReply
        else:
            try:
                comment.reply(commentReply)
                print("Comment made.\n")
            except praw.errors.Forbidden:
                print('Request from banned '
                      'subreddit: {0}\n'.format(comment.subreddit))
            except Exception as e:
                logger.debug(traceback.print_exc())
                logger.warn(e)

            comment_author = comment.author.name if comment.author else '!UNKNOWN!'

            try:
                DatabaseHandler.addComment(
                    comment.id,
                    comment_author,
                    comment.subreddit,
                    True
                )
            except Exception as e:
                logger.debug(traceback.print_exc())
                logger.warn(e)
    else:
        try:
            if is_edit:
                return None
            else:
                comment_author = comment.author.name if comment.author else '!UNKNOWN!'

                DatabaseHandler.addComment(
                    comment.id,
                    comment_author,
                    comment.subreddit,
                    False
                )
        except Exception as e:
            logger.debug(traceback.print_exc())
            logger.warn(e)
Exemple #4
0
def process_comment(comment, is_edit=False):
    #Anime/Manga requests that are found go into separate arrays
    animeArray = []
    mangaArray = []
    lnArray = []

    #ignores all "code" markup (i.e. anything between backticks)
    comment.body = re.sub(r"\`(?s)(.*?)\`", "", comment.body)
    
    #This checks for requests. First up we check all known tags for the !stats request
    if re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)', comment.body, re.S) is not None:
        username = re.search('[uU]\/([A-Za-z0-9_-]+?)(>|}|$)', comment.body, re.S)
        subreddit = re.search('[rR]\/([A-Za-z0-9_]+?)(>|}|$)', comment.body, re.S)

        if username:
            commentReply = CommentBuilder.buildStatsComment(username=username.group(1))
        elif subreddit:
            commentReply = CommentBuilder.buildStatsComment(subreddit=subreddit.group(1))
        else:
            commentReply = CommentBuilder.buildStatsComment()
    else:
        
        #The basic algorithm here is:
        #If it's an expanded request, build a reply using the data in the braces, clear the arrays, add the reply to the relevant array and ignore everything else.
        #If it's a normal request, build a reply using the data in the braces, add the reply to the relevant array.

        #Counts the number of expanded results vs total results. If it's not just a single expanded result, they all get turned into normal requests.
        numOfRequest = 0
        numOfExpandedRequest = 0
        forceNormal = False

        for match in re.finditer("\{{2}([^}]*)\}{2}|\<{2}([^>]*)\>{2}", comment.body, re.S):
            numOfRequest += 1
            numOfExpandedRequest += 1
            
        for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))|(?<=(?<!\<)\<)([^\<\>]*)(?=\>(?!\>))", comment.body, re.S):
            numOfRequest += 1

        if (numOfExpandedRequest >= 1) and (numOfRequest > 1):
            forceNormal = True

        #Expanded Anime
        for match in re.finditer("\{{2}([^}]*)\}{2}", comment.body, re.S):
            reply = ''

            if (forceNormal) or (str(comment.subreddit).lower() in disableexpanded):
                reply = Search.buildAnimeReply(match.group(1), False, comment)
            else:
                reply = Search.buildAnimeReply(match.group(1), True, comment)                    

            if (reply is not None):
                animeArray.append(reply)

        #Normal Anime  
        for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))", comment.body, re.S):
            reply = Search.buildAnimeReply(match.group(1), False, comment)
            
            if (reply is not None):
                animeArray.append(reply)

        #Expanded Manga
        #NORMAL EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}(?!(:|\>))", comment.body, re.S):
            reply = ''
            
            if (forceNormal) or (str(comment.subreddit).lower() in disableexpanded):
                reply = Search.buildMangaReply(match.group(1), False, comment)
            else:
                reply = Search.buildMangaReply(match.group(1), True, comment)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}:\(([^)]+)\)", comment.body, re.S):
            reply = ''
            
            if (forceNormal) or (str(comment.subreddit).lower() in disableexpanded):
                reply = Search.buildMangaReplyWithAuthor(match.group(1), match.group(2), False, comment)
            else:
                reply = Search.buildMangaReplyWithAuthor(match.group(1), match.group(2), True, comment)

            if (reply is not None):
                mangaArray.append(reply)

        #Normal Manga
        #NORMAL
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]+)\>(?!(:|\>))", comment.body, re.S):
            reply = Search.buildMangaReply(match.group(1), False, comment)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]*)\>:\(([^)]+)\)", comment.body, re.S):
            reply = Search.buildMangaReplyWithAuthor(match.group(1), match.group(2), False, comment)

            if (reply is not None):
                mangaArray.append(reply)

        #Expanded LN
        for match in re.finditer("\]{2}([^]]*)\[{2}", comment.body, re.S):
            reply = ''

            if (forceNormal) or (str(comment.subreddit).lower() in disableexpanded):
                reply = Search.buildLightNovelReply(match.group(1), False, comment)
            else:
                reply = Search.buildLightNovelReply(match.group(1), True, comment)                    

            if (reply is not None):
                lnArray.append(reply)

        #Normal LN  
        for match in re.finditer("(?<=(?<!\])\])([^\]\[]*)(?=\[(?!\[))", comment.body, re.S):
            reply = Search.buildLightNovelReply(match.group(1), False, comment)
            
            if (reply is not None):
                lnArray.append(reply)
            
        #Here is where we create the final reply to be posted

        #The final comment reply. We add stuff to this progressively.
        commentReply = ''

        #Basically just to keep track of people posting the same title multiple times (e.g. {Nisekoi}{Nisekoi}{Nisekoi})
        postedAnimeTitles = []
        postedMangaTitles = []
        postedLNTitles = []

        #Adding all the anime to the final comment. If there's manga too we split up all the paragraphs and indent them in Reddit markup by adding a '>', then recombine them
        for i, animeReply in enumerate(animeArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (animeReply['title'] in postedAnimeTitles):
                postedAnimeTitles.append(animeReply['title'])
                commentReply += animeReply['comment']
            

        if mangaArray:
            commentReply += '\n\n'

        #Adding all the manga to the final comment
        for i, mangaReply in enumerate(mangaArray):
            if not (i is 0):
                commentReply += '\n\n'
            
            if not (mangaReply['title'] in postedMangaTitles):
                postedMangaTitles.append(mangaReply['title'])
                commentReply += mangaReply['comment']

        if lnArray:
            commentReply += '\n\n'

        #Adding all the manga to the final comment
        for i, lnReply in enumerate(lnArray):
            if not (i is 0):
                commentReply += '\n\n'
            
            if not (lnReply['title'] in postedLNTitles):
                postedLNTitles.append(lnReply['title'])
                commentReply += lnReply['comment']

        #If there are more than 10 requests, shorten them all 
        if not (commentReply is '') and (len(animeArray) + len(mangaArray)+ len(lnArray) >= 10):
            commentReply = re.sub(r"\^\((.*?)\)", "", commentReply, flags=re.M)

    #If there was actually something found, add the signature and post the comment to Reddit. Then, add the comment to the "already seen" database.
    if commentReply is not '':
        '''if (comment.author.name == 'treborabc'):
            commentReply = '[No.](https://www.reddit.com/r/anime_irl/comments/4sba1n/anime_irl/d58xkha)'''
        
        commentReply += Config.getSignature(comment.permalink)

        commentReply += Reference.get_bling(comment.author.name)

        if is_edit:
            return commentReply
        else:
            try:
                comment.reply(commentReply)
                print("Comment made.\n")
            except praw.errors.Forbidden:
                print('Request from banned subreddit: ' + str(comment.subreddit) + '\n')
            except Exception:
                traceback.print_exc()

            try:
                DatabaseHandler.addComment(comment.id, comment.author.name, comment.subreddit, True)
            except:
                traceback.print_exc()
    else:
        try:
            if is_edit:
                return None
            else:
                DatabaseHandler.addComment(comment.id, comment.author.name, comment.subreddit, False)
        except:
            traceback.print_exc()
Exemple #5
0
def process_comment(comment, is_edit=False):
    #Anime/Manga requests that are found go into separate arrays
    animeArray = []
    mangaArray = []
    lnArray = []

    #ignores all "code" markup (i.e. anything between backticks)
    comment.body = re.sub(r"\`(?s)(.*?)\`", "", comment.body)

    #This checks for requests. First up we check all known tags for the !stats request
    if re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)',
                 comment.body, re.S) is not None:
        username = re.search('[uU]\/([A-Za-z0-9_-]+?)(>|}|$)', comment.body,
                             re.S)
        subreddit = re.search('[rR]\/([A-Za-z0-9_]+?)(>|}|$)', comment.body,
                              re.S)

        if username:
            commentReply = CommentBuilder.buildStatsComment(
                username=username.group(1))
        elif subreddit:
            commentReply = CommentBuilder.buildStatsComment(
                subreddit=subreddit.group(1))
        else:
            commentReply = CommentBuilder.buildStatsComment()
    else:

        #The basic algorithm here is:
        #If it's an expanded request, build a reply using the data in the braces, clear the arrays, add the reply to the relevant array and ignore everything else.
        #If it's a normal request, build a reply using the data in the braces, add the reply to the relevant array.

        #Counts the number of expanded results vs total results. If it's not just a single expanded result, they all get turned into normal requests.
        numOfRequest = 0
        numOfExpandedRequest = 0
        forceNormal = False

        for match in re.finditer("\{{2}([^}]*)\}{2}|\<{2}([^>]*)\>{2}",
                                 comment.body, re.S):
            numOfRequest += 1
            numOfExpandedRequest += 1

        for match in re.finditer(
                "(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))|(?<=(?<!\<)\<)([^\<\>]*)(?=\>(?!\>))",
                comment.body, re.S):
            numOfRequest += 1

        if (numOfExpandedRequest >= 1) and (numOfRequest > 1):
            forceNormal = True

        #Expanded Anime
        for match in re.finditer("\{{2}([^}]*)\}{2}", comment.body, re.S):
            reply = ''

            if (forceNormal) or (str(comment.subreddit).lower()
                                 in disableexpanded):
                reply = Search.buildAnimeReply(match.group(1), False, comment)
            else:
                reply = Search.buildAnimeReply(match.group(1), True, comment)

            if (reply is not None):
                animeArray.append(reply)

        #Normal Anime
        for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))",
                                 comment.body, re.S):
            reply = Search.buildAnimeReply(match.group(1), False, comment)

            if (reply is not None):
                animeArray.append(reply)

        #Expanded Manga
        #NORMAL EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}(?!(:|\>))", comment.body,
                                 re.S):
            reply = ''

            if (forceNormal) or (str(comment.subreddit).lower()
                                 in disableexpanded):
                reply = Search.buildMangaReply(match.group(1), False, comment)
            else:
                reply = Search.buildMangaReply(match.group(1), True, comment)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}:\(([^)]+)\)", comment.body,
                                 re.S):
            reply = ''

            if (forceNormal) or (str(comment.subreddit).lower()
                                 in disableexpanded):
                reply = Search.buildMangaReplyWithAuthor(
                    match.group(1), match.group(2), False, comment)
            else:
                reply = Search.buildMangaReplyWithAuthor(
                    match.group(1), match.group(2), True, comment)

            if (reply is not None):
                mangaArray.append(reply)

        #Normal Manga
        #NORMAL
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]+)\>(?!(:|\>))",
                                 comment.body, re.S):
            reply = Search.buildMangaReply(match.group(1), False, comment)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]*)\>:\(([^)]+)\)",
                                 comment.body, re.S):
            reply = Search.buildMangaReplyWithAuthor(match.group(1),
                                                     match.group(2), False,
                                                     comment)

            if (reply is not None):
                mangaArray.append(reply)

        #Expanded LN
        for match in re.finditer("\]{2}([^]]*)\[{2}", comment.body, re.S):
            reply = ''

            if (forceNormal) or (str(comment.subreddit).lower()
                                 in disableexpanded):
                reply = Search.buildLightNovelReply(match.group(1), False,
                                                    comment)
            else:
                reply = Search.buildLightNovelReply(match.group(1), True,
                                                    comment)

            if (reply is not None):
                lnArray.append(reply)

        #Normal LN
        for match in re.finditer("(?<=(?<!\])\])([^\]\[]*)(?=\[(?!\[))",
                                 comment.body, re.S):
            reply = Search.buildLightNovelReply(match.group(1), False, comment)

            if (reply is not None):
                lnArray.append(reply)

        #Here is where we create the final reply to be posted

        #The final comment reply. We add stuff to this progressively.
        commentReply = ''

        #Basically just to keep track of people posting the same title multiple times (e.g. {Nisekoi}{Nisekoi}{Nisekoi})
        postedAnimeTitles = []
        postedMangaTitles = []
        postedLNTitles = []

        #Adding all the anime to the final comment. If there's manga too we split up all the paragraphs and indent them in Reddit markup by adding a '>', then recombine them
        for i, animeReply in enumerate(animeArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (animeReply['title'] in postedAnimeTitles):
                postedAnimeTitles.append(animeReply['title'])
                commentReply += animeReply['comment']

        if mangaArray:
            commentReply += '\n\n'

        #Adding all the manga to the final comment
        for i, mangaReply in enumerate(mangaArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (mangaReply['title'] in postedMangaTitles):
                postedMangaTitles.append(mangaReply['title'])
                commentReply += mangaReply['comment']

        if lnArray:
            commentReply += '\n\n'

        #Adding all the manga to the final comment
        for i, lnReply in enumerate(lnArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (lnReply['title'] in postedLNTitles):
                postedLNTitles.append(lnReply['title'])
                commentReply += lnReply['comment']

        #If there are more than 10 requests, shorten them all
        if not (commentReply is '') and (
                len(animeArray) + len(mangaArray) + len(lnArray) >= 10):
            commentReply = re.sub(r"\^\((.*?)\)", "", commentReply, flags=re.M)

    #If there was actually something found, add the signature and post the comment to Reddit. Then, add the comment to the "already seen" database.
    if commentReply is not '':
        '''if (comment.author.name == 'treborabc'):
            commentReply = '[No.](https://www.reddit.com/r/anime_irl/comments/4sba1n/anime_irl/d58xkha)'''

        commentReply += Config.getSignature(comment.permalink)

        commentReply += Reference.get_bling(comment.author.name)

        if is_edit:
            return commentReply
        else:
            try:
                comment.reply(commentReply)
                print("Comment made.\n")
            except praw.errors.Forbidden:
                print('Request from banned subreddit: ' +
                      str(comment.subreddit) + '\n')
            except Exception:
                traceback.print_exc()

            try:
                DatabaseHandler.addComment(comment.id, comment.author.name,
                                           comment.subreddit, True)
            except:
                traceback.print_exc()
    else:
        try:
            if is_edit:
                return None
            else:
                DatabaseHandler.addComment(comment.id, comment.author.name,
                                           comment.subreddit, False)
        except:
            traceback.print_exc()
Exemple #6
0
async def process_message(message, is_edit=False):
    #Anime/Manga requests that are found go into separate arrays
    animeArray = []
    mangaArray = []
    lnArray = []

    #ignores all "code" markup (i.e. anything between backticks)
    cleanMessage = re.sub(r"\`(?s)(.*?)\`", "", message.clean_content)

    sender = re.search('[@]([A-Za-z0-9_-]+?)(>|}|$)', cleanMessage, re.S)
    
    if re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)', cleanMessage, re.S) is not None and sender is not None:
        messageReply = CommentBuilder.buildStatsComment(username=sender.group(1))
    if re.search('({!sstats.*?}|{{!sstats.*?}}|<!sstats.*?>|<<!sstats.*?>>)', cleanMessage, re.S) is not None:
        server = re.search('([A-Za-z0-9_]+?)(>|}|$)', cleanMessage, re.S)
        messageReply = CommentBuilder.buildStatsComment(server=server.group(1))
    elif re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)', cleanMessage, re.S) is not None:
        messageReply = CommentBuilder.buildStatsComment()
    else:
        
        #The basic algorithm here is:
        #If it's an expanded request, build a reply using the data in the braces, clear the arrays, add the reply to the relevant array and ignore everything else.
        #If it's a normal request, build a reply using the data in the braces, add the reply to the relevant array.
        
        #Counts the number of expanded results vs total results. If it's not just a single expanded result, they all get turned into normal requests.
        numOfRequest = 0
        numOfExpandedRequest = 0
        forceNormal = False
        for match in re.finditer("\{{2}([^}]*)\}{2}|\<{2}([^>]*)\>{2}", cleanMessage, re.S):
            numOfRequest += 1
            numOfExpandedRequest += 1

        for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))|(?<=(?<!\<)\<)([^\<\>]*)(?=\>(?!\>))", cleanMessage, re.S):
            numOfRequest += 1

        if (numOfExpandedRequest >= 1) and (numOfRequest > 1):
            forceNormal = True

        #Expanded Anime
        for match in re.finditer("\{{2}([^}]*)\}{2}", cleanMessage, re.S):
            reply = ''
            if (forceNormal) or (str(message.channel).lower() in disableexpanded):
                reply = DiscordoragiSearch.buildAnimeReply(match.group(1), message, False)
            else:
                reply = DiscordoragiSearch.buildAnimeReply(match.group(1), message, True)

            if (reply is not None):
                animeArray.append(reply)

        #Normal Anime
        for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))", cleanMessage, re.S):
            reply = DiscordoragiSearch.buildAnimeReply(match.group(1), message, False)

            if (reply is not None):
                animeArray.append(reply)

        #Expanded Manga
        #NORMAL EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}(?!(:|\>))", cleanMessage, re.S):
            reply = ''

            if (forceNormal) or (str(message.channel).lower() in disableexpanded):
                reply = DiscordoragiSearch.buildMangaReply(match.group(1), message, False)
            else:
                reply = DiscordoragiSearch.buildMangaReply(match.group(1), message, True)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}:\(([^)]+)\)", cleanMessage, re.S):
            reply = ''

            if (forceNormal) or (str(message.server).lower() in disableexpanded):
                reply = DiscordoragiSearch.buildMangaReplyWithAuthor(match.group(1), match.group(2), message, False)
            else:
                reply = DiscordoragiSearch.buildMangaReplyWithAuthor(match.group(1), match.group(2), message, True)

            if (reply is not None):
                mangaArray.append(reply)

        #Normal Manga
        #NORMAL
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]+)\>(?!(:|\>))", cleanMessage, re.S):
            reply = DiscordoragiSearch.buildMangaReply(match.group(1), message, False)

            if (reply is not None):
                mangaArray.append(reply)

        #AUTHOR SEARCH
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]*)\>:\(([^)]+)\)", cleanMessage, re.S):
            reply = DiscordoragiSearch.buildMangaReplyWithAuthor(match.group(1), match.group(2), message, False)

            if (reply is not None):
                mangaArray.append(reply)

        #Expanded LN
        for match in re.finditer("\]{2}([^]]*)\[{2}", cleanMessage, re.S):
            reply = ''

            if (forceNormal) or (str(message.server).lower() in disableexpanded):
                reply = DiscordoragiSearch.buildLightNovelReply(match.group(1), False, message)
            else:
                reply = DiscordoragiSearch.buildLightNovelReply(match.group(1), True, message)                    

            if (reply is not None):
                lnArray.append(reply)

        #Normal LN  
        for match in re.finditer("(?<=(?<!\])\])([^\]\[]*)(?=\[(?!\[))", cleanMessage, re.S):
            reply = DiscordoragiSearch.buildLightNovelReply(match.group(1), False, message)
            
            if (reply is not None):
                lnArray.append(reply)

        #Here is where we create the final reply to be posted

        #The final message reply. We add stuff to this progressively.
        messageReply = ''

        #Basically just to keep track of people posting the same title multiple times (e.g. {Nisekoi}{Nisekoi}{Nisekoi})
        postedAnimeTitles = []
        postedMangaTitles = []
        postedLNTitles = []

        #Adding all the anime to the final message. If there's manga too we split up all the paragraphs and indent them in Reddit markup by adding a '>', then recombine them
        for i, animeReply in enumerate(animeArray):
            if not (i is 0):
                messageReply += '\n\n'

            if not (animeReply['title'] in postedAnimeTitles):
                postedAnimeTitles.append(animeReply['title'])
                messageReply += animeReply['comment']


        if mangaArray:
            messageReply += '\n\n'

        #Adding all the manga to the final message
        for i, mangaReply in enumerate(mangaArray):
            if not (i is 0):
                messageReply += '\n\n'

            if not (mangaReply['title'] in postedMangaTitles):
                postedMangaTitles.append(mangaReply['title'])
                messageReply += mangaReply['comment']

        if lnArray:
            messageReply += '\n\n'

        #Adding all the manga to the final comment
        for i, lnReply in enumerate(lnArray):
            if not (i is 0):
                commentReply += '\n\n'
            
            if not (lnReply['title'] in postedLNTitles):
                postedLNTitles.append(lnReply['title'])
                messageReply += lnReply['comment']

        #If there are more than 10 requests, shorten them all
        if not (messageReply is '') and (len(animeArray) + len(mangaArray) >= 10):
            messageReply = re.sub(r"\^\((.*?)\)", "", messageReply, flags=re.M)

    #If there was actually something found, add the signature and post the message to Reddit. Then, add the message to the "already seen" database.
    if not (messageReply is ''):
        messageReply += Config.getSignature()

        if is_edit:
            await Discord.client.send_message(message.channel, messageReply)
        else:
            try:
                print("Message created.\n")
                await Discord.client.send_message(message.channel, messageReply)
            except discord.errors.Forbidden:
                print('Request from banned channel: ' + str(message.channel) + '\n')
            except Exception:
                traceback.print_exc()
            
            try:
                DatabaseHandler.addMessage(message.id, message.author.id, message.server.id, True)
            except:
                traceback.print_exc()
    else:
        try:
            if is_edit:
                return None
            else:
                DatabaseHandler.addMessage(message.id, message.author.id, message.server.id, False)
        except:
            traceback.print_exc()
Exemple #7
0
async def process_message(message, is_edit=False):
    #Anime/Manga requests that are found go into separate arrays
    animeArray = []
    mangaArray = []
    lnArray = []

    #Checks if bot has permissions to embed
    if message.channel.type != discord.ChannelType.private:
        canEmbed = message.channel.server.default_role.permissions.embed_links
    else:
        canEmbed = True
    if not canEmbed:
        botMember = Discord.getMemberFromID(Config.clientid, message.server)
        defaultroleperm = botMember.top_role.permissions
        canEmbed = defaultroleperm.embed_links

    isAdmin = message.author.top_role.permissions.administrator
    isServerMod = message.author.top_role.permissions.manage_server
    isOwner = message.author.id == ownerID

    if message.author.bot:
        return

    #ignores all "code" markup (i.e. anything between backticks)
    preCleanMessage = re.sub(r"\`(.*?)\`", "", message.clean_content)
    cleanMessage = re.sub(r'<:.+?:([0-9]{15,21})>', "", preCleanMessage)
    messageReply = ''

    if re.search('({!help.*?}|{{!help.*?}}|<!help.*?>|<<!help.*?>>)',
                 cleanMessage, re.S) is not None:
        try:
            localEm = CommentBuilder.buildHelpEmbed()
            await Discord.client.send_message(message.channel, embed=localEm)
            return
        except:
            return

    if re.search(
            '({!command.*?}|{{!command.*?}}|<!command.*?>|<<!command.*?>>)',
            cleanMessage, re.S) is not None:
        if 'toggleexpanded' in cleanMessage.lower() and (isAdmin
                                                         or isServerMod):
            try:
                allowedStatus = DatabaseHandler.toggleAllowExpanded(
                    message.server.id)
                print("Toggled allowExpanded for server {}".format(
                    message.server.id))
                if allowedStatus.lower() == 'true':
                    await Discord.client.send_message(
                        message.channel, "Expanded requests are now allowed.")
                else:
                    await Discord.client.send_message(
                        message.channel,
                        "Expanded requests are now disallowed.")
                return
            except Exception as e:
                print(e)
                return

        if 'addserver' in cleanMessage.lower() and (isOwner == True):
            try:
                DatabaseHandler.addServerToDatabase(message.server.id)
                await Discord.client.send_message(message.channel,
                                                  "Server has been added.")
                return
            except Exception as e:
                print(e)
                return

        else:
            print("command failed, user probably has insufficient rights")
            return

    sender = re.search('[@]([A-Za-z0-9 _-]+?)(>|}|$)', cleanMessage, re.S)
    mentionArray = message.raw_mentions
    if re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)',
                 cleanMessage, re.S) is not None and sender is not None:
        for mention in mentionArray:
            if not canEmbed:
                messageReply = CommentBuilder.buildStatsComment(
                    server=message.server, username=mention)
            else:
                localEm = CommentBuilder.buildStatsEmbed(server=message.server,
                                                         username=mention)
                await Discord.client.send_message(message.channel,
                                                  embed=localEm)
                return None
    if re.search('({!sstats}|{{!sstats}}|<!sstats>|<<!sstats>>)', cleanMessage,
                 re.S) is not None:
        if not canEmbed:
            messageReply = CommentBuilder.buildStatsComment(
                server=message.server)
        else:
            localEm = CommentBuilder.buildStatsEmbed(server=message.server)
            await Discord.client.send_message(message.channel, embed=localEm)
            return None
    elif re.search('({!stats.*?}|{{!stats.*?}}|<!stats.*?>|<<!stats.*?>>)',
                   cleanMessage, re.S) is not None:
        if not canEmbed:
            messageReply = CommentBuilder.buildStatsComment()
        else:
            localEm = CommentBuilder.buildStatsEmbed()
            await Discord.client.send_message(message.channel, embed=localEm)
            return None
    else:

        #The basic algorithm here is:
        #If it's an expanded request, build a reply using the data in the braces, clear the arrays, add the reply to the relevant array and ignore everything else.
        #If it's a normal request, build a reply using the data in the braces, add the reply to the relevant array.

        #Counts the number of expanded results vs total results. If it's not just a single expanded result, they all get turned into normal requests.
        numOfRequest = 0
        numOfExpandedRequest = 0
        forceNormal = False
        expandedAllowed = DatabaseHandler.checkServerConfig(
            'allowexpanded', message.server.id)
        if expandedAllowed == False:
            forceNormal = True
        for match in re.finditer("\{{2}([^}]*)\}{2}|\<{2}([^>]*)\>{2}",
                                 cleanMessage, re.S):
            numOfRequest += 1
            numOfExpandedRequest += 1
            print("Request found: {}".format(match.group(0)))

        for match in re.finditer(
                "(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))|(?<=(?<!\<)\<)([^\<\>]*)(?=\>(?!\>))",
                cleanMessage, re.S):
            numOfRequest += 1
            print("Request found: {}".format(match.group(0)))

        if (numOfExpandedRequest >= 1) and (numOfRequest > 1):
            forceNormal = True

        #if numOfRequest != 0:
        #await Discord.client.send_typing(message.channel)
        #Expanded Anime
        for match in re.finditer("\{{2}([^}]*)\}{2}", cleanMessage, re.S):
            reply = ''
            if match.group(1) != '':
                if (forceNormal) or (str(message.channel).lower()
                                     in disableexpanded):
                    reply = await DiscordoragiSearch.buildAnimeReply(
                        match.group(1), message, False, canEmbed)
                else:
                    reply = await DiscordoragiSearch.buildAnimeReply(
                        match.group(1), message, True, canEmbed)

                if (reply is not None):
                    animeArray.append(reply)
            else:
                print("Empty request, ignoring")

        #Normal Anime
        for match in re.finditer("(?<=(?<!\{)\{)([^\{\}]*)(?=\}(?!\}))",
                                 cleanMessage, re.S):
            if match.group(1) != '':
                reply = await DiscordoragiSearch.buildAnimeReply(
                    match.group(1), message, False, canEmbed)

                if (reply is not None):
                    animeArray.append(reply)
                else:
                    print('Could not find anime')
            else:
                print("Empty request, ignoring")

        #Expanded Manga
        #NORMAL EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}(?!(:|\>))", cleanMessage,
                                 re.S):
            if match.group(1) != '':
                reply = ''

                if (forceNormal) or (str(message.channel).lower()
                                     in disableexpanded):
                    reply = await DiscordoragiSearch.buildMangaReply(
                        match.group(1), message, False, canEmbed)
                else:
                    reply = await DiscordoragiSearch.buildMangaReply(
                        match.group(1), message, True, canEmbed)

                if (reply is not None):
                    mangaArray.append(reply)
            else:
                print("Empty request, ignoring")

        #AUTHOR SEARCH EXPANDED
        for match in re.finditer("\<{2}([^>]*)\>{2}:\(([^)]+)\)", cleanMessage,
                                 re.S):
            if match.group(1) != '':
                reply = ''

                if (forceNormal) or (str(message.server).lower()
                                     in disableexpanded):
                    reply = await DiscordoragiSearch.buildMangaReplyWithAuthor(
                        match.group(1), match.group(2), message, False,
                        canEmbed)
                else:
                    reply = await DiscordoragiSearch.buildMangaReplyWithAuthor(
                        match.group(1), match.group(2), message, True,
                        canEmbed)

                if (reply is not None):
                    mangaArray.append(reply)
            else:
                print("Empty request, ignoring")

        #Normal Manga
        #NORMAL
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]+)\>(?!(:|\>))",
                                 cleanMessage, re.S):
            if match.group(1) != '':
                reply = await DiscordoragiSearch.buildMangaReply(
                    match.group(1), message, False, canEmbed)

                if (reply is not None):
                    mangaArray.append(reply)
            else:
                print("Empty request, ignoring")

        #AUTHOR SEARCH
        for match in re.finditer("(?<=(?<!\<)\<)([^\<\>]*)\>:\(([^)]+)\)",
                                 cleanMessage, re.S):
            reply = await DiscordoragiSearch.buildMangaReplyWithAuthor(
                match.group(1), match.group(2), message, False, canEmbed)

            if (reply is not None):
                mangaArray.append(reply)

        #Expanded LN
        for match in re.finditer("\]{2}([^]]*)\[{2}", cleanMessage, re.S):
            if match.group(1) != '':
                reply = ''

                if (forceNormal) or (str(message.server).lower()
                                     in disableexpanded):
                    reply = await DiscordoragiSearch.buildLightNovelReply(
                        match.group(1), False, message, canEmbed)
                else:
                    reply = await DiscordoragiSearch.buildLightNovelReply(
                        match.group(1), True, message, canEmbed)

                if (reply is not None):
                    lnArray.append(reply)
            else:
                print("Empty request, ignoring")

        #Normal LN
        for match in re.finditer("(?<=(?<!\])\])([^\]\[]*)(?=\[(?!\[))",
                                 cleanMessage, re.S):
            if match.group(1) != '':
                reply = await DiscordoragiSearch.buildLightNovelReply(
                    match.group(1), False, message, canEmbed)

                if (reply is not None):
                    lnArray.append(reply)
            else:
                print("Empty request, ignoring")

        #Here is where we create the final reply to be posted

        #The final message reply. We add stuff to this progressively.
        postedAnimeTitles = []
        postedMangaTitles = []
        postedLNTitles = []

        messageReply = ''
        #Basically just to keep track of people posting the same title multiple times (e.g. {Nisekoi}{Nisekoi}{Nisekoi})
        postedAnimeTitles = []
        postedMangaTitles = []
        postedLNTitles = []
        #Adding all the anime to the final message. If there's manga too we split up all the paragraphs and indent them in Reddit markup by adding a '>', then recombine them
        for i, animeReply in enumerate(animeArray):
            if not (i is 0):
                messageReply += '\n\n'
            if not (animeReply['title'] in postedAnimeTitles):
                postedAnimeTitles.append(animeReply['title'])
                if not canEmbed:
                    messageReply += animeReply['comment']
                else:
                    messageReply = 'n/a'
        if mangaArray:
            messageReply += '\n\n'
        #Adding all the manga to the final message
        for i, mangaReply in enumerate(mangaArray):
            if not (i is 0):
                messageReply += '\n\n'
            if not (mangaReply['title'] in postedMangaTitles):
                postedMangaTitles.append(mangaReply['title'])
                if not canEmbed:
                    messageReply += mangaReply['comment']
                else:
                    messageReply = 'n/a'
        if lnArray:
            messageReply += '\n\n'
        #Adding all the manga to the final comment
        for i, lnReply in enumerate(lnArray):
            if not (i is 0):
                commentReply += '\n\n'

            if not (lnReply['title'] in postedLNTitles):
                postedLNTitles.append(lnReply['title'])
                if not canEmbed:
                    messageReply += lnReply['comment']
                else:
                    messageReply = 'N/A'
        #If there are more than 10 requests, shorten them all
        if not (messageReply is '') and (len(animeArray) + len(mangaArray) >=
                                         10):
            messageReply = re.sub(r"\^\((.*?)\)", "", messageReply, flags=re.M)
    #If there was actually something found, add the signature and post the message to Reddit. Then, add the message to the "already seen" database.
    if not (messageReply is ''):

        if is_edit:
            if not canEmbed:
                await Discord.client.send_message(message.channel,
                                                  messageReply)
            else:
                for i, animeReply in enumerate(animeArray):
                    await Discord.client.send_message(
                        message.channel, embed=animeReply['embed'])
                for i, mangaReply in enumerate(mangaArray):
                    await Discord.client.send_message(
                        message.channel, embed=mangaReply['embed'])
                for i, lnReply in enumerate(lnArray):
                    await Discord.client.send_message(message.channel,
                                                      embed=lnReply['embed'])
        else:
            try:
                print("Message created.\n")
                if not canEmbed:
                    await Discord.client.send_message(message.channel,
                                                      messageReply)
                else:
                    for i, animeReply in enumerate(animeArray):
                        await Discord.client.send_message(
                            message.channel, embed=animeReply['embed'])
                    for i, mangaReply in enumerate(mangaArray):
                        await Discord.client.send_message(
                            message.channel, embed=mangaReply['embed'])
                    for i, lnReply in enumerate(lnArray):
                        await Discord.client.send_message(
                            message.channel, embed=lnReply['embed'])
            except discord.errors.Forbidden:
                print('Request from banned channel: ' + str(message.channel) +
                      '\n')
            except Exception as e:
                print(e)
                traceback.print_exc()
            except:
                traceback.print_exc()
    else:
        try:
            if is_edit:
                return None
            else:
                DatabaseHandler.addMessage(message.id, message.author.id,
                                           message.server.id, False)
        except:
            traceback.print_exc()