Ejemplo n.º 1
0
def incoming_message_response(data):
    debug = True

    if debug:
            
        sender = utils.is_number(data.get('From', None))
        receiver = utils.is_number(data.get('To', None))
        message = utils.clean_message(data.get('Body', None))
        sender_info = None
    else:
        sender = utils.is_number(data.values.get('From', None))
        receiver = utils.is_number(data.values.get('To', None))
        message = utils.clean_message(data.values.get('Body', None))
        sender_info = None

    if not sender:
        no_sender(receiver, message)
        return
    
    if not message:
        no_message(sender, receiver)
        return

    if not receiver:
        #Cannot text company, try to locate company by sender and send email
        no_receiver(sender, message)
        return
        
    admin = database.companies.find_one({'bot.phone':receiver})
    if not admin:
        #Reciever bot is not Registered with any company
        #Log it. Notify sender message cannot be processed
        return
    
    #Admin is sender
    
    if admin['admin'].get('phone', None) == sender:
        admin_is_sender(admin, receiver, message)
        return
    
    sender_info = database.jobs.find_one({'phone':sender})
    if sender_info:
        customer_is_sender(sender_info, receiver, admin, message)
        return
    
    for employee in admin['employees']:
        if employee.get('phone', "") == sender:
            employee_is_sender(employee, admin, receiver, message)
            return
Ejemplo n.º 2
0
def cleanUp():
    '''Delete existing session and cleanup the database'''
    global conn
    print("\nAre you SURE you want to perform a clean up?")
    print("This will STOP and DELETE any running session.")
    s = input("Type 'YES' to confirm: ")
    if (s.strip() == "YES"):
        # connect to the DB if not already connected
        connect()
        print(utils.clean_message())
        sql.clean(conn)
        end_session(2)
    else:
        print("\nNo changes made. Exiting.")
        end_session(2)
Ejemplo n.º 3
0
def prediction():
    content = {}
    content['message'] = str(session['email_msg'])

    word_list = utils.clean_message(content['message'])
    print(word_list)
    word_df = utils.make_dataframe([word_list])
    print(word_df.index[0])
    sparse_df = utils.make_sparse_matrix(word_df, word_index)
    sparse_df = np.array(sparse_df)
    full_df = nb.make_full_matrix(sparse_df, VOCAB_SIZE)
    full_df = np.array(full_df)
    output = nb.predict(full_df)
    session['status'] = output[0]
    return redirect(url_for("results"))
    return render_template('prediction.html', results=output[1])
Ejemplo n.º 4
0
 async def handle_message(self, message):
     if message.author.bot:
         return
     if message.channel.name == self.bot.config['log_channel']:
         return
     content = utils.ascii_filter(utils.clean_message(message.content))
     prediction = await ml.predict(content)  # Get prediction from API
     print(f'{message.content} - {prediction}')
     classification = prediction[0]
     score = prediction[1]
     if classification == 'notok':
         if score > 0.8:  # Delete if score is good
             await message.delete()
         await self.send_log(message, score)
     elif classification == "ok":
         if score < 0.9:
             await self.send_log(message, 0)
Ejemplo n.º 5
0
    async def channel_export(self, ctx, pdf, channel):
        """
        Takes all messages from a text channel and adds them
        to the current page of the PDF object
        """

        # Get event loop
        loop = asyncio.get_running_loop()

        pdf.set_font(*PM_FONT)
        async for message in channel.history(limit=None, oldest_first=True):
            # Name
            author = message.author.display_name.split()[0]

            # Remove emojis and out of character parts
            line = utils.clean_message(ctx, message.clean_content)

            # If string is empty after cleaning, skip
            if line == "":
                continue

            # If message looks like a command attempt, ignore it
            if utils.is_command(line):
                continue

            line = f"{author}: {line}"

            # Time remaining
            delta = message.created_at - ctx.game.start_time
            change = delta.seconds
            time = gamedata.GAME_LENGTH - change
            if time >= 0:
                # Don't display timestamp if after game has ended
                stamp = f"({utils.time_string(time)})"
                line += f" {stamp}"

            await loop.run_in_executor(None, pdf.multi_cell,
                                       *(0, MESSAGES_LINE_HEIGHT, line))
Ejemplo n.º 6
0
 def build_text_message(self):
     self.message = utils.clean_message(self.message_entity)
     self.text = utils.clean_message(self.message_entity)
     self.valid = True
