简体   繁体   English

回复传入的媒体消息| Twilio Whatsapp API | 内部服务器错误

[英]Reply to Incoming Media Messages | Twilio Whatsapp API | Internal Server Error

I am using Twilio whatsapp API to reply to media messages. 我正在使用Twilio whatsapp API回复媒体消息。 Whenever somebody will message me on whatapp with a picture, Twilio will respond with message "Thanks for the image" with a dog picture and if somebody texts the twilio number, then it responds "Send us an image!", again with a dog picture. 每当有人在whatapp上用图片向我发送消息时,Twilio就会用狗图片用消息“感谢图像”进行响应,如果有人用短信发送了twilio号,则它会用狗图片来响应“向我们发送图像!”。 。

When I sent a text message, I am getting a dog picture with text "Send us an image", but the other function is not working. 当我发送一条短信时,我收到一张带有“发送给我们图像”文本的狗图片,但其他功能不起作用。 在此处输入图片说明

The error I think is in the server I am writing. 我认为该错误是在我正在编写的服务器中。 Because it keeps generating error, even though I am following their official documentation , but keeps getting error. 因为它一直在产生错误,所以即使我遵循他们的官方文档 ,也一直在出错。

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


app = Flask(__name__)


GOOD_BOY_URL = "https://images.unsplash.com/photo-1518717758536-85ae29035b6d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80"


@app.route("/whatsapp", methods=["GET", "POST"])
def reply_whatsapp():

    num_media = int(request.values.get("NumMedia"))
    response = MessagingResponse()
    if not num_media:
        msg = response.message("Send us an image!")
    else:
        msg = response.message("Thanks for the image(s).")
    msg.media(GOOD_BOY_URL)
    return str(response)


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

Error 错误

Traceback (most recent call last):
  File "C:\Users\mnauf\Anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\mnauf\Anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\mnauf\Anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\mnauf\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\Users\mnauf\Anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\mnauf\Anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "c:/Users/mnauf/Desktop/IOT/twilio/whatsapp/replyWithMediaToIncomingMsg.py", line 19, in reply_whatsapp
    num_media = int(request.values.get("NumMedia"))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
127.0.0.1 - - [11/May/2019 10:05:02] "GET /whatsapp HTTP/1.1" 500 -
[2019-05-11 10:06:07,095] ERROR in app: Exception on /whatsapp [GET]

If I understand correctly, it works when you send just a text message, but when you send a message with an image attached, it does not work. 如果我理解正确,那么当您仅发送文本消息时它可以工作,但是当您发送带有图像的消息时,它就无法工作。

Twilio's tutorial is masking (blurring out) some code to emphasize the changes between steps, and to me it appears that this feature is not working properly, so you're missing some code (the part to handle incoming media attachments). Twilio的教程掩盖(模糊)了一些代码以强调步骤之间的更改,对我来说,此功能似乎无法正常工作,因此您缺少了一些代码(用于处理传入的媒体附件的部分)。

The complete code is below, and also, you need to create an app_data folder to store incoming media files. 完整的代码在下面,并且, 您还需要创建一个app_data文件夹来存储传入的媒体文件。



import mimetypes
import os
from urllib.parse import urlparse

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


app = Flask(__name__)


GOOD_BOY_URL = "https://images.unsplash.com/" \
    "photo-1518717758536-85ae29035b6d?" \
    "ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80"


@app.route("/whatsapp", methods=["GET", "POST"])
def reply_whatsapp():

    num_media = int(request.values.get("NumMedia"))
    media_files = []
    for idx in range(num_media):
        media_url = request.values.get(f'MediaUrl{idx}')
        mime_type = request.values.get(f'MediaContentType{idx}')
        media_files.append((media_url, mime_type))

        req = requests.get(media_url)
        file_extension = mimetypes.guess_extension(mime_type)
        media_sid = os.path.basename(urlparse(media_url).path)

        with open(f"app_data/{media_sid}{file_extension}", 'wb') as f:
            f.write(req.content)

    response = MessagingResponse()
    if not num_media:
        msg = response.message("Send us an image!")
    else:
        msg = response.message("Thanks for the image(s).")
    msg.media(GOOD_BOY_URL)
    return str(response)


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM