安排Facebook聊天机器人在一天中的某个时间在Flask中讲话

时间:2018-12-03 23:29:47

标签: facebook flask chatbot

在聊天机器人应用程序下方;该应用程序运行良好,机器人可能会回答每条消息;我希望聊天机器人每天下午3点与用户对话;我在代码末尾使用“时间表”来启动函数hello;

所有东西都无法正常工作,而且我没有收到任何错误; python正在无限加载;

据我了解,会有2个无限循环,一个用于python,一个用于调度;所以我需要使用并发或类似的东西吗?

from flask import Flask, request

import requests
import time
import schedule
from datetime import datetime
app = Flask(__name__)

FB_API_URL = 'https://graph.facebook.com/v2.6/me/messages'
VERIFY_TOKEN = "blabla"
PAGE_ACCESS_TOKEN = "blabla"

def Hello(message):
    return "Hello, how are you doing today '{}'".format(message)

def get_bot_response(message):
    """this is a dummy response to what the user says."""
    return "maybe '{}'".format(message)


def verify_webhook(req):
    if req.args.get("hub.verify_token") == VERIFY_TOKEN:
        return req.args.get("hub.challenge")
    else:
        return "incorrect"

def respond(sender, message):
    response = get_bot_response(message)
    send_message(sender, response)


def is_user_message(message):
    """Check if the message is a message from the user"""
    return (message.get('message') and
            message['message'].get('text') and
            not message['message'].get("is_echo"))


@app.route("/webhook",methods=['GET','POST'])
def listen():
    """This is the main function flask uses to 
    listen at the `/webhook` endpoint"""
    if request.method == 'GET':
        return verify_webhook(request)

    if request.method == 'POST':
        payload = request.json
        event = payload['entry'][0]['messaging']
        for x in event:
            if is_user_message(x):
                text = x['message']['text']
                sender_id = x['sender']['id']
                respond(sender_id, text)

        return "ok"



def send_message(recipient_id, text):
    """Send a response to Facebook"""
    payload = {
        'message': {
            'text': text
        },
        'recipient': {
            'id': recipient_id
        },
        'notification_type': 'regular'
    }

    auth = {
        'access_token': PAGE_ACCESS_TOKEN
    }

    response = requests.post(
        FB_API_URL,
        params=auth,
        json=payload
    )

    return response.json()


if __name__ == "__main__":
    app.run(port=5000)
    schedule.every().sunday.at("15:00").do(hello)

0 个答案:

没有答案