def test_find_movies_closest_to_title():
    print("Testing find_movies_closest_to_title() functionality...")
    chatbot = Chatbot(True)

    # add more test cases here!!!
    test_cases = [
        ('Sleeping Beaty', [1656]),
        ('Te', [8082, 4511, 1664]),
        ('BAT-MAAAN', [524, 5743]),
        ('Blargdeblargh', []),
    ]

    tests_passed = True
    for input_text, expected_output in test_cases:
        if not assertListEquals(
                chatbot.find_movies_closest_to_title(
                    chatbot.preprocess(input_text)),
                expected_output,
                "Incorrect output for find_movies_closest_to_title(chatbot.preprocess('{}'))."
                .format(input_text),
                orderMatters=False):
            tests_passed = False
    if tests_passed:
        print('find_movies_closest_to_title() sanity check passed!')
    print()
    return True
Beispiel #2
0
def test():
    dataset = CornellMovieDialogs(data_directory="data/",
                                  vocabulary_size=20000)
    if not os.path.exists("data/cleaned"):
        dataset.make_conversations()
    else:
        dataset.load()

    bot = Chatbot(sequence_length=20,
                  hidden_size=256,
                  vocabulary_size=dataset.vocabulary_size)
    bot.load("models/checkpoints/checkpoint.h5")
    while True:
        print(">>>", end="")
        sentence = raw_input()
        sentence = dataset.clean(sentence)
        sentence = dataset.encode_sequence(sentence)
        sentence = sequence.pad_sequences([sentence],
                                          maxlen=bot.sequence_length)
        for t in [.7, .8, .9]:
            response = bot.respond(sentence, temperature=t)
            print(response)
            response = dataset.decode_sequence(response)
            start_index = response.index(
                "START") + 1 if "START" in response else 0
            end_index = response.index("END") if "END" in response else len(
                response)
            response = response[start_index:end_index]
            print(" ".join(response))
def test_extract_titles():
    print("Testing extract_titles() functionality...")
    chatbot = Chatbot(False)

    # add more test cases here!!!
    test_cases = [
        ('I liked "The Notebook"', ["The Notebook"]),
        ('You are a great bot!', []),
        ('I enjoyed "Titanic (1997)" and "Scream 2 (1997)"',
         ["Titanic (1997)", "Scream 2 (1997)"]),
    ]

    tests_passed = True
    for input_text, expected_output in test_cases:
        if not assert_list_equals(
                chatbot.extract_titles(chatbot.preprocess(input_text)),
                expected_output,
                "Incorrect output for extract_titles("
                "chatbot.preprocess('{}')).".format(
                    input_text),
                orderMatters=False
        ):
            tests_passed = False
    if tests_passed:
        print('extract_titles() sanity check passed!')
    print()
Beispiel #4
0
class Main():
    def __init__(self) -> None:
        # Configurando o chatbot
        self.update()

    def update(self) -> None:
        # Criando os objetos do bot
        self.data = Database()
        self.bot = Chatbot(self.data)

    def start(self) -> None or int:
        # Função principal do loop:

        # Pega o input do usuario e verifica a decisao de saida
        user_input = str(input('>> '))
        if user_input == 'sair':
            return 1

        # Pegando a resposta vinda do bot
        answer = self.bot.reply(user_input)

        # Verificando se o bot realmente achou a resposta
        # Se sim ele retornara uma string com a resposta
        # Se não ele retorna uma lista com uma resposta aleatoria e com a ultima posisão True
        if answer[-1] != True:
            print(answer)
        else:
            print(answer[0])
            sleep(1)
            print(user_input + '?')

            # Adicionando a nova pergunta ao banco e atualizando os dados
            self.bot.add(user_input, str(input('>> ')))
            self.update()
 def __call__(self, environ, start_response):
     """
     WSGI application implementing a simple chat protocol.
     On a GET request, serve the chat interface.  On a POST, pass
     the input to the chatbot and return its response as text.
     """
     method = environ['REQUEST_METHOD']
     if method == 'GET':
         session_id = str(uuid.uuid4())
         # Start a new conversation
         chatbot = Chatbot(self.db, self.logger, enable_debug=False)
         greeting = chatbot.get_greeting()
         # Save the chatbot in the key-value store
         self._save_chatbot(chatbot, session_id)
         # Return HTML of chat interface
         start_response('200 OK', [('content-type', 'text/html')])
         template = open('chat_interface.html').read()
         template = template.replace("{{SESSION_ID}}", session_id)
         template = template.replace("{{OUTPUT}}", greeting)
         return (template, )
     elif method == 'POST':
         # Get form data
         length = int(environ.get('CONTENT_LENGTH', '0'))
         post = urlparse.parse_qs(environ['wsgi.input'].read(length))
         session_id = post['session_id'][0]
         chat_message = post['chat_message'][0]
         # Load the saved state
         chatbot = self._load_chatbot(session_id)
         # Get the bot's output
         output = chatbot.handle_input(chat_message)
         # Save the chatbot in the key-value store
         self._save_chatbot(chatbot, session_id)
         # Return the output as text
         start_response('200 OK', [('content-type', 'text/plain')])
         return (output, )
