Exemple #1
0
''' 
    Events:
    messages,
    messaging_postbacks,
    '''
import json
from _thread import *
from flask import Flask, request
from pymessager.message import Messager, QuickReply
from utils.config import *
from utils.wit import *
from utils.api import *
from utils.ans import *

app = Flask(__name__)
client = Messager(ACCESS_TOKEN)

sender_id = ''
recipient_id = ''
text = ''


# Verify & confirms all requests can sent to bot
@app.route('/', methods=['GET'])
def fb_webhook():
    verify_token = request.args.get('hub.verify_token')
    if verify_token == VERIFY_TOKEN:
        return request.args.get('hub.challenge')
    else:
        return '200'
"""


https://github.com/davidchua/pymessenger/blob/master/examples/echo_bot.py

Better option
https://github.com/rehabstudio/fbmessenger
https://github.com/rehabstudio/fbmessenger/blob/master/example/main.py

"""
from pymessager.message import Messager
client = Messager(config.facebook_access_token)

import json

from flask import Flask, request

API_ROOT = 'api/'
FB_WEBHOOK = 'fb_webhook'

app = Flask(__name__)


@app.route(API_ROOT + FB_WEBHOOK, methods=["GET"])
def fb_webhook():
    verification_code = 'I_AM_VERIFICIATION_CODE'
    verify_token = request.args.get('hub.verify_token')
    if verification_code == verify_token:
        return request.args.get('hub.challenge')
Exemple #3
0
import os
import sys
import json
from datetime import datetime

import requests
from flask import Flask, request
from pymessager.message import Messager

app = Flask(__name__)
client = Messager('EAAD4hzOfxVcBAKVSvIbuqWBz7jmSv5ZARVsaUwLcXZB7ggB7eT7kejoF8OZC9feKDuencuGa9YZBZCAfidT7PN8ztXwElhQYnwiNgI9JHy6g51rXPgTvLfsLtDFh4cbrbxpuZC9SA0iGQO9DQ8iQL3O3kjD3vnm0NQquJ0ZCXuZAGgZDZD')

@app.route('/', methods=["GET"])
def fb_webhook():
    if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
        if not request.args.get("hub.verify_token") == os.environ["italia10"]:
            return "Verification token mismatch", 403
        return request.args["hub.challenge"], 200

    return "Hello world", 200

@app.route('/', methods=["POST"])
def fb_receive_message():
    message_entries = json.loads(request.data.decode('utf8'))['entry']
    for entry in message_entries:
        for message in entry['messaging']:
            if message.get('message'):
                print("{sender[id]} says {message[text]}".format(**message))
    return "Hi"

if __name__ == '__main__':
Exemple #4
0
#import to messenger api
import os,sys
from flask import Flask, request
from pymessenger.bot import Bot
from pymessager.message import Messager
import json
client = Messager("EAAGfWvt5cFABABZBFY3NL9JHFKEYn9dwswgCDgZAZA2DIDRL8fysezOqZCZAGbuOiKLkeKebNtrASCHODKFkefZAnK0chi3YpZAj0VUgHYqfN49mFUeFAn9ZA7eLvARngJ2SE2SzLR2Dh3h66NhyXM2ydafMvCY7ZAWQI8BLYWZAUKux4wbKielMbU")



#import to chatbot
import numpy as np
from sklearn import tree
from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5,strip_accents='unicode')

intencaos = []
corpus = []
pedido = []
listener = ''


file = open("dadosIntencoesChatBot.txt", "r") 
CONVERSATION = 1

for x in file:
  classe, texto = x.split(" - ")
  intencaos.append(classe)
  corpus.append(texto.rstrip())
Exemple #5
0
# -*- coding: utf-8 -*-
from chatterbot import ChatBot
import json
from pymessager.message import Messager
from flask import Flask, redirect, url_for, request

app = Flask(__name__)


#Get access token
def get_access_token():
    token = "EAAbTWtBx3EEBAPICjzhEI3fuZB2BjvZBEpZArTq8XZAwnnFeI5BqFYPTT8TgJpaLEYOGs8L0NHE1ZALwZCoK4PnGyBCRl0ULBq9Ygw4IjCxZCneYNsV3kQLZApummj4y054rpTZCEySxLAZCuqHhymfMAqMzi9LqSMGxVRsfOLwExx1QZDZD"
    return token


client = Messager(get_access_token())


#handle message
@app.route('/talk/<msg>', methods=['POST', 'GET'])
def talk(msg="Hi"):
    chatbot = ChatBot('Pyson', trainer='chatterbot.trainers.ListTrainer')
    #msg = "Hi"
    reply = ""
    resp = chatbot.get_response(msg)
    if (resp.confidence > 0.5 and msg.upper() != "BYE"):
        reply = resp.serialize()
    elif (msg.upper() != "BYE"):
        reply = "Sorry Didn't get you? Try these questions <br>"
        sample_questions = "Will i get a job after training?  - " + "When is the next workshop?   - " + "What is taught in 3 days workshop?"
        reply += sample_questions
app = Flask(__name__)
PAGE_ACCESS_TOKEN = "EAAHZAErTAOQQBALrqCBVYr5LkkSLm8ngNI6DLaHSGopNsk8RhZC9Oq0hjBgjsTqsGy0gyMZAAHRsjg9Aotmm8KW1R1z9ZCcduPZA2WnM1FYouXOW71O1LtMYbsaAxrS98BhTFyr33eoP4o4JusTZCXIqLBLeYox5ZAQi7jFhHcNONEEKZCqZAwFC2"
bot = Bot(PAGE_ACCESS_TOKEN)


@app.route('/', methods=['GET'])
def verify():
    if request.args.get("hub.mode") == "subscribe" and request.args.get(
            "hub.challenge"):
        if not request.args.get("hub.verify_token") == "test-app":
            return "Verification token mismatch", 403
        return request.args["hub.challenge"], 200
    return "Hello Cuong", 200


client = Messager(PAGE_ACCESS_TOKEN)
client.set_greeting_text(
    "Kính chào ban lãnh đạo công ty VNNet\n Tên em là Nguyễn Quốc Cường\n Đây là chatbot đầu tiên của em"
)
client.set_get_started_button_payload("Get Start")
#ggsearch = GoogleSearch()
button_list = [{
    "type": "web_url",
    "url": "https://www.facebook.com/cuong.nguyenquoc.7186",
    "title": "Thông tin về tôi"
}, {
    "type": "postback",
    "title": "Tin tức hôm nay",
    "payload": "payload"
}, {
    "type": "postback",
        except Exception as e:
            print(traceback.format_exc())  # si il y a un erreur

    return 'Ok'


#envoyer le message vers Skype
def process_messages(sender, text, service):
    bot.send_message(service, sender, text)


#########################################################################
#facebook bot

from pymessager.message import Messager
client = Messager(conf.fb_access_token)


@app.route('/webhook', methods=["GET"])
def fb_webhook():
    verification_code = conf.fb_verifing_token
    verify_token = request.args.get('hub.verify_token')
    if verification_code == verify_token:
        return request.args.get('hub.challenge')


@app.route('/webhook', methods=['POST'])
def fb_receive_message():
    message_entries = json.loads(request.data.decode('utf8'))['entry']
    for entry in message_entries:
        for message in entry['messaging']: