Ejemplo n.º 1
0
def main():
    args = parse_args()
    token = args.token

    if not token:
        if not "TELEGRAM_TOKEN" in os.environ:
            print("Please, set bot token through --token or TELEGRAM_TOKEN env variable")
            return
        token = os.environ["TELEGRAM_TOKEN"]

    advanced_manager = DialogueManager(RESOURCE_PATH)
    advanced_manager.create_chitchat_bot()
    bot = BotHandler(token, advanced_manager)

    print("Ready to talk!")
    offset = 0
    while True:
        updates = bot.get_updates(offset=offset)
        for update in updates:
            print("An update received.")
            if "message" in update:
                chat_id = update["message"]["chat"]["id"]
                if "text" in update["message"]:
                    text = update["message"]["text"]
                    if is_unicode(text):
                        print("Update content: {}".format(update))
                        bot.send_message(chat_id, bot.get_answer(update["message"]["text"]))
                    else:
                        bot.send_message(chat_id, "Hmm, you are sending some weird characters to me...")
            offset = max(offset, update['update_id'] + 1)
        time.sleep(1)
Ejemplo n.º 2
0
def main():
    args = parse_args()
    token = args.token

    if not token:
        if not "TELEGRAM_TOKEN" in os.environ:
            print(
                "Please, set bot token through --token or TELEGRAM_TOKEN env variable"
            )
            return
        token = os.environ["TELEGRAM_TOKEN"]

    paths = dict({
        'INTENT_RECOGNIZER': "intent_recognizer.pkl",
        'TFIDF_VECTORIZER': "TFIDF_VECTORIZER.pkl",
        'TAG_CLASSIFIER': "tag_classifier.pkl",
        'WORD_EMBEDDINGS': "GoogleNews-0.5Mvectors300.bin",
        'THREAD_EMBEDDINGS_FOLDER': "thread_embeddings_by_tags"
    })

    #################################################################

    # Your task is to complete dialogue_manager.py and use your
    # advanced DialogueManager instead of SimpleDialogueManager.

    # This is the point where you plug it into the Telegram bot.
    # Do not forget to import all needed dependencies when you do so.

    #simple_manager = SimpleDialogueManager()
    advanced_manager = DialogueManager(paths)
    advanced_manager.create_chitchat_bot()
    bot = BotHandler(token, advanced_manager)

    ###############################################################

    print("Ready to talk!")
    offset = 0
    while True:
        updates = bot.get_updates(offset=offset)
        for update in updates:
            print("An update received.")
            if "message" in update:
                chat_id = update["message"]["chat"]["id"]
                if "text" in update["message"]:
                    text = update["message"]["text"]
                    if is_unicode(text):
                        print("Update content: {}".format(update))
                        bot.send_message(
                            chat_id, bot.get_answer(update["message"]["text"]))
                    else:
                        bot.send_message(
                            chat_id,
                            "Hmm, you are sending some weird characters to me..."
                        )
            offset = max(offset, update['update_id'] + 1)
        time.sleep(1)
def main():
    args = parse_args()
    token = args.token

    if not token:
        if not "TELEGRAM_TOKEN" in os.environ:
            print(
                "Please, set bot token through --token or TELEGRAM_TOKEN env variable"
            )
            return
        token = os.environ["TELEGRAM_TOKEN"]

    #################################################################

    # Your task is to complete dialogue_manager.py and use your
    # advanced DialogueManager instead of SimpleDialogueManager.

    # This is the point where you plug it into the Telegram bot.
    # Do not forget to import all needed dependencies when you do so.

    #simple_manager = SimpleDialogueManager()
    #bot = BotHandler(token, simple_manager)
    dialogue_manager = DialogueManager(RESOURCE_PATH)
    dialogue_manager.create_chitchat_bot()
    bot = BotHandler(token, dialogue_manager)

    ###############################################################

    print("Ready to talk!")
    offset = 0
    while True:
        updates = bot.get_updates(offset=offset)
        for update in updates:
            print("An update received.")
            if "message" in update:
                chat_id = update["message"]["chat"]["id"]
                if "text" in update["message"]:
                    text = update["message"]["text"]
                    if is_unicode(text):
                        print("Update content: {}".format(update))
                        bot.send_message(
                            chat_id, bot.get_answer(update["message"]["text"]))
                    else:
                        bot.send_message(
                            chat_id,
                            "Hmm, you are sending some weird characters to me..."
                        )
            offset = max(offset, update['update_id'] + 1)
        time.sleep(1)