def test_find_movies_by_title():
    print("Testing find_movies_by_title() functionality...")
    chatbot = Chatbot(False)

    # add more test cases here!!!
    test_cases = [
        ('The American President', [10]),
        ('Titanic', [1359, 2716]),
        ('Titanic (1997)', [1359]),
        ('An American in Paris (1951)', [721]),
        ('The Notebook (1220)', []),
        ('Scream', [1142]),
    ]

    tests_passed = True
    for input_text, expected_output in test_cases:
        if not assert_list_equals(
                chatbot.find_movies_by_title(input_text),
                expected_output,
                "Incorrect output for find_movies_by_title('{}').".format(
                    input_text),
                orderMatters=False
        ):
            tests_passed = False
    if tests_passed:
        print('find_movies_by_title() sanity check passed!')
    print()
Beispiel #7
0
def test_find_movies_closest_to_title():
    print("Testing find_movies_closest_to_title() functionality...")
    chatbot = Chatbot(True)

    # add more test cases here!!!
    test_cases = [('Sleeping Beaty', [1656]), ('Te', [8082, 4511, 1664]),
                  ('BAT-MAAAN', [524, 5743]), ('Blargdeblargh', []),
                  ('The Notebok', [5448]),
                  ('An Awfully Big Advventuree', [127]),
                  ('An Amrican in Paris', [721]),
                  ('The Cellloid Closet', [516]), ('Titanc', [2716, 1359])]

    tests_passed = True
    for input_text, expected_output in test_cases:
        if not assert_list_equals(
                chatbot.find_movies_closest_to_title(input_text),
                expected_output,
                "Incorrect output for find_movies_closest_to_title("
                "chatbot.preprocess('{}')).".format(input_text),
                orderMatters=False):
            tests_passed = False
    if tests_passed:
        print('find_movies_closest_to_title() sanity check passed!')
    print()
    return True
def test_extract_sentiment():
    print("Testing extract_sentiment() functionality...")
    chatbot = Chatbot(False)

    # add more test cases here!!!
    test_cases = [
        ('I like "Titanic (1997)".', 1),
        ('I saw "Titanic (1997)".', 0),
        ('I didn\'t enjoy "Titanic (1997)".', -1),
        ('I didn\'t really like "Titanic (1997)".', -1),
        ('I never liked "Titanic (1997)".', -1),
        ('I really enjoyed "Titanic (1997)".', 1),
        ('"Titanic (1997)" started out terrible, but the ending was totally great and I loved it!',
         1),
        ('I loved "10 Things I Hate About You"', 1),
    ]

    tests_passed = True
    for input_text, expected_output in test_cases:
        if not assertEquals(
                chatbot.extract_sentiment(
                    chatbot.preprocess(input_text)), expected_output,
                "Incorrect output for extract_sentiment(chatbot.preprocess('{}'))."
                .format(input_text)):
            tests_passed = False
    if tests_passed:
        print('extract_sentiment() sanity check passed!')
    print()