Ejemplo n.º 7
0
    async def pdf(self, ctx, file_name=""):
        """Exports the game to a PDF"""

        # Start timer
        start_time = timer()

        # Get event loop
        loop = asyncio.get_running_loop()

        # Import game data
        asyncio.create_task(ctx.send(loc["pdf"]["CollectingData"]))
        try:
            await self.import_data(ctx)
        except KeyError:
            asyncio.create_task(ctx.send(loc["pdf"]["FailedImport"]))
            return

        # If data not found, tell user and quit
        if not ctx.game.start_time:
            asyncio.create_task(ctx.send(loc["pdf"]["MissingGameData"]))
            return

        # Create pdf object
        pdf = PDF(format="letter", unit="in")
        await loop.run_in_executor(None, pdf.set_auto_page_break, *(True, 1))

        # Add fonts
        await loop.run_in_executor(None, pdf.add_font,
                                   *("Built", "", str(BUILT_TITLING_RG), True))
        await loop.run_in_executor(
            None, pdf.add_font, *("Built", "sb", str(BUILT_TITLING_SB), True))
        await loop.run_in_executor(
            None, pdf.add_font, *("Built", "bd", str(BUILT_TITLING_BD), True))
        await loop.run_in_executor(None, pdf.add_font,
                                   *("Abel", "", str(ABEL_REGULAR), True))

        # Cover page
        await loop.run_in_executor(None, pdf.add_page)
        # Heading
        await loop.run_in_executor(
            None, self.heading,
            *(ctx, pdf, LOCALIZATION_DATA["title"], COVER_TITLE_FONT, "C",
              COVER_TITLE_Y))

        # Poster
        poster = utils.get_image(dirs.POSTER_DIR,
                                 f"Alice-Briarwood-{ctx.game.alice}")
        await loop.run_in_executor(
            None, pdf.image,
            *(str(poster), COVER_POSTER_X, COVER_POSTER_Y, COVER_POSTER_WIDTH))

        # Create list of player characters
        characters = [character.lower() for character in ctx.game.char_roles()]

        await ctx.send(loc["pdf"]["BuildingCharPages"])

        pm_channels = []
        for i, character in enumerate(characters):
            # Create pages for each character
            await loop.run_in_executor(None, self.generate_char_page,
                                       *(ctx, pdf, character))

            # Create list of character pairs
            for j in range(i + 1, len(characters)):
                pm_channels.append((character, characters[j]))

        await ctx.send(loc["pdf"]["RecreatingTimeline"])

        # Conclusions/timeline
        # TODO: either timeline will have to be async or it will also need
        # to be wrapped in loop.run_in_executor
        #
        # self.timeline(ctx, pdf)
        await loop.run_in_executor(None, self.conclusion_page, *(ctx, pdf))

        await ctx.send(loc["pdf"]["CollectingMessages"])

        # Group chat export
        pdf.add_page()
        await loop.run_in_executor(
            None, self.heading,
            *(ctx, pdf, loc["pdf"]["group-chat"], PM_TITLE_FONT, '',
              MESSAGES_TITLE_Y, MESSAGES_TITLE_TEXT_GAP))
        await self.channel_export(
            ctx, pdf, ctx.text_channels[LOCALIZATION_DATA["channels"]["texts"]
                                        ["group-chat"]])

        # Chat message exports
        for a, b in pm_channels:
            try:
                channel = ctx.text_channels[LOCALIZATION_DATA["channels"]
                                            ["texts"][f"{a}-{b}"]]
            except KeyError:
                # Fallback from older versions
                channel = ctx.text_channels[LOCALIZATION_DATA["channels"]
                                            ["texts"][f"pm-{a}-{b}"]]

            # Make sure channel has messages that will be counted
            empty = True
            async for message in channel.history(limit=None,
                                                 oldest_first=True):
                line = utils.clean_message(ctx, message.clean_content)

                if line:
                    empty = False
                    break

            if not empty:
                title = f"{a.title()}/{b.title()}"
                pdf.add_page()
                await loop.run_in_executor(
                    None, self.heading,
                    *(ctx, pdf, title, PM_TITLE_FONT, '', MESSAGES_TITLE_Y,
                      MESSAGES_TITLE_TEXT_GAP))

                await self.channel_export(ctx, pdf, channel)

        # Output the file
        if not file_name:
            file_name = ctx.guild.name

        out = (dirs.PDF_EXPORT_DIR / file_name).with_suffix(".pdf")
        pdf.output(str(out))

        end_time = timer()
        time = constants.TIMER_FORMAT % (end_time - start_time)
        print(f"PDF generated in {time} seconds.")

        await ctx.send(loc["pdf"]["PDFCreated"])