Ejemplo n.º 4
0
def main():
    token = '1547700302:AAERs9g0D40N-VvW0TIh5jvJc1EujMjC8nc'

    if not token:
        if not "TELEGRAM_TOKEN" in os.environ:
            print(
                "Please, set bot token through --token or TELEGRAM_TOKEN env variable"
            )
            return
        token = os.environ["TELEGRAM_TOKEN"]

    # This is the point where you plug it into the Telegram bot.
    # Do not forget to import all needed dependencies when you do so.

    dialogue_manager = DialogueManager(RESOURCE_PATH)
    dialogue_manager.create_chitchat_bot()
    bot = BotHandler(token, dialogue_manager)

    print("Ready to talk!")
    offset = 0
    while True:
        updates = bot.get_updates(offset=offset)
        for update in updates:
            print("An update received.")
            if "message" in update:
                chat_id = update["message"]["chat"]["id"]
                if "text" in update["message"]:
                    text = update["message"]["text"]
                    text = text.encode('ascii', 'ignore').decode('ascii')
                    if is_unicode(text):
                        print("Update content: {}".format(update))
                        bot.send_message(chat_id, bot.get_answer(text))
                    else:
                        bot.send_message(
                            chat_id,
                            "Hmm, you are sending some weird characters to me..."
                        )
                if "voice" in update["message"]:
                    file_id = update["message"]["voice"]["file_id"]
                    text = voice_recognition.get(update["message"], token)
                    print(f"Did u said '{text}'")
                    bot.send_message(chat_id, f"Did u said '{text}'")
                    print("Update content: {}".format(update))
                    bot.send_message(chat_id, bot.get_answer(text))

            offset = max(offset, update['update_id'] + 1)
        time.sleep(1)
Ejemplo n.º 5
0
def main():
    token = "959893539:AAEKPBviifT1oYt85_xW6G30ITF1_Xy8nQw"
    print(token)

    if not token:
        if not "TELEGRAM_TOKEN" in os.environ:
            print(
                "Please, set bot token through --token or TELEGRAM_TOKEN env variable"
            )
            return
        token = os.environ["TELEGRAM_TOKEN"]

        # This is the point where you plug it into the Telegram bot.
        # Do not forget to import all needed dependencies when you do so.

    dialogue_manager = DialogueManager()
    dialogue_manager.create_chitchat_bot()
    bot = BotHandler(token, dialogue_manager)

    print("Ready to talk!")
    offset = 0
    while True:
        updates = bot.get_updates(offset=offset)
        for update in updates:
            print("An update received.")
            if "message" in update:
                chat_id = update["message"]["chat"]["id"]
                if "text" in update["message"]:
                    text = update["message"]["text"]
                    if is_unicode(text):
                        print("Update content: {}".format(update))
                        bot.send_message(
                            chat_id, bot.get_answer(update["message"]["text"]))
                    else:
                        bot.send_message(
                            chat_id,
                            "Hmm, you are sending some weird characters to me..."
                        )
            offset = max(offset, update['update_id'] + 1)
        time.sleep(1)
