Exemple #1
0
def run_bot(tags, intents):
    conversation = Conversation(tags, intents)

    while not conversation.is_finished():
        sentence = str(input("Human: "))
        answer = conversation.input_sentence(sentence)
        print('Bot  :', answer)
Exemple #2
0
def play_game(li, game_id, control_queue, engine_factory, user_profile,
              config):
    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')),
                      user_profile["username"], li.baseUrl)
    board = setup_board(game)
    engine = engine_factory(board)
    conversation = Conversation(game, engine, li, __version__)

    print("+++ {}".format(game))

    engine.pre_game(game)

    engine_cfg = config["engine"]

    if (engine_cfg["polyglot"] == True):
        board = play_first_book_move(game, engine, board, li, engine_cfg)
    else:
        board = play_first_move(game, engine, board, li)

    try:
        for binary_chunk in updates:
            upd = json.loads(
                binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if u_type == "chatLine":
                conversation.react(ChatLine(upd), game)
            elif u_type == "gameState":
                game.state = upd
                moves = upd["moves"].split()
                board = update_board(board, moves[-1])
                if is_engine_move(game, moves):
                    best_move = None
                    if (engine_cfg["polyglot"] == True and len(moves) <=
                        (engine_cfg["polyglot_max_depth"] * 2) - 1):
                        best_move = get_book_move(board, engine_cfg)
                    if best_move == None:
                        best_move = engine.search(board, upd["wtime"],
                                                  upd["btime"], upd["winc"],
                                                  upd["binc"])
                    li.make_move(game.id, best_move)
                    game.abort_in(20)
            elif u_type == "ping":
                if game.should_abort_now() and len(game.state["moves"]) < 6:
                    print("    Aborting {} by lack of activity".format(
                        game.url()))
                    li.abort(game.id)
    except (RemoteDisconnected, ConnectionError, ProtocolError,
            HTTPError) as exception:
        print("Abandoning game due to connection error")
        traceback.print_exception(type(exception), exception,
                                  exception.__traceback__)
    finally:
        print("--- {} Game over".format(game.url()))
        engine.quit()
        # This can raise queue.NoFull, but that should only happen if we're not processing
        # events fast enough and in this case I believe the exception should be raised
        control_queue.put_nowait({"type": "local_game_done"})
Exemple #3
0
 def __init__(self):
     self.trip_date = ""  # The date of the trip
     self.trip_forecast = ""  # The forecast for the trip
     self.check_date = False  # Flag for verify date in user input
     self.other_trip = False  # Flag for checking if we will provide info for other trip
     self.conversation = Conversation(current_app)
     self.bot = create_chatbot()
Exemple #4
0
    def post(self):
        """ 
        Function to handle received messages

        @rtype: None
        """
        #TODO: Delete this variable.
        dummy_email = "*****@*****.**" #: Dummy Email. Will be used for user_2 if there is no match.
        message = xmpp.Message(self.request.POST) 
        pass_message = True #: Whether the message will be passed to partner

        sender = message.sender.split("/")[0] # Remove the identifier string from JID
        conversation = Conversation(user_1 = sender, user_2 = dummy_email ,location = db.GeoPt(41,28)) # Create a new conversation
        conversation = conversation.getPartner(sender) # Try to get a partner

        if message.body[0] == "|": # If this is a custom message
            pass_message = self.customMessageHandler(conversation,message)

        if conversation.is_started == True: # If this conversation has started
            if conversation.user_1 == sender: 
                partner = conversation.user_2
            else:
                partner = conversation.user_1
            
            if pass_message == True: # If we need to pass this message to client (See custom messages)
                xmpp.send_message(partner, message.body) # Send this message to partner
Exemple #5
0
 def add_new_reminder(self, data, conversation_id, user):
     if Conversation.is_active_conversation(conversation_id):
         next_question = Conversation.get_open_question_response(conversation_id, str(data))
         if next_question is None:
             self.doc.insert(Conversation.active_con.get(conversation_id))
             del Conversation.active_con[conversation_id]
             response = ":floppy_disk: _Document inserted_"
         else:
             extra = ""
             if next_question == "DateOfExpire":
                 extra = " (format MM/DD/YYYY - Eg 05/31/2020 will be may 5th of 2020)"
             response = "Please give input for %s%s: " % (next_question, extra)
     else:
         Conversation.active_con[conversation_id] = {"command": data}
         for column in self.doc.INSERT_COLUMNS:
             Conversation.active_con[conversation_id][column] = None
         next_question = Conversation.get_open_question_response(conversation_id, None)
         extra = ""
         if str(next_question).lower().find("date") >= 0:
             extra = " (format MM/DD/YYYY - Eg 05/31/2020     will be may 5th of 2020)"
         elif str(next_question).lower() in ["RemindStart", "RemindFrequency"]:
             extra = " (format 1M for 1 month, 3M for 3 Months, 1W for one week, 1Y for one year - " \
                     "only M/W/Y is supported)"
         response = "Please give input for %s%s: " % (next_question, extra)
     return response
Exemple #6
0
def get_message_history():
    conversation_db_path = get_conversation_db_path_for_users(request.form)
    conversation = Conversation(conversation_db_path)

    history = conversation.get_history()

    return jsonify({"history": history})
Exemple #7
0
def create_conversation_db():
    conversations_db_path = get_conversation_db_path_for_users(request.form)

    if not os.path.exists(conversations_db_path):
        conversation = Conversation(conversations_db_path)
        conversation.initialise_table()

    return jsonify({"success": True})
def create_loop():

    conversation = Conversation()

    while True:
        inp = input('>>> ')
        if len(inp) > 0:
            print('<<< ' + str(conversation.respond(inp)))
Exemple #9
0
 def test_process_string(self):
     app = MagicMock()
     conversation = Conversation(app)
     test_cases = [("Hello there!", ['hello', 'there']),
                   ("LIfe is g00d", ['life', 'is', 'g00d']),
                   ("00 123 nananA", ['00', '123', 'nanana'])]
     for option, answer in test_cases:
         self.assertEqual(conversation.process_string(option), answer)
Exemple #10
0
    def run(self):
        if 'first_name' in self.config:
            salutation = ("Hoe kan ik je helpen?")
        else:
            salutation = "Hoe kan ik je helpen?"
        self.mic.say(salutation)

        conversation = Conversation(self.config['keyword'].upper(), self.mic, self.config)
        conversation.handleForever()
Exemple #11
0
 def test_is_negative(self):
     app = MagicMock()
     conversation = Conversation(app)
     test_cases = [("no", True), ("cancel", True), ("dont", True),
                   ("don't", True), ("not", True), ("nope", True),
                   ("n", True), ("0", True), ("hi", False),
                   ("hellow", False), ("1", False)]
     for option, answer in test_cases:
         self.assertEqual(conversation.is_negative(option), answer)
Exemple #12
0
 def test_is_goodbye(self):
     app = MagicMock()
     conversation = Conversation(app)
     test_cases = [("bye", True), ("see you", True), ("au revoir", True),
                   ("goobye", True), ("bye-bye", True), ("cheers", True),
                   ("farewell", True), ("take care", True), ("hi", False),
                   ("hellow", False)]
     for option, answer in test_cases:
         self.assertEqual(conversation.is_goodbye(option), answer)
Exemple #13
0
def play_game(li, game_id, control_queue, engine_factory, user_profile, config):
    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')), user_profile["username"], li.baseUrl, config.get("abort_time", 20))
    board = setup_board(game)
    engine = engine_factory(board)
    conversation = Conversation(game, engine, li, __version__)

    print("+++ {}".format(game))

    engine_cfg = config["engine"]
    polyglot_cfg = engine_cfg.get("polyglot", {})
    book_cfg = polyglot_cfg.get("book", {})

    if not polyglot_cfg.get("enabled") or not play_first_book_move(game, engine, board, li, book_cfg):
        play_first_move(game, engine, board, li)

    engine.set_time_control(game)

    try:
        for binary_chunk in updates:
            upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if u_type == "chatLine":
                conversation.react(ChatLine(upd), game)
            elif u_type == "gameState":
                game.state = upd
                moves = upd["moves"].split()
                board = update_board(board, moves[-1])
                if is_engine_move(game, moves):
                    if config.get("fake_think_time") and len(moves) > 9:
                        delay = min(game.clock_initial, game.my_remaining_seconds()) * 0.015
                        accel = 1 - max(0, min(100, len(moves) - 20)) / 150
                        sleep = min(5, delay * accel)
                        time.sleep(sleep)
                    best_move = None
                    if polyglot_cfg.get("enabled") and len(moves) <= polyglot_cfg.get("max_depth", 8) * 2 - 1:
                        best_move = get_book_move(board, book_cfg)
                    if best_move == None:
                        best_move = engine.search(board, upd["wtime"], upd["btime"], upd["winc"], upd["binc"])
                    li.make_move(game.id, best_move)
                    game.abort_in(config.get("abort_time", 20))
            elif u_type == "ping":
                if game.should_abort_now():
                    print("    Aborting {} by lack of activity".format(game.url()))
                    li.abort(game.id)
    except (RemoteDisconnected, ChunkedEncodingError, ConnectionError, ProtocolError, HTTPError) as exception:
        print("Abandoning game due to connection error")
        traceback.print_exception(type(exception), exception, exception.__traceback__)
    finally:
        print("--- {} Game over".format(game.url()))
        engine.quit()
        # This can raise queue.NoFull, but that should only happen if we're not processing
        # events fast enough and in this case I believe the exception should be raised
        control_queue.put_nowait({"type": "local_game_done"})
 def __init__(self, server_ip, dialogflow_key_file, dialogflow_agent_id):
     """
     :param server_ip: IP address of Social Interaction Cloud server
     :param dialogflow_key_file: path to Google's Dialogflow key file (JSON)
     :param dialogflow_agent_id: ID number of Dialogflow agent to be used (project ID)
     """
     self.sic = BasicSICConnector(
         server_ip, 'en-US', dialogflow_key_file, dialogflow_agent_id)
     self.conversation = Conversation(self.sic, robot_present=True, animation=True)
     self.story = Story(interactive=True)
	def __init__(self, name, gamestatemanager):
		self.__gamestatemanager = gamestatemanager
		try:
			introText = open("Text Dialogue and Intro/Story intro.txt").read()
		except:
			introText = "Langes Intro..."
		introConversation = Conversation(introText,[])
		okAnswer = Answer("Beginne dein Abenteuer...", IntroGameState.startGame, [self])
		introConversation.addAnswer(okAnswer)
		self.__textbox = TextBox(introConversation)
Exemple #16
0
    def run(self):
        if 'first_name' in self.config:
            salutation = ("How can I be of service, %s?" %
                          self.config["first_name"])
        else:
            salutation = "How can I be of service?"
        self.mic.say(salutation)

        conversation = Conversation("JASPER", self.mic, self.config)
        conversation.handleForever()
Exemple #17
0
def get_conv(event, config):
    if event.conv:
        return Conversation.lookup_or_convsummary(event.conv.id, event.conv, config.db)
    if event.msg:
        if not event.msg.conv_id:
            raise RuntimeError("KbEvent msg has no conv_id")
        if event.msg.channel:
            return Conversation.lookup_or_convsummary(event.msg.conv_id, event.msg, config.db)
        return Conversation.lookup(event.msg.conv_id)
    raise RuntimeError("KbEvent has no conv or msg")
Exemple #18
0
    def run(self):
        print 'Start'
        if 'first_name' in self.config:
            salutation = ("How can I be of service, %s?"
                          % self.config["first_name"])
        else:
            salutation = "How can I be of service?"
        print('Say hello')
        self.input.say(salutation)

        conversation = Conversation("JANE", self.input, self.config)
        conversation.handleForever()
Exemple #19
0
    def run(self):
        print 'Start'
        if 'first_name' in self.config:
            salutation = ("How can I be of service, %s?" %
                          self.config["first_name"])
        else:
            salutation = "How can I be of service?"
        print('Say hello')
        self.input.say(salutation)

        conversation = Conversation("JANE", self.input, self.config)
        conversation.handleForever()
Exemple #20
0
def get_new_messages():
    data = request.form
    conversation_db_path = get_conversation_db_path_for_users(data)
    conversation_db = Conversation(conversation_db_path)

    timestamp = data['timestamp']
    requester_username = data['user_one']

    new_messages = conversation_db.get_new_messages(timestamp,
                                                    requester_username)

    return jsonify({'messages': new_messages})
Exemple #21
0
def send_message(username):
    data = request.form
    author = data["author"]
    message = data["message"]
    date_sent = arrow.now().timestamp

    conversation_db_path = get_conversation_db_path_for_users({"user_one": author, "user_two": username})
    conversation = Conversation(conversation_db_path)
    conversation.add_message(author, message, date_sent)

    return jsonify({
        "success": True
    })
Exemple #22
0
def create_conversation_db():
    conversation_db_path = get_conversation_db_path_for_users(request.form)
    print(conversations_dir)

    if not os.path.exists(conversation_db_path):
        with open(conversation_db_path, 'w') as f:
            pass
        conversation = Conversation(conversation_db_path)
        conversation.initialise_table()

    return jsonify({
        "success": True,
    })
Exemple #23
0
def inteligence():
    objectConversations = request.get_json()
    conversation = Conversation()
    for objectConversation in objectConversations['objectConversations']:
        intention = Intention()

        questions = tuple(objectConversation['questions'])
        responses = tuple(objectConversation['responses'])
        dialog = Dialog(questions, responses, objectConversation['action'])
        intention.insert_dialog(dialog)

        conversation.insert_intention(intention)

    return conversation.get_response(objectConversations['question'],
                                     objectConversations['no_responses'])
Exemple #24
0
def _load_model():
    global sentiment_analysis
    global conversation

    with graph.as_default():
        sentiment_analysis = SentimentAnalysis(SA_TOKENIZER, SA_MODEL)
        conversation = Conversation(CONVERSATION_MODEL)
Exemple #25
0
    def getccEndorsed(self, threshold):

        query = "PREPARE stmt(int) AS " \
                "SELECT * FROM conversation WHERE endorsements >= $1;" \
                "EXECUTE stmt(" + str(threshold) + ");"

        conversations = Database.connectDB(self, query)

        conversation_list = []

        for i, conversation in enumerate(conversations):

            conzip = json.loads(conversation[3])
            speakers = []
            descrips = []
            links = []
            images = []

            for converse in conzip.values():
                speakers.append(converse[0])
                descrips.append(converse[1])
                links.append(converse[2])
                images.append(converse[3])

            conversation_list.append(
                Conversation(conversation[0], conversation[1], conversation[2],
                             speakers, descrips, links, images,
                             conversation[4], conversation[5],
                             conversation[6]))

        return conversation_list
Exemple #26
0
    def getConversations(self, promoted):
        if promoted == 0:
            query = "SELECT * FROM conversation WHERE faculty = '0'"
        else:
            query = "SELECT * FROM conversation WHERE faculty != '0'"
        conversations = Database.connectDB(self, query)

        conversation_list = []

        for i, conversation in enumerate(conversations):

            conzip = json.loads(conversation[3])
            speakers = []
            descrips = []
            links = []
            images = []

            for converse in conzip.values():
                speakers.append(converse[0])
                descrips.append(converse[1])
                links.append(converse[2])
                images.append(converse[3])

            conversation_list.append(
                Conversation(conversation[0], conversation[1], conversation[2],
                             speakers, descrips, links, images,
                             conversation[4], conversation[5],
                             conversation[6]))

        return conversation_list
Exemple #27
0
    def getConversation(self, converseid):
        query = "PREPARE stmt(text) AS " \
                "SELECT * FROM conversation WHERE converseid = $1;" \
                "EXECUTE stmt('" + str(converseid) + "');"

        conversation = Database.connectDB(self, query)

        if not conversation:
            conversation = 0
        else:
            conversation = conversation[0]
            conzip = json.loads(conversation[3])
            speakers = []
            descrips = []
            links = []
            images = []

            for converse in conzip.values():
                speakers.append(converse[0])
                descrips.append(converse[1])
                links.append(converse[2])
                images.append(converse[3])

            conversation = Conversation(conversation[0], conversation[1],
                                        conversation[2], speakers, descrips,
                                        links, images, conversation[4],
                                        conversation[5], conversation[6])

        return conversation
Exemple #28
0
    async def test_hello(self, mockNow, mockRandom, mockKeybaseSend):
        await self.message_test("hi", "hi!", mockKeybaseSend)

        conv = Conversation.lookup_or_json(TEST_CONV_ID, TEST_CONV_JSON, DB)
        conv.delete()

        await self.message_test("hello", "hello!", mockKeybaseSend)
Exemple #29
0
def start(update, context):
    if update.effective_user.id not in ADMINS_IDS:
        return

    text = 'Админка. Для отмены, нажмите "готово".'
    buttons = []
    for i, question in enumerate(Conversation().questions):
        q_text = _truncate(question['text'])
        buttons.append([
            InlineKeyboardButton(text=q_text, callback_data=f'{DETAIL_QUESTION}_{i}'),
            InlineKeyboardButton(text='📝', callback_data=f'{CHANGING_QUESTION}_{i}'),
            InlineKeyboardButton(text='🗑️', callback_data=f'{REMOVING_QUESTION}_{i}'),
        ])
    buttons.extend([
        [InlineKeyboardButton(text='Добавить вопрос', callback_data=str(ADDING_QUESTION))],
        [InlineKeyboardButton(text='Изменить информацию', callback_data=str(CH_INFO))],
        [InlineKeyboardButton(text='Изменить приветствие', callback_data=str(CH_HELLO))],
        [InlineKeyboardButton(text='Изменить прощание', callback_data=str(CH_BYE))],
        [InlineKeyboardButton(text='Готово', callback_data=str(END))]
    ])
    keyboard = InlineKeyboardMarkup(buttons)

    if update.callback_query:
        update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
    else:
        update.message.reply_text(text=text, reply_markup=keyboard)

    context.user_data[START_OVER] = True
    return SELECTING_ACTION
Exemple #30
0
def send_message(username):
    data = request.form
    author = data['author']
    message = data['message']
    date_sent = arrow.now().timestamp

    conversation_db_path = get_conversation_db_path_for_users({
        'user_one':
        author,
        'user_two':
        username
    })
    conversation = Conversation(conversation_db_path)
    conversation.add_message(author, message, date_sent)

    return jsonify({'success': True})
    def new_conversation(self, worker, user):
        worker = int(worker)
        user = int(user)

        conv = Conversation(worker, user)
        self.active_conversations.append(conv)
        self.waiting_queue.remove(user)
 def send_message(self, incoming, mockKeybaseSend):
     conv = Conversation.lookup(TEST_CONV_ID, TEST_CONV_JSON, DB)
     message = keybase.Message.inject(incoming, TEST_USER, TEST_CONV_ID,
                                      TEST_CHANNEL, DB)
     resp = bot.process_message(self.config, message, conv)
     if resp is not None:
         keybase.send(TEST_CONV_ID, resp)
Exemple #33
0
def process(update: Update, context):
    if not context.user_data.get(
            'processing'
    ) and update.callback_query and update.callback_query.data:
        context.user_data['processing'] = True

    if not context.user_data.get('processing'):
        return END
        # return start(update, context)

    conversation = Conversation()
    current_step = context.user_data.get('current_step', 0)
    context.user_data['current_step'] = current_step + 1
    current_question = conversation.get_question(current_step)

    if update.message:
        value = update.message.text
        previous_question = conversation.get_question(current_step - 1)
        if previous_question and value:
            context.user_data[previous_question] = value

    if current_step > 0:
        if current_step == len(conversation.questions):
            user = update.effective_user
            name = getattr(user, 'full_name', getattr(user,
                                                      'name')) or 'нет_имени'
            data = 'Поступила заявка от %s. (%s)\n' % (
                name, '@' + getattr(user, 'username'))
            for question in conversation.questions:
                question_text = question['text']
                data += '%s: %s\n' % (question_text,
                                      context.user_data[question_text])

            for admin_id in ADMINS_IDS:
                context.bot.send_message(admin_id, data)

            bye = Bye().read()
            update.message.reply_text(bye or 'С вами скоро свяжутся.')
            context.user_data.clear()
            return END

        update.message.reply_text(current_question)
        return PROCESS

    else:
        update.callback_query.edit_message_text(text=current_question)
        return PROCESS
Exemple #34
0
 def setUp(self) -> None:
     conversation = [
         {
             'text': 'test1',
         },
         {
             'text': 'test2',
         },
         {
             'text': 'test3',
         }
     ]
     fn = 'test_conversation.json'
     self._fn = fn
     with open(fn, 'w') as f:
         f.write(json.dumps(conversation))
     self.conversation = Conversation(fn)
Exemple #35
0
    def detectDeadConversations(self):

        now = datetime.datetime.now()
        yesterday = now - datetime.timedelta(days=1)

        q = Conversation.all()
        q.filter(date_created < yesterday)

        return q
Exemple #36
0
 def add_conversation(self, subject, message):
     convo = Conversation()
     convo.subject = subject
     convo.message = message
 def run(self):
     conversation = Conversation("alfred", self.speaker, self.person)
     conversation.handleForever()
Exemple #38
0
def main():
    if len(sys.argv) == 1:
        print 'Available Functions:'
        print '  --setup'
        print
        print '  --account/verify_credentials(email, password)'
        print '  --account/settings (user_id)'
        print '  --account/update_settings (user_id, email, password, privacy, locale, timezone)'
        print '  --account/update_profile(user_id, username, name, bio, website, image)'
        print '  --account/create(email, password, username, name, privacy)'
        print 
        print '  --blocks/exists (user_id, follower_id)'
        print '  --blocks/blocking/ids (user_id)'
        print '  --blocks/create (user_id, follower_id)'
        print '  --blocks/destroy (user_id, follower_id)'
        print
        print '  --users/show (user_id)'
        print '  --users/lookup (user_ids)'
        print '  --users/search (query)'
        print '  --users/flag (user_id)'
        print
        print '  --friends/ids (user_id)'
        print '  --followers/ids (user_id)'
        print
        print '  --friendships/create (user_id, following_id)'
        print '  --friendships/destroy (user_id, following_id)'
        print '  --friendships/exists (user_id, following_id)'
        print '  --friendships/show (user_id, following_id)'
        print '  --friendships/incoming (user_id)'
        print '  --friendships/outgoing (user_id)'
        print
        print '  --entities/show (entity_id)'
        print '  --entities/create (title, category)'
        print '  --entities/destroy (entity_id)'
        print '  --entities/update (entity_id, title, category)'
        print '  --entities/match (query)'
        print
        print '  --stamps/create (uid, entity_id, comment)'
        print '  --stamps/show (stamp_id)'
        print '  --stamps/destroy (stamp_id)'
        print '  --stamps/flag (stamp_id, [is_flagged])'
        print '  --stamps/read (stamp_id, [user_id], [is_read])'
        print 
        print '  --conversation/show (comment_id)'
        print '  --conversation/create (user_id, stamp_id, comment)'
        print '  --conversation/destroy (comment_id)'
        print '  --conversation/flag (comment_id, [is_flagged])'
        print
        print '  --mentions/create (stamp_id, user_id)'
        print '  --mentions/destroy (stamp_id, user_id)'
        print '  --mentions/user (user_id)'
        print 
        print '  --collections/inbox (user_id)'
        print '  --collections/user (user_id)'
        print '  --collections/add_stamp (stamp_id)'
        print
        print '  --favorites/show (user_id)'
        print '  --favorites/create (stamp_id, user_id)'
        print '  --favorites/destroy (stamp_id, user_id)'
        print
        sys.exit(1)
    
    option = sys.argv[1]
    
    
    # Setup:
    if option == '--setup':
        setup.setup()
    
    
    # Account:
    elif option == '--account/verify_credentials':
        account = Account()
        checkNumberOfArguments(2, len(sys.argv))
        response = account.verify_credentials(sys.argv[2], sys.argv[3])
        print 'Response: ', response
        
    elif option == '--account/settings':
        account = Account()
        checkNumberOfArguments(1, len(sys.argv))
        response = account.settings(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--account/update_settings':
        account = Account()
        checkNumberOfArguments(6, len(sys.argv))
        response = account.update_settings(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7])
        print 'Response: ', response
        
    elif option == '--account/update_profile':
        account = Account()
        checkNumberOfArguments(6, len(sys.argv))
        response = account.update_profile(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7])
        print 'Response: ', response
        
    elif option == '--account/create':
        account = Account()
        checkNumberOfArguments(5, len(sys.argv))
        response = account.create(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6])
        print 'Response: ', response
        
        
    # Blocks:
    elif option == '--blocks/exists':
        block = Block()
        checkNumberOfArguments(2, len(sys.argv))
        response = block.exists(sys.argv[2], sys.argv[3])
        print 'Response: ', response
    
    elif option == '--blocks/blocking':
        block = Block()
        checkNumberOfArguments(1, len(sys.argv))
        response = block.blocking(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--blocks/create':
        block = Block()
        checkNumberOfArguments(2, len(sys.argv))
        response = block.create(sys.argv[2], sys.argv[3])
        print 'Response: ', response
    
    elif option == '--blocks/destroy':
        block = Block()
        checkNumberOfArguments(2, len(sys.argv))
        response = block.destroy(sys.argv[2], sys.argv[3])
        print 'Response: ', response
    
    
    # Users:
    elif option == '--users/show':
        user = User()
        checkNumberOfArguments(1, len(sys.argv))
        response = user.show(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--users/lookup':
        user = User()
        checkNumberOfArguments(1, len(sys.argv))
        user_ids = []
        for user_id in sys.argv[2:]:
            user_ids.append(user_id)
        response = user.lookup(user_ids)
        print 'Response: ', response
        
    elif option == '--users/search':
        user = User()
        checkNumberOfArguments(1, len(sys.argv))
        response = user.search(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--users/flag':
        user = User()
        if len(sys.argv) == 4:
            response = user.flag(sys.argv[2], sys.argv[3])
        elif len(sys.argv) == 3:
            response = user.flag(sys.argv[2])
        else:
            print 'Missing parameters'
            sys.exit(1)
        print 'Response: ', response
        
        
    # Friends & Followers:
    elif option == '--friends/ids':
        friend = Friend()
        checkNumberOfArguments(1, len(sys.argv))
        response = friend.ids(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--followers/ids':
        follower = Follower()
        checkNumberOfArguments(1, len(sys.argv))
        response = follower.ids(sys.argv[2])
        print 'Response: ', response
    
    
    # Friendships:
    elif option == '--friendships/create':
        friendship = Friendship()
        checkNumberOfArguments(2, len(sys.argv))
        response = friendship.create(sys.argv[2], sys.argv[3])
        print 'Response: ', response
    
    elif option == '--friendships/destroy':
        friendship = Friendship()
        checkNumberOfArguments(2, len(sys.argv))
        response = friendship.destroy(sys.argv[2], sys.argv[3])
        print 'Response: ', response
    
    elif option == '--friendships/exists':
        friendship = Friendship()
        checkNumberOfArguments(2, len(sys.argv))
        response = friendship.exists(sys.argv[2], sys.argv[3])
        print 'Response: ', response
    
    elif option == '--friendships/show':
        friendship = Friendship()
        checkNumberOfArguments(2, len(sys.argv))
        response = friendship.show(sys.argv[2], sys.argv[3])
        print 'Response: ', response
    
    elif option == '--friendships/incoming':
        friendship = Friendship()
        checkNumberOfArguments(1, len(sys.argv))
        response = friendship.incoming(sys.argv[2])
        print 'Response: ', response
    
    elif option == '--friendships/outgoing':
        friendship = Friendship()
        checkNumberOfArguments(1, len(sys.argv))
        response = friendship.outgoing(sys.argv[2])
        print 'Response: ', response
        
        
    # Entities:
    elif option == '--entities/show':
        entity = Entity()
        checkNumberOfArguments(1, len(sys.argv))
        response = entity.show(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--entities/create':
        entity = Entity()
        checkNumberOfArguments(2, len(sys.argv))
        response = entity.create(sys.argv[2], sys.argv[3])
        print 'Response: ', response
        
    elif option == '--entities/destroy':
        entity = Entity()
        checkNumberOfArguments(1, len(sys.argv))
        response = entity.destroy(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--entities/update':
        entity = Entity()
        checkNumberOfArguments(3, len(sys.argv))
        response = entity.update(sys.argv[2], sys.argv[3], sys.argv[4])
        print 'Response: ', response
        
    elif option == '--entities/match':
        entity = Entity()
        checkNumberOfArguments(1, len(sys.argv))
        response = entity.match(sys.argv[2])
        print 'Response: ', response
        
        
    # Stamps:
    elif option == '--stamps/create':
        stamp = Stamp()
        checkNumberOfArguments(3, len(sys.argv))
        response = stamp.create(sys.argv[2], sys.argv[3], sys.argv[4])
        print 'Response: ', response
        
    elif option == '--stamps/show':
        stamp = Stamp()
        checkNumberOfArguments(1, len(sys.argv))
        response = stamp.show(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--stamps/destroy':
        stamp = Stamp()
        checkNumberOfArguments(1, len(sys.argv))
        response = stamp.destroy(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--stamps/flag':
        stamp = Stamp()
        if len(sys.argv) == 4:
            response = stamp.flag(sys.argv[2], sys.argv[3])
        elif len(sys.argv) == 3:
            response = stamp.flag(sys.argv[2])
        else:
            print 'Missing parameters'
            sys.exit(1)
        print 'Response: ', response
        
    elif option == '--stamps/read':
        stamp = Stamp()
        if len(sys.argv) == 5:
            response = stamp.read(sys.argv[2], sys.argv[3], sys.argv[4])
        elif len(sys.argv) == 4:
            response = stamp.read(sys.argv[2], sys.argv[3])
        elif len(sys.argv) == 3:
            response = stamp.read(sys.argv[2])
        else:
            print 'Missing parameters'
            sys.exit(1)
        print 'Response: ', response
        
        
    # Conversation:
    elif option == '--conversation/show':
        conversation = Conversation()
        checkNumberOfArguments(1, len(sys.argv))
        response = conversation.show(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--conversation/create':
        conversation = Conversation()
        checkNumberOfArguments(3, len(sys.argv))
        response = conversation.create(sys.argv[2], sys.argv[3], sys.argv[4])
        print 'Response: ', response
        
    elif option == '--conversation/destroy':
        conversation = Conversation()
        checkNumberOfArguments(1, len(sys.argv))
        response = conversation.destroy(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--conversation/flag':
        conversation = Conversation()
        if len(sys.argv) == 4:
            response = conversation.flag(sys.argv[2], sys.argv[3])
        elif len(sys.argv) == 3:
            response = conversation.flag(sys.argv[2])
        else:
            print 'Missing parameters'
            sys.exit(1)
        print 'Response: ', response
        
    
    # Mentions:
    elif option == '--mentions/create':
        mention = Mention()
        checkNumberOfArguments(2, len(sys.argv))
        response = mention.create(sys.argv[2], sys.argv[3])
        print 'Response: ', response
        
    elif option == '--mentions/destroy':
        mention = Mention()
        checkNumberOfArguments(2, len(sys.argv))
        response = mention.destroy(sys.argv[2], sys.argv[3])
        print 'Response: ', response
        
    elif option == '--mentions/user':
        mention = Mention()
        checkNumberOfArguments(1, len(sys.argv))
        response = mention.user(sys.argv[2])
        print 'Response: ', response
        
        
    # Collections:
    elif option == '--collections/inbox':
        collection = Collection()
        checkNumberOfArguments(1, len(sys.argv))
        response = collection.inbox(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--collections/user':
        collection = Collection()
        checkNumberOfArguments(1, len(sys.argv))
        response = collection.user(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--collections/add_stamp':
        collection = Collection()
        checkNumberOfArguments(1, len(sys.argv))
        response = collection.add_stamp(sys.argv[2])
        print 'Response: ', response
        
        
    # Favorites:
    elif option == '--favorites/show':
        favorite = Favorite()
        checkNumberOfArguments(1, len(sys.argv))
        response = favorite.show(sys.argv[2])
        print 'Response: ', response
        
    elif option == '--favorites/create':
        favorite = Favorite()
        checkNumberOfArguments(2, len(sys.argv))
        response = favorite.create(sys.argv[2], sys.argv[3])
        print 'Response: ', response
        
    elif option == '--favorites/destroy':
        favorite = Favorite()
        checkNumberOfArguments(2, len(sys.argv))
        response = favorite.destroy(sys.argv[2], sys.argv[3])
        print 'Response: ', response
        
        
    else:
        print 'unknown option: ' + option
        sys.exit(1)
Exemple #39
0
def isLocal():
    return len(sys.argv) > 1 and sys.argv[1] == "--local"

if isLocal():
    from input.text import Receiver as Receiver
    from output.text import Sender as Sender
else:
    from input.att_audio import Receiver as Receiver
    from output.att_audio import Sender as Sender

if __name__ == "__main__":

    print "==========================================================="
    print " JASPER The Talking Computer                               "
    print " Copyright 2013 Shubhro Saha & Charlie Marsh               "
    print "==========================================================="

    profile = yaml.safe_load(open("profile.yml", "r"))

    receiver = Receiver("languagemodel.lm", "dictionary.dic",
              "languagemodel_persona.lm", "dictionary_persona.dic")

    sender = Sender()

    sender.say("How can I be of service?")

    conversation = Conversation("JASPER", sender, receiver, profile)

    conversation.handleForever()