Ejemplo n.º 8
0
    async def import_data(self, ctx):
        """imports data from message history"""

        # Find game start
        channel = ctx.text_channels[LOCALIZATION_DATA["channels"]["texts"]
                                    ["group-chat"]]
        ctx.game.start_time = None
        async for message in channel.history(limit=None, oldest_first=True):
            # Check if first message matches
            if LOCALIZATION_DATA["stuff-for-charlie"]["first-message"][
                    0:20] in message.clean_content:
                ctx.game.start_time = message.created_at
                break

        # Couldn't find exact match, use first message in channel
        first_message = await channel.history(limit=1,
                                              oldest_first=True).flatten()

        if not first_message:
            # Channel is empty, so we quit
            return
        else:
            first_message = first_message[0]
            ctx.game.start_time = first_message.created_at

        # Alice
        channel = ctx.text_channels[LOCALIZATION_DATA["channels"]["resources"]]
        url_list = await self.channel_attachments(channel)

        for url in url_list:
            filename = self.parse_filename(url)

            if filename.startswith("alice-briarwood"):
                ctx.game.alice = int(filename.split("-")[-1])
                break

        # Clues
        for name in gamedata.CHARACTERS:
            # Create blank values to fill out
            ctx.game.clue_assignments[name] = []

            channel = ctx.text_channels[LOCALIZATION_DATA["channels"]["clues"]
                                        [name]]
            current_clue = 90
            url_list = await self.channel_attachments(channel, True)

            for url in url_list:
                filename = self.parse_filename(url)

                # Ignore character cards
                if filename in gamedata.CHARACTERS.keys():
                    continue

                # Motives
                elif filename.split("-")[0] == "motive":
                    ctx.game.motives[name] = filename.split("-")[1]

                # Suspects
                elif filename in gamedata.SUSPECTS.keys():
                    ctx.game.suspects_drawn[current_clue] = filename
                    if current_clue == 10:
                        ctx.game.second_culprit = filename

                # Locations
                elif filename in gamedata.LOCATIONS.keys():
                    ctx.game.locations_drawn[current_clue] = filename

                # Searching cards
                elif filename in gamedata.SEARCHING.keys():
                    ctx.game.searching[name].append(filename)

                # Ignore debrief card
                elif filename == "debrief":
                    pass

                # Clue cards
                else:
                    try:
                        # This will raise a ValueError if filename does not
                        # contain "-", so we catch down below
                        time, choice = [
                            num for num in filename.split("-", maxsplit=2)
                        ]

                        # Split in case of old filenames
                        choice = choice.split()[0]

                        time = int(time)
                        choice = int(choice)

                        current_clue = time
                        # If 10 minute clue card, mark ten_char
                        if time == 10:
                            ctx.game.ten_char = name

                        ctx.game.clue_assignments[name].append(time)
                        ctx.game.picked_clues[time] = choice
                    except ValueError:
                        # If still can't determine image type, log to console
                        # and ignore
                        print(
                            f"{constants.WARNING_PREFIX}Unknown image found in {name.title()}'s clues during export: {filename}"
                        )

        # Look for coin flip
        channel = ctx.text_channels[LOCALIZATION_DATA["channels"]["clues"][
            ctx.game.ten_char]]
        async for message in channel.history(limit=5):
            text = message.clean_content.strip().title()
            if text in (LOCALIZATION_DATA["flip"]["heads"],
                        LOCALIZATION_DATA["flip"]["tails"]):
                ctx.game.ending_flip = text
                break

        # Voicemails
        channel = ctx.text_channels[LOCALIZATION_DATA["channels"]
                                    ["voicemails"]]
        async for message in channel.history(limit=None, oldest_first=True):
            # Name
            character = message.author.display_name.lower().split()[0]

            # Only grab first message from each player
            if not ctx.game.voicemails[character]:
                voicemail = utils.clean_message(ctx, message.clean_content)
                ctx.game.voicemails[character] = voicemail.replace(
                    "||", "").replace("\n", "")