python - Twilio 和 Python 的 session 聊天机器人无法正常工作

标签 python twilio chatbot whatsapp

我正在尝试教我的女朋友如何构建聊天机器人。

我们学习了有关基于规则的聊天机器人基础知识的代码学院类(class),并尝试将其集成到 Twilio 中(在 Facebook Messenger 出现问题之后)。

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse




app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

@app.route("/sms", methods=['POST'])
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Fetch the message
    msg = request.form.get('Body')

    # Create reply
    if msg == "bunny" or "michael":

        resp = MessagingResponse()
        resp.message("You said: {}".format(msg))

        return str(resp)


if __name__ == "__main__":
    app.run(debug=True)

将此代码与 Twilio 结合使用可以很好地通过 WhatsApp 解析如上所示的简单内容。

但是,将其集成到这个聊天机器人中会让人感到困惑。您如何使用 twilio 发送和接收消息以使下面的代码正常工作?我玩了一把,但无法正常工作。

import re
import random

class BunnyBot:
  # potential negative responses
  negative_responses = ("no", "nope", "nah", "naw", "not a chance", "sorry")
  # keywords for exiting the conversation
  exit_commands = ("quit", "pause", "exit", "goodbye", "bye", "later", "goodbye", "got to go")
  # random starter questions
  random_questions = (
        "How's your day going Mummy Bunny? ",
        "What do you do when you leave the house? ",
        "What did you have to eat today? I had some fresh weeds. ",
        "Are there other bunnies like me? ",
        "Do you want to come hang out with me in the garden? ",
        "Would you like to help me dig a hole? ",
        "Do you have any carrots today? "
    )

  def __init__(self):
    self.bunnybabble = {'hows_your_day_intent': '.*\s*your day.*','carrots_intent': '.\s*carrot.*', 'cubed_intent': '.*.*(\d+)'}

  # Define .greet() below:
  def greet(self):
    self.name = input("Hi there. Who I am talking to?")
    will_chat = input(f"Hey {self.name}! Do you want to chat with me? ")
    if will_chat in self.negative_responses:
      print ("No worries, see you later! xxx")
      return
    self.chat()

  # Define .make_exit() here:
  def make_exit(self, reply):
    for word in self.exit_commands:
      if word in reply:
        print ("Bye for now! I hope we can chat later xxx")
        return True

  # Define .chat() next:
  def chat(self):
    reply = input(random.choice(self.random_questions)).lower()
    while not self.make_exit(reply):
      reply = input(self.match_reply(reply))

  # Define .match_reply() below:
  def match_reply(self, reply):
    found = False
    for intent, regPattern in self.bunnybabble.items():
      found_match = re.findall(regPattern, reply)
      if found_match and intent == 'hows_your_day_intent':
        return self.hows_your_day_intent()
      elif found_match and intent == 'carrots_intent':
        return self.carrots_intent()
      elif found_match and intent == 'cubed_intent':
        return self.cubed_intent(found_match[0])
    if not found:
      return self.no_match_intent()

  def hows_your_day_intent(self):
    responses = ("Pretty relaxing, I've just been napping. ", "Great! I dug a tunnel, do you want to see? ", "Good, but I'm kind of hungry, do you have any snacks? ", "It's been alright, but I'm a bit lonely and would love a pat. ", "So good, just been eating some curtains! ")
    return random.choice(responses)

  def carrots_intent(self):
    responses = ("I love carrots! Can I have one now? ", "Unfortunately I never get a full carrots, only the peel. ", "Carrots are good but so is apple! Do you have a snack for me? ")
    return random.choice(responses)

  def cubed_intent(self, number):
    number = int(number)
    cubed_number = number * number * number
    return (f"The cube of {number} is {cubed_number}. Who knew bunnies were good at maths? ")

  def plans_for_today_intent(self):
    responses = ("I might see if my pigeon friends are around! ", "Maybe hang out with Mummy Bunny if she's doing some gardening. ", "Probably watch some TV with Mummy Bunny and Nicole. ", "I'm just going to hang around until some weeds appear for me to eat. ")
    return random.choice(responses)

  def love_me_intent(self):
    responses = ("Of course I do, you're the best Mummy Bunny ever! ", "I love you so much, no one else gets me weeds like you do. ", "Yes I do, you give the best pats and jaw rubs. ", "Absolutely, thanks for always looking after me. ")
    return random.choice(responses)

  def my_name_intent(self):
    responses = ("Honestly, I'm not sure. It's either Bunny, Fluffy Bun or Heather. It's a bit confusing. ", "Well, someone once mentioned Flat Bunny which got me a little worried. ", "Mummy Bunny calls me Bunny Bun a lot? ")
    return random.choice(responses)

  def favourite_intent(self):
    responses = ("Mummy Bunny obviously. She looks after me. ", "Nicole is pretty cool, after all, I am technically her rabbit. She can be pretty loud though. ", "Natalie is nice to me, but I never really see her anymore which is sad. ")
    return random.choice(responses)

  def no_match_intent(self):
    responses = ("Please tell me more. ", "Tell me more! ", "Why do you say that? ", "I see. Can you elaborate? ", "Interesting. Can you tell me more? ", "I see. How do you think? ", "Why? ", "How do you think I feel when you say that? ")
    return random.choice(responses)