Ejemplo n.º 6
0
def main():

    dialogue_manager = DialogueManager(RESOURCE_PATH)

    bot = BotHandler(dialogue_manager)

    print('\nCreating and Training Chatbot, this will take about 4 minutes, please wait...\n')
    dialogue_manager.create_chitchat_bot()
    print("Ready to talk!")

    host = '' # Get local machine name # "http://chat-chat.1d35.starter-us-east-1.openshiftapps.com"
    port = 8080

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, port))
    sock.listen(1)

    print('host: ', host)

    def before(value, a):
        # Find first part and return slice before it.
        pos_a = value.find(a)
        if pos_a == -1:
            return ""
        return value[0:pos_a]

    def after(value, a):
        # Find and validate first part.
        pos_a = value.rfind(a)
        if pos_a == -1:
            return ""
        # Returns chars after the found string.
        adjusted_pos_a = pos_a + len(a)
        if adjusted_pos_a >= len(value):
            return ""
        return value[adjusted_pos_a:]

    def parse_data(data):
        # old version (brute force):
        # question = before(after(data, '"text":"'), '"')
        # from_id = before(after(data, '"recipient":{"id":"'), '"')
        # conversation_id = before(after(data, '"conversation":{"id":"'), '"')
        # recipient_id = before(after(data, '"from":{"id":"'), '"')
        # reply_to_id = before(after(data, ',"id":"'), '"')

        # question = data['text']
        # from_id = data['recipient']['id']
        # conversation_id = data['conversation']['id']
        # recipient_id = data['from']['id']
        # reply_to_id = data['id']
        print('entre a -> parse_data()')
        question = data.get('text', '')
        from_id = data.get('recipient', {}).get('id', '')
        conversation_id = data.get('conversation', {}).get('id', '')
        recipient_id = data.get('from', {}).get('id', '')
        reply_to_id = data.get('id', '')

        return question, from_id, conversation_id, recipient_id, reply_to_id

    def handler(c, a, bot):
        while True:
            try:
                data = c.recv(1024)
                print(data)
                if data:
                    data_str = str(data, 'utf-8')

                    (request_header, request_body) = data_str.split("\r\n\r\n")
                    request_body = json.loads(request_body)
                    request_type = request_body.get('type', '')
                    print('request type ->', request_type)
                    if request_type == 'message':
                        print('voy a -> parse_data()')
                        question, from_id, conversation_id, recipient_id, reply_to_id = parse_data(
                            request_body)
                        print('regrese de -> parse_data()')
                        print('question ->', question)
                        print('voy a -> bot.get_answer()')
                        text = bot.get_answer(question)
                        # text = 'respuesta de prueba'
                        print('ya regrese de -> bot.get_answer()')
                        print('text ->', text)
                        if text == '':
                            text = "Hmm, you are sending some weird characters to me..."

                        print('\nquestion:', question, '\nanswer:', text)

                        body = {'type': 'message', 'from': {'id': from_id, 'name': 'Walter bot'},
                                'conversation': {'id': conversation_id, 'name': 'Walter conversation'},
                                'recipient': {'id': recipient_id, 'name': 'Walter user'},
                                'text': text, 'replyToId': reply_to_id}

                        body_json = json.dumps(body)

                        # c.send(bytes(text, "utf8"))

                        base_url = request_body.get('serviceUrl', '')
                        try:
                            api_url = urljoin(
                                base_url, '/v3/conversations/' + conversation_id + '/activities/' + reply_to_id)
                            requests.post(api_url, data=body_json, headers={
                                          'Authorization': 'Bearer',
                                          'Content-Type': 'application/json'})
                            # c.send(bytes('HTTP/1.1 200 OK', 'utf-8'))
                            # print('sending body...', bytes(body_json, 'utf-8'))
                            # c.send(bytes(body_json, 'utf-8'))
                            # finally:
                            #     pass
                        except:
                            print('something wrong with the post!')

                else:
                    # print('no data')
                    break

            except:
                break

        c.close()

    while True:
        c, a = sock.accept()
        c.send(bytes('HTTP/1.1 200 OK', 'utf-8'))
        cThread = threading.Thread(target=handler, args=(c, a, bot))
        cThread.daemon = True
        cThread.start()
        print('connection: ', c)
        print('argument: ', a)