예제 #1
0
class EchoLayer(YowInterfaceLayer):
    database = Db()
    questions = database.getQuestions()
    responses = database.getResponses()

    def reinitialize(self):
        print 'resetting questions and responses...'
        self.questions = database.getQuestions()
        self.responses = database.getResponses()

    @ProtocolEntityCallback("message")
    def onMessage(self, messageProtocolEntity):
        #send receipt otherwise we keep receiving the same message over and
        print 'message van:', messageProtocolEntity.getFrom()
        print 'message participants:', messageProtocolEntity.getParticipant()
        print messageProtocolEntity.getBody()

        if messageProtocolEntity.getBody() == 'chat reset':
            self.reinitialize()

        receipt = OutgoingReceiptProtocolEntity(
            messageProtocolEntity.getId(), messageProtocolEntity.getFrom(),
            'read', messageProtocolEntity.getParticipant())
        messagebody = messageProtocolEntity.getBody().lower()

        # else:
        #     outgoingMessageProtocolEntity = TextMessageProtocolEntity(
        #         messageProtocolEntity.getBody(),
        #         to = messageProtocolEntity.getFrom())

        self.toLower(receipt)
        # uncomment to send msg defined in outgoingMessageProtocolEntity
        # self.toLower(outgoingMessageProtocolEntity)

    @ProtocolEntityCallback("receipt")
    def onReceipt(self, entity):
        ack = OutgoingAckProtocolEntity(entity.getId(), "receipt",
                                        entity.getType(), entity.getFrom())
        self.toLower(ack)

    #Test. IQ info: http://xmpp.org/rfcs/rfc6120.html#stanzas-semantics-iq
    @ProtocolEntityCallback("iq")
    def onIq(self, entity):
        print(entity)
예제 #2
0
from responseBuilder import ResponseBuilder
from database.db import Db

db = Db()
rb = ResponseBuilder()

print 'starting...'


class SampleMessageProtocolEntity:
    def __init__(self, sender, message):
        self.sender = sender
        self.message = unicode(message)

    def getFrom(self):
        return self.sender

    def getBody(self):
        return self.message


while True:
    incomingmsg = raw_input('Incoming message:')

    db.insertTestIncomingMsg({'message': incomingmsg, 'sender': 'testuser'})
    testmsg = db.getMostRecentTestIncomingMsg()
    msgentity = SampleMessageProtocolEntity(testmsg['sender'],
                                            testmsg['message'])
    response = rb.getResponsesForMessage(msgentity)
    if not response:
        print 'no response for input ', incomingmsg
예제 #3
0
    'user': os.environ.get('username_local'),
    'password': os.environ.get('dbPass_local')
}

# Localhost db - TEST!
localTest_parm = {
    'host': os.environ.get('host_local'),
    'database': os.environ.get('dbName_test'),
    'user': os.environ.get('username_local'),
    'password': os.environ.get('dbPass_local')
}

# Azure
azureHost_parm = {
    'host': os.environ.get('host_azure'),
    'database': os.environ.get('dbName_azure'),
    'user': os.environ.get('username_azure'),
    'password': os.environ.get('dbPass_azure')
}

localHost = Db(localHost_parm['user'], localHost_parm['password'],
               localHost_parm["database"], localHost_parm['host'])

localTest = Db(localHost_parm['user'], localHost_parm['password'],
               localTest_parm["database"], localHost_parm['host'])

azure = Db(azureHost_parm['user'], azureHost_parm['password'],
           azureHost_parm['database'], azureHost_parm['host'])

current_db = localHost
예제 #4
0
class ResponseBuilder:
    # logging.basicConfig(stream=sys.stderr, level=logging.INFO)
    logging.basicConfig(stream=sys.stderr, level=logging.WARNING)
    # logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
    db = Db()
    messages = db.getMessages()
    conversations = db.getConversations()
    resetmsg = 'chatreset'
    conversationTimeoutThreshold = dt.timedelta(seconds=10)

    # Keeps track of the state of different conversations, so different people
    # can talk to the bot at the same time without the chat intermingling a
    # response.MessageProtocolEntity.getFrom() will be key.The most recent
    # interaction with the bot will be tracked to figure out if the conversation
    # has timed out and should be reset. Finally, it tracks how far into the
    # conversation they are.
    # conversationstates = {
    #     m.getFrom() : [
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr},
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr},
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}],
    #     m.getFrom() : [
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr},
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}],
    #     m.getFrom() : [
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr},
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr},
    #         {conv_id : x, mostrecentinteraction: timestamp, mostrecentquestion: question_nr}]
    # }
    #
    # messages: [
    #   { "m_nr" : 1, "qtext" : "hoi1", "rtext" : "doei 1", "is_alternative" : False, "conv_id" : 1 },
    #        ..]

    conversationstates = {}

    # searces through self.messages to find if the incoming message
    # matches any of the preprogramming input
    def findMessageQuestionMatches(self, incomingmessage):
        matches = []
        for message in self.messages:
            loweredmessage = message['qtext'].lower()
            if (re.search(r'\b' + loweredmessage + r'\b', incomingmessage)):
                # print '\n\nRE match, appending', loweredmessage, incomingmessage, re.search(r'\b' + loweredmessage + r'\b', incomingmessage)
                matches.append(message)
            elif loweredmessage == incomingmessage:
                # print 'exact match, appending', message
                matches.append(message)
        # print 'returning matches:', matches
        return matches

    def isFirstQuestion(self, question):
        return (question['m_nr'] == 1)

    def isUserRegisteredInConversationState(self, messageSender):
        return (messageSender in self.conversationstates)

    def isFollowUpQuestion(self, messageSender, question):
        m_nrs = self.getm_nrsAndis_alternativeForConvId(question['conv_id'])
        try:
            for convstate in self.conversationstates[messageSender]:
                if convstate['conv_id'] == question['conv_id']:
                    if question['m_nr'] == (convstate['mostrecentquestion'] +
                                            1):
                        return True
                    else:
                        return self.testPreviousMessagesAreAlternatives(
                            question['m_nr'], convstate['mostrecentquestion'],
                            m_nrs)
        except Exception, e:
            print 'exception, probably indexerror ', e
            return False
        return False