def getResponse(input_statement):
    from chatbot import Chatbot
    bot = Chatbot()

    with open(answers_json) as ans:
        ans_json = json.load(ans)

    input_statement = re.sub(r'[^a-zA-Z0-9-:.@/ ]', '',
                             input_statement).strip()
    input_statement = ' '.join(input_statement.split())

    bucket, sub_bucket, _, _ = extract_buckets(input_statement.lower())
    reply = bot.get_response(input_statement)
    print("reply ---- {}".format(reply))

    if bucket and sub_bucket:
        reply = reply
    elif bucket and not sub_bucket:
        reply = reply
    elif not bucket and sub_bucket:
        reply = ""
    else:
        reply = ""

    reply = str(reply)
    if not reply:
        suggestions = ""
    else:
        suggestions = ans_json[reply]["category"]
    replyJson = {"suggestions": suggestions}
    return replyJson
def test_recommend():
    print("Testing recommend() functionality...")
    chatbot = Chatbot(False)

    user_ratings = np.array([1, -1, 0, 0, 0, 0])
    all_ratings = np.array([
        [1, 1, 1, 0],
        [1, -1, 0, -1],
        [1, 1, 1, 0],
        [0, 1, 1, -1],
        [0, -1, 1, -1],
        [-1, -1, -1, 0],
    ])
    small_recommendations = chatbot.recommend(user_ratings, all_ratings, 2)
    user_ratings = np.zeros(9125)
    user_ratings[[8514, 7953, 6979, 7890]] = 1
    user_ratings[[7369, 8726]] = -1
    recommendations = chatbot.recommend(user_ratings, chatbot.ratings, k=5)

    test_cases = [
        (small_recommendations, [2, 3]),
        (recommendations, [8582, 8596, 8786, 8309, 8637]),
    ]

    tests_passed = True
    for i, (recs, expected_output) in enumerate(test_cases):
        if not assertListEquals(
                recs,
                expected_output,
                "Test case #{} for recommender tests failed".format(i),
        ):
            tests_passed = False
    if tests_passed:
        print('recommend() sanity check passed!')
    print()
Beispiel #11
0
def test_disambiguate():
    print("Testing disambiguate() functionality...")
    chatbot = Chatbot(True)

    # clarification = "2"
    # candidates = [3812, 4325, 5399, 6294, 6735, 7274, 7670, 7842]
    # if assertListEquals(
    #     chatbot.disambiguate(clarification, candidates),
    #     [4325],
    #     "Incorrect output for disambiguate('{}', {})".format(clarification, candidates),
    #     orderMatters=False
    # ):

    # clarification = "Sorcerer's Stone"
    # candidates = [3812, 4325, 5399, 6294, 6735, 7274, 7670, 7842]
    # if assertListEquals(
    #     chatbot.disambiguate(clarification, candidates),
    #     [3812],
    #     "Incorrect output for disambiguate('{}', {})".format(clarification, candidates),
    #     orderMatters=False
    # ):

    clarification = "1997"
    candidates = [1359, 2716]
    if assertListEquals(
        chatbot.disambiguate(clarification, candidates),
        [1359],
        "Incorrect output for disambiguate('{}', {})".format(clarification, candidates),
        orderMatters=False
    ):
        print('disambiguate() sanity check passed!')
    print()
    return True
def test_disambiguate():
    print("Testing disambiguate() functionality...")
    chatbot = Chatbot(True)

    # add more test cases here!!!
    test_cases = [
        ('1997', [1359, 2716], [1359]),
        ('2', [1142, 1357, 2629, 546], [1357]),
        ('Sorcerer\'s Stone', [3812, 4325, 5399, 6294, 6735, 7274, 7670,
                               7842], [3812]),
    ]

    tests_passed = True
    for clarification, candidates, expected_output in test_cases:
        if not assertListEquals(
                chatbot.disambiguate(clarification, candidates),
                expected_output,
                "Incorrect output for disambiguate('{}', {})".format(
                    clarification, candidates),
                orderMatters=False):
            tests_passed = False
    if tests_passed:
        print('disambiguate() sanity check passed!')
    print()
    return True
Beispiel #13
0
def index():

    chatbot_label = "Hallo. Worüber wollen Sie sprechen?"

    # Listen
    zufallsantworten = [
        "Oh wirklich...", "Interessant", "Das kann man so sehen.",
        "Ich verstehe..."
    ]
    reaktionen = {
        "hallo": "aber hallo",
        "geht": "Was verstehst Du darunter",
        "schmeckt": "Ich habe keinen Geschmackssinn"
    }

    if request.method == 'POST':
        chatbot_input = request.form['chatbot_input']
        if not chatbot_input:
            flash('Ohne Frage kann ich nicht antworten!')
        else:
            bot = Chatbot(reaktionen, zufallsantworten)
            bot.set_Message(chatbot_input)
            chatbot_label = bot.get_response()

    return render_template('chatbot.html', chatbot_label=chatbot_label)