my_bot = BunnyBot()
my_bot.greet()

我认为它与利用 thw twillio 消息响应有关,但我不明白它如何记住过去说过的话?

更新

这是新代码,尝试根据此处的 youtube 教程与 Twilio 一起使用:

https://www.youtube.com/watch?v=EeUdel2AJ5g

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

import re
import random


def send(msg):
    resp = MessagingResponse()
    resp.message(format(msg))
    return str(resp)


def recv():
    return request.form.get('Body')


app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello, World!"


@app.route("/sms", methods=['POST'])
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Fetch the message
    msg = request.form.get('Body')

    # Create reply
    if msg == "bunny" or "michael":

        resp = MessagingResponse()
        resp.message("You said: {}".format(msg))

        return str(resp)


class BunnyBot:
    # potential negative responses
    negative_responses = ("no", "nope", "nah", "naw", "not a chance", "sorry")
    # keywords for exiting the conversation
    exit_commands = ("quit", "pause", "exit", "goodbye",
                     "bye", "later", "goodbye", "got to go")
    # random starter questions
    random_questions = (
        "How's your day going Mummy Bunny? ",
        "What do you do when you leave the house? ",
        "What did you have to eat today? I had some fresh weeds. ",
        "Are there other bunnies like me? ",
        "Do you want to come hang out with me in the garden? ",
        "Would you like to help me dig a hole? ",
        "Do you have any carrots today? "
    )

    def __init__(self):
        self.bunnybabble = {'hows_your_day_intent': '.*\s*your day.*',
                            'carrots_intent': '.\s*carrot.*', 'cubed_intent': '.*.*(\d+)'}

    # Define .greet() below:
    def greet(self):
        self.name = recv("Hi there. Who I am talking to?")
        will_chat = recv(f"Hey {self.name}! Do you want to chat with me? ")
        if will_chat in self.negative_responses:
            send("No worries, see you later! xxx")
            return
        self.chat()

    # Define .make_exit() here:
    def make_exit(self, reply):
        for word in self.exit_commands:
            if word in reply:
                send("Bye for now! I hope we can chat later xxx")
                return True

    # Define .chat() next:
    def chat(self):
        reply = recv(random.choice(self.random_questions)).lower()
        while not self.make_exit(reply):
            reply = recv(self.match_reply(reply))

    # Define .match_reply() below:
    def match_reply(self, reply):
        found = False
        for intent, regPattern in self.bunnybabble.items():
            found_match = re.findall(regPattern, reply)
            if found_match and intent == 'hows_your_day_intent':
                return self.hows_your_day_intent()
            elif found_match and intent == 'carrots_intent':
                return self.carrots_intent()
            elif found_match and intent == 'cubed_intent':
                return self.cubed_intent(found_match[0])
        if not found:
            return self.no_match_intent()

    def hows_your_day_intent(self):
        responses = ("Pretty relaxing, I've just been napping. ", "Great! I dug a tunnel, do you want to see? ", "Good, but I'm kind of hungry, do you have any snacks? ",
                     "It's been alright, but I'm a bit lonely and would love a pat. ", "So good, just been eating some curtains! ")
        return random.choice(responses)

    def carrots_intent(self):
        responses = ("I love carrots! Can I have one now? ", "Unfortunately I never get a full carrots, only the peel. ",
                     "Carrots are good but so is apple! Do you have a snack for me? ")
        return random.choice(responses)

    def cubed_intent(self, number):
        number = int(number)
        cubed_number = number * number * number
        return (f"The cube of {number} is {cubed_number}. Who knew bunnies were good at maths? ")

    def plans_for_today_intent(self):
        responses = ("I might see if my pigeon friends are around! ", "Maybe hang out with Mummy Bunny if she's doing some gardening. ",
                     "Probably watch some TV with Mummy Bunny and Nicole. ", "I'm just going to hang around until some weeds appear for me to eat. ")
        return random.choice(responses)

    def love_me_intent(self):
        responses = ("Of course I do, you're the best Mummy Bunny ever! ", "I love you so much, no one else gets me weeds like you do. ",
                     "Yes I do, you give the best pats and jaw rubs. ", "Absolutely, thanks for always looking after me. ")
        return random.choice(responses)

    def my_name_intent(self):
        responses = ("Honestly, I'm not sure. It's either Bunny, Fluffy Bun or Heather. It's a bit confusing. ",
                     "Well, someone once mentioned Flat Bunny which got me a little worried. ", "Mummy Bunny calls me Bunny Bun a lot? ")
        return random.choice(responses)

    def favourite_intent(self):
        responses = ("Mummy Bunny obviously. She looks after me. ", "Nicole is pretty cool, after all, I am technically her rabbit. She can be pretty loud though. ",
                     "Natalie is nice to me, but I never really see her anymore which is sad. ")
        return random.choice(responses)

    def no_match_intent(self):
        responses = ("Please tell me more. ", "Tell me more! ", "Why do you say that? ", "I see. Can you elaborate? ",
                     "Interesting. Can you tell me more? ", "I see. How do you think? ", "Why? ", "How do you think I feel when you say that? ")
        return random.choice(responses)


