在twilio + flask + python + whatsapp自动化中出错

问题描述

我正在尝试使用python进行Whatsapp自动化,而烧瓶在Whatsapp中向Twilio发送消息时出现了一些错误。我的代码是这个

from flask import Flask,request
from twilio.twiml.messaging_response import MessagingResponse
import io
import datetime
#import xmlrpc.client import strftime

appbot=Flask(__name__)
@appbot.route("/sms",methods=["get","post"])

def reply():
    with io.open("response.csv","a",encoding="utf-8")as f1:
        ur = request.form.get("Body")
        un = request.form.get("From")
        print(un)
        print(ur)
        un = un.replace("whatsapp:","")
        dt=datetime.datetime.Now().strftime("%y%m%d--%H%M%s")
        data = un+","+ur+","+dt
        f1.write(data)
        resp = MessagingResponse("You sent"+" "+ur+"from"+" "+un+"on"+" "+dt)
        return(str(resp))
    
    f1.close()
    
    
if (__name__ == "__main__"):
    appbot.run()

首先,我还必须在Twilio中更改链接,但仍然会出错。

[2020-08-23 13:23:19,609] ERROR in app: Exception on /sms [POST]
Traceback (most recent call last):
  File "C:\Users\KENIL\Anaconda3\lib\site-packages\flask\app.py",line 2446,in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\KENIL\Anaconda3\lib\site-packages\flask\app.py",line 1951,in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\KENIL\Anaconda3\lib\site-packages\flask\app.py",line 1820,in handle_user_exception
    reraise(exc_type,exc_value,tb)
  File "C:\Users\KENIL\Anaconda3\lib\site-packages\flask\_compat.py",line 39,in reraise
    raise value
  File "C:\Users\KENIL\Anaconda3\lib\site-packages\flask\app.py",line 1949,in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\KENIL\Anaconda3\lib\site-packages\flask\app.py",line 1935,in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "G:/P P SAVANI SCHOOL OF ENGINEERING/4 Forth year/Others/chatbot/udemychat/app.py",line 27,in reply
    resp = MessagingResponse("You sent"+" "+ur+"from"+" "+un+"on"+" "+dt)
TypeError: __init__() takes 1 positional argument but 2 were given
127.0.0.1 - - [23/Aug/2020 13:23:19] "POST /sms HTTP/1.1" 500 -

解决方法

您需要实例化一个响应并在其上调用.message方法。

来自文档的

https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-python

@app.route("/sms",methods=['GET','POST'])
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Start our TwiML response
    resp = MessagingResponse()

    # Add a message
    resp.message("The Robots are coming! Head for the hills!")

您收到的错误来自以下事实:一个类的所有方法(包括__init__)都在self中传递,这就是为什么您传递的消息成为第二个参数并且Python抛出该错误的原因TypeError: __init__() takes 1 positional argument but 2 were given错误