Beispiel #14
0
def ask():

    data = request.get_json()

    if not data:
        return jsonify({"message": "No payload received"}), 400
    if ("message" not in data):
        return jsonify({"message": "please specify a message"}), 400

    if ("current_context" not in data):
        current_context = None
    else:
        current_context = data["current_context"]

    chatbot = Chatbot(sensitivity=0.4)
    chatbot.load()
    '''
    chatbot.add_action("NutrizionistaCittaIntent", search_nutritionists)
    chatbot.add_action("DietistaCittaIntent", search_dietisti)
    chatbot.add_action("DietologoCittaIntent", search_dietologi)
    '''
    answer = chatbot.ask(data["message"],
                         current_context=current_context,
                         return_proba=True)

    return jsonify({
        "answer": str(answer[0]),
        "new_context": str(answer[1]),
        "probability": str(answer[2])
    }), 200
def test_disambiguate_complex():
    print("Testing complex disambiguate() functionality...")
    chatbot = Chatbot(True)

    # add more test cases here!!!
    test_cases = [
        ('2', [8082, 4511, 1664], [4511]),
        ('most recent', [524, 5743], [1524]),
        ('the Goblet of Fire one',
         [3812, 4325, 5399, 6294, 6735, 7274, 7670, 7842], [6294]),
        ('the second one', [3812, 6294, 4325, 5399, 6735, 7274, 7670,
                            7842], [6294]),
    ]

    tests_passed = True
    for clarification, candidates, expected_output in test_cases:
        if not assertListEquals(
                chatbot.disambiguate(clarification, candidates),
                expected_output,
                "Incorrect output for complex disambiguate('{}', {})".format(
                    clarification, candidates),
                orderMatters=False):
            tests_passed = False
    if tests_passed:
        print('complex disambiguate() sanity check passed!')
    print()
    return True