if __name__ == "__main__":
    app.run(debug=True)

尝试使用 Ngrok 但还不能正常工作 - 有什么线索吗?

最佳答案

你快到了。

长话短说

您的机器人在命令行上运行良好。 唯一的问题是将它挂接到 twilio

分步解决方案。

  1. 使用 twilio 代码创建两个函数。发送和接收函数 即
def send(msg):
        resp = MessagingResponse()
        resp.message(format(msg))
        return str(resp)

def recv():
        return request.form.get('Body')
  1. 测试这些功能,如果需要修改。因为我没有帐户,所以没有测试。
  2. 将 print 更改为 send 并将 input 更改为 sendrecv

输入

msg = input("Hi there. Who I am talking to?")
# change it to
send("Hi there. Who I am talking to?")
msg = recv()

打印

print ("No worries, see you later!")
#change this to
send("No worries, see you later!")

这样你就会有工作的聊天机器人

为什么要使用发送和接收函数?

当您将机器人扩展或移植到其他平台(例如 电报或推特或不同的供应商,如 gupshup.io

关于python - Twilio 和 Python 的 session 聊天机器人无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61615942/

相关文章:

Python 导入错误 : No module named wmi

jquery - 如何使用jquery ajax从node.js文件中检索数据

java - 增加 DialogFlow (api.ai) Android SDK 中的监听超时

python - 任何 n_jobs 进行交叉验证的内存泄漏

python - 旧版本 Python 中字典中的键顺序

ios - 具有媒体和自定义属性的 Twilio 可编程聊天消息

twilio - 将 Amazon Lex 与 twilio 结合使用

node.js - 如何将 INTENT_CONFIDENCE 断言者作为全局变量放入 Botium

nlp - 计算梯度PyTorch 中嵌入向量的值

python - 如何将 Python 的 urllib2.urlopen() 转换为文本?