def main():
    """
    Main loop for the command line interface.
    """
    (options, args) = PARSER.parse_args()
    # Configure logging
    logging.basicConfig(filename=options.log_filename, level=logging.DEBUG,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    logging.getLogger('py4j.java_gateway').setLevel(logging.INFO)
    # These imports are performed after the logging setup because basicConfig
    # will not work if other modules call logging functions before it's called.
    from chatbot import Chatbot
    from database import Database
    # Setup the database
    db = Database(options.database_url)
    # Setup the chatbot
    logger = logging.getLogger('chatbot')
    bot = Chatbot(db, logger)
    greeting = bot.get_greeting()

    print greeting
    while 1:
        # Chatbot instances should not call exit() themselves.
        # If they need to exit, they should signal so, not exit
        # themselves.
        PROMPT = bot.prompt # prompt from chatbot, shows mode: creative/regular
        try:
            user_input = raw_input(PROMPT)
        except EOFError:
            return
        bot_output = bot.handle_input(user_input)
        print bot_output
def test_extract_sentiment_for_movies():
    print("Testing test_extract_sentiment_for_movies() functionality...")
    chatbot = Chatbot(True)

    # add more test cases here!!!
    test_cases = [
        ('I liked both "I, Robot" and "Ex Machina".', [("I, Robot", 1),
                                                       ("Ex Machina", 1)]),
        ('I liked "I, Robot" but not "Ex Machina".', [("I, Robot", 1),
                                                      ("Ex Machina", -1)]),
        ('I didn\'t like either "I, Robot" or "Ex Machina".',
         [("I, Robot", -1), ("Ex Machina", -1)]),
        ('I liked "Titanic (1997)", but "Ex Machina" was not good.',
         [("Titanic (1997)", 1), ("Ex Machina", -1)]),
    ]

    tests_passed = True
    for input_text, expected_output in test_cases:
        if not assertListEquals(
                chatbot.extract_sentiment_for_movies(
                    chatbot.preprocess(input_text)),
                expected_output,
                "Incorrect output for extract_sentiment_for_movies(chatbot.preprocess('{}'))."
                .format(input_text),
                orderMatters=False):
            tests_passed = False
    if tests_passed:
        print('extract_sentiment_for_movies() sanity check passed!')
    print()
Beispiel #18
0
def main():
    chatbot = Chatbot()

    print('BOT: Olá querido usuário!')
    print(
        'BOT: Fico a disposição para responder perguntas sobre mercado, saúde, tecnologia e telefonia.'
    )
    print('BOT: Diga tchau quando encerrar!')

    stop = False

    while not stop:
        user_request = input('Pergunta: ')
        user_request = user_request.lower()

        if user_request != 'tchau':
            if user_request == 'obrigado' or user_request == 'muito obrigado':
                stop = True
                print("BOT: Não há de quê!")
            else:
                if chatbot.greeting(user_request) != '':
                    print("BOT:", chatbot.greeting(user_request))
                else:
                    print("BOT: Pensando...")
                    start_time = time.perf_counter()
                    response = chatbot.response(user_request)
                    end_time = time.perf_counter()
                    print("BOT:", response)
                    print('[{:.1f} segundos]'.format(end_time - start_time))
        else:
            stop = True
            print("BOT: Até mais!")
def test_binarize():
    print("Testing binarize() functionality...")
    chatbot = Chatbot(False)
    if assertNumpyArrayEquals(
            chatbot.binarize(np.array([[1, 2.5, 5, 0]])),
            np.array([[-1., -1., 1., 0.]]),
            "Incorrect output for binarize(np.array([[1, 2.5, 5, 0]]))."):
        print("binarize() sanity check passed!")
    print()
Beispiel #20
0
 def reply_messages(msg):
     print(msg)
     sender = msg.sender
     global chatbots
     if sender in chatbots:
         sender.send(chatbots[sender].respond(msg.text))
     else:
         chatbot = Chatbot(interpreter)
         chatbots[sender] = chatbot
         sender.send(chatbot.greet())
Beispiel #21
0
    def __init__(self, creative=False):
        super().__init__()

        self.chatbot = Chatbot(creative=creative)
        self.name = self.chatbot.name
        self.bot_prompt = '\001\033[96m\002%s> \001\033[0m\002' % self.name

        self.greeting = self.chatbot.greeting()
        self.intro = self.chatbot.intro() + '\n' + self.bot_prompt + self.greeting
        self.debug = False
class ChatbotTest(unittest.TestCase):
    def setUp(self):
        path = os.path.join(os.path.dirname(__file__), "chatbot_messages.csv")
        self.chatbot = Chatbot(path, "Tanay Agarwal")

    def testSimilarityMetric(self):
        self.assertEqual(1.0, self.chatbot.similarity("hello", "hello"))
        self.assertEqual(1.0, self.chatbot.similarity("hello my name is tanay", "hello my Name is TANAY"))
        self.assertEqual(3.0/5.0, self.chatbot.similarity("my name is Tanay", "my name is Manyu"))
        self.assertEqual(4.0/5.0, self.chatbot.similarity("my name is Tanay", "My name is Not Tanay"))
        self.assertEqual(0.0, self.chatbot.similarity("where are we", "not here"))

    def testClosestMatch(self):
        message, sender, date = self.chatbot.get_closest_match("yeah")
        self.assertEqual(message, "yeah")
        self.assertEqual(sender, "Michael Borger")
        message, sender, date = self.chatbot.get_closest_match("you can sign up")
        self.assertTrue(message in ["you can sign up with me", "you already signed up?", "thank you hahahahah"])
        self.assertEqual(sender, "Michael Borger")

    def testGetResponse(self):
        message = self.chatbot.get_response("yeah")
        self.assertTrue(message in ["damn", "alright", "im in also"])
        message = self.chatbot.get_response("you can sign up")
        self.assertTrue(message in ["ok", "thank you hahahahah", "when can i get the thing"])
Beispiel #23
0
def test_extract_sentiment():
    print("Testing extract_sentiment() functionality...")
    chatbot = Chatbot(False)
    if assertEquals(
            chatbot.extract_sentiment("I like \"Titanic (1997)\"."), 1,
            "Incorrect output for extract_sentiment(\'I like \"Titanic (1997)\".\')"
    ) and assertEquals(
            chatbot.extract_sentiment("I saw \"Titanic (1997)\"."), 0,
            "Incorrect output for extract_sentiment(\'I saw  \"Titanic (1997)\".\')"
    ) and assertEquals(
            chatbot.extract_sentiment("I didn't enjoy \"Titanic (1997)\"."),
            -1,
            "Incorrect output for extract_sentiment(\'I didn't enjoy  \"Titanic (1997)\"\'.)"
    ) and assertEquals(
            chatbot.extract_sentiment("I saw \"Titanic (1997)\"."), 0,
            "Incorrect output for extract_sentiment(\'I saw  \"Titanic (1997)\"\'.)"
    ) and assertEquals(
            chatbot.extract_sentiment(
                " \"Titanic (1997)\" started out terrible, but the ending was totally great and I loved it!"
            ), 1,
            "Incorrect output for extract_sentiment(\" \"Titanic (1997)\" started out terrible, but the ending was totally great and I loved it!\'.\")"
    ) and assertEquals(
            chatbot.extract_sentiment(
                "I loved \"10 Things I Hate About You\""), 1,
            "Incorrect output for extract_sentiment(\'I loved  \"10 Things I Hate About You\"\')"
    ) and assertEquals(
            chatbot.extract_sentiment(
                "I saw \"The Notebook\" and it was great!"), 1,
            "Incorrect output for extract_sentiment(\'I saw \"The Notebook\" and it was great!\')"
    ):
        print('extract_sentiment() sanity check passed!')
    print()
Beispiel #24
0
def test_disambiguate():
    print("Testing disambiguate() functionality...")
    chatbot = Chatbot(True)

    clarification1 = "1997"
    candidates1 = [1359, 2716]

    clarification2 = "2"
    candidates2 = [1142, 1357, 2629, 546]

    clarification3 = "sorcerer's stone"
    candidates3 = [3812, 4325, 5399, 6294, 6735, 7274, 7670, 7842]

    clarification4 = "that darn cat!"
    candidates4 = [822, 1090, 1182, 1599]
    # [822]

    clarification5 = "That Darn Cat"
    candidates5 = [822, 1090, 1182, 1599]
    # [1182]

    # Ending punctuation cases
    """
    and assertListEquals(
        chatbot.disambiguate(clarification4, candidates4),
        [822],
        "Incorrect output for disambiguate('{}', {})".format(clarification4, candidates4),
        orderMatters=False
    ) and assertListEquals(
        chatbot.disambiguate(clarification5, candidates5),
        [1182],
        "Incorrect output for disambiguate('{}', {})".format(clarification5, candidates5),
        orderMatters=False
    )
    """

    if assertListEquals(
        chatbot.disambiguate(clarification1, candidates1),
        [1359],
        "Incorrect output for disambiguate('{}', {})".format(clarification1, candidates1),
        orderMatters=False
    ) and assertListEquals(
        chatbot.disambiguate(clarification2, candidates2),
        [1357],
        "Incorrect output for disambiguate('{}', {})".format(clarification2, candidates2),
        orderMatters=False
    ) and assertListEquals(
        chatbot.disambiguate(clarification3, candidates3),
        [3812],
        "Incorrect output for disambiguate('{}', {})".format(clarification3, candidates3),
        orderMatters=False
    ):
        print('disambiguate() sanity check passed!')
    print()
    return True
Beispiel #25
0
def chatbot():
    if request.method == 'POST':
        chatbot = Chatbot()
        if 'text' in request.form:
            return chatbot.recibir_mensaje(request.form['text'])
        elif 'satisfaccion' in request.form and 'pregunta' in request.form:
            return chatbot.satisfaccion(request.form['satisfaccion'], request.form['pregunta'],
                                        request.form['original'])
        else:
            return "Nada que responder"
    return "No se ha solicitado ninguna pregunta."
Beispiel #26
0
 def __init__(self, socketio, session):
     """
     Input
         socketio - Flask SocketIO object
         session - request ID
     """
     self.cb = Chatbot(socketio, session)
     self.socket = socketio
     self.session = session
     self.iu = None
     self.conv = None
     self.already_running = False
Beispiel #27
0
    def __init__(self, amqp_url):
        """Create a new instance of the consumer class, passing in the AMQP
        URL used to connect to RabbitMQ.

        :param str amqp_url: The AMQP url to connect with

        """
        self._connection = None
        self._channel = None
        self._closing = False
        self._consumer_tag = None
        self._url = amqp_url
        self.chatbot = Chatbot()
Beispiel #28
0
def on_new_message(data):
    # this is used to strip away the nickname infront of the chat message
    botcommand = data["message"].lstrip(":")

    chat = Chatbot(botcommand)
    if chat.checkcommand():
        db.session.add(models.Chatlog(chat.getcommand()))
        db.session.commit()
    else:
        db.session.add(
            models.Chatlog(data["nickname"] + ": " + data["message"]))
        db.session.commit()

    emit_all_messages(ADDRESSES_RECEIVED_CHANNEL)
Beispiel #29
0
def test_disambiguate():
    print("Testing disambiguate() functionality...")
    chatbot = Chatbot(True)

    clarification = "1997"
    candidates = [1359, 2716]
    if assertListEquals(chatbot.disambiguate(clarification, candidates),
                        [1359],
                        "Incorrect output for disambiguate('{}', {})".format(
                            clarification, candidates),
                        orderMatters=False):
        print('disambiguate() sanity check passed!')
    print()
    return True
Beispiel #30
0
def test_chatbot_at_monday(patch_datetime_monday):
    Cb = Chatbot()
    range_name, text_to_send = Cb.today_metric()
    assert range_name == 'Dashboard!I42:I42'


# def test_chatbot_at_tuesday(tuesday):
#     Cb = Chatbot()
#     range_name, text_to_send = Cb.today_metric()
#     assert range_name == 'Dashboard!I46:I46'

# marker pytest.mark.run_these_please require import pytest
# pytest -v test/test_one.py::test_passing
# pytest -v -m run_these_please
Beispiel #31
0
def test_extract_titles():
    print("Testing extract_titles() functionality...")
    chatbot = Chatbot(False)
    if assertListEquals(
        chatbot.extract_titles('I liked "The Notebook"'),
        ["The Notebook"],
        "Incorrect output for extract_titles(\'I liked \"The Notebook\"\')."
    ) and assertListEquals(
        chatbot.extract_titles('No movies here!'),
        [],
        "Incorrect output for extract_titles('No movies here!').",
    ):
        print('extract_titles() sanity check passed!')
    print()
Beispiel #32
0
import trivia

import discord

from cleverbot import cleverbot
from chatbot import Chatbot
from polls import Poll
from reminder import Reminder
from timezone import Timezone
from trivia import Trivia

# Set up the logging module to output diagnostic to the console.
logging.basicConfig()

# Create new instances of bot objects
bot = Chatbot('settings.txt')
remind_module = Reminder()
timezone_module = Timezone()
trivia_module = Trivia()
poll_module = Poll()

# RPi Lighting
if bot.gpio_enabled == "yes":
	import RPi.GPIO as GPIO
	GPIO.setmode(GPIO.BCM)
	statPin = 4
	GPIO.setup(statPin, GPIO.OUT)

#cleverbot object
clever_bot = cleverbot.Session()
Beispiel #33
0
import trivia

import discord

from cleverbot import cleverbot
from chatbot import Chatbot
from polls import Poll
from reminder import Reminder
from timezone import Timezone
from trivia import Trivia

# Set up the logging module to output diagnostic to the console.
logging.basicConfig()

# Create new instances of bot objects
bot = Chatbot('settings.txt')
remind_module = Reminder()
timezone_module = Timezone()
trivia_module = Trivia()
poll_module = Poll()

#cleverbot object
clever_bot = cleverbot.Session()

# Initialize client object, begin connection
client = discord.Client()

serv = ''

# Event handler
@client.event
Beispiel #34
0
# Imports and initialization
from chatbot import Chatbot, log # chatbot.py, the chatbot framework
import random # chose a random element from a table
import upsidedown # flips strings - non PIP library
import shutil # file manipulation (creating images from bytes)
from PIL import Image # check if images are valid / images format conversion
from imgurpython import ImgurClient # upload images to imgur
import time # sleeping

client_id = 'fb1b922cb86bb0f'  # Imgur module setup
client_secret = 'cffaf5da440289a8923f9be60c22b26e25675d3d'
clientImg = ImgurClient(client_id, client_secret)

## Initialization
# Create chatbot
chatbot=Chatbot()
# Login to SE
chatbot.login()

# useful vars
coolTables = {
    "tablesList": ["(╯°□°)╯︵ ┻━┻", "(ノಠ益ಠ)ノ彡┻━┻", "ʕノ•ᴥ•ʔノ ︵ ┻━┻", "(/¯◡ ‿ ◡)/¯ ~ ┻━┻", "(ノ-_-)ノ ~┻━┻", "(ノ;;)ノ~┻━┻",
                   "(ノ-_-)ノ ~┻━┻ ☆`", "(ノ-_-)ノ・・・~~┻━┻", "(ノ-_-)ノ~┻━┻", "ノ ̄□ ̄)ノ ~┻━┻", "(ノꐦ ⊙曲ఠ)ノ彡┻━┻", "(ノ`□´)ノ⌒┻━┻",
                   "(ノꐦ ๑´Д`๑)ノ彡┻━┻", "┻━┻ミ\(≧ロ≦\)", "(ノ ̄□ ̄)ノ ~┻━┻", "(ノ♯`△´)ノ~’┻━┻", "(ノT_T)ノ ^┻━┻", "(┛ಠДಠ)┛彡┻━┻",
                   "(ノ°▽°)ノ︵┻━┻", "(ノ*’ω’*)ノ彡┻━┻", "‎(ノಥ益ಥ)ノ ┻━┻", "(╯’□’)╯︵ ┻━┻", "(ノಥДಥ)ノ︵┻━┻・/", "(._.) ~ ︵ ┻━┻",
                   "┗[© ♒ ©]┛ ︵ ┻━┻", "┻━┻ ︵ ლ(⌒-⌒ლ)", "(ノ^◡^)ノ︵ ┻━┻", "༼ ᕤ ºل͟º ༽ᕤ ︵┻━┻", "ヽ༼ ツ ༽ノ ︵┻━┻",
                   "༼ ͠ຈ ͟ل͜ ͠ຈ༽ง︵┻━┻", "ヽ༼ຈل͜ຈ༽ノ︵┻━┻", "(╯ຈل͜ຈ) ╯︵ ┻━┻", "༼ノಠل͟ಠ༽ノ ︵ ┻━┻", "༼ノຈل͜ຈ༽ノ︵┻━┻",
                   "(╯ ͝° ͜ʖ͡°)╯︵ ┻━┻", "(つ☢益☢)つ︵┻━┻", "ヽ༼ຈل͜ຈ༽ノ︵ ┻━┻", "(┛◉Д◉)┛彡┻━┻", "(ノ≧∇≦)ノ ミ ┸━┸", "┻━┻ミ\(≧ロ≦\)",
                   "(ノ`´)ノ ~┻━┻ ~", "ʕ ⊃・ ◡ ・ ʔ⊃︵┻━┻", "(ノ▼д▼)ノ ~┻━┻ ☆`", "(┛❍ᴥ❍)┛彡┻━┻", "(ʘ∇ʘ)ク 彡 ┻━┻",
                   "┻━┻ ︵ ლ(ಠ益ಠლ)", "(╯ಠ_ರೃ)╯︵ ┻━┻", "/(ò.ó)┛彡┻━┻", "(╯=▃=)╯︵┻━┻", "(ノ`ー´)ノ・・・~~┻━┻", "(ノ`◇´)ノ~┻━┻",
                   "┻━┻ ヘ╰( •̀ε•́ ╰)", "(ノ`Д´)ノ~┻━┻", "(ノ`△´)ノ~┻━┻", "(⑅ノ-_-)ノ~┻━┻    ", "(╯ ・ ᗜ ・ )╯︵ ┻━┻  ",
Beispiel #35
0
			print ot
			logging.info(ot)

		batch_idx = (batch_idx+1) % num_batchs
	"""
	with open(path_pkl, "wb") as mf:
		pickle.dump(model, mf)
	"""
	return model


if __name__ == '__main__':
	print "Initializing chatbot..."
	time_start = timeit.default_timer()

	model = build_model(retrain=True)
	cbot = Chatbot(model)

	time_end = timeit.default_timer()
	print "Done initializing chatbot...Time taken:   ", (time_end-time_start)

	
	while True:
		conva = raw_input("role A: ")
		convB = cbot.utter(conva)
		print "role B: ", convB, "\n"