需要修复错误,使用 flask twilio 和 openai 与 python 构建 whatsapp 聊天机器人与 openai 集成

问题描述 投票:0回答:0

我正在为我的公司构建一个聊天机器人,用作客户支持机器人 附加的是我目前拥有的代码

需要

pip install twilio openai flask

from flask import Flask, request, jsonify
from twilio.rest import Client
import openai
import os

app = Flask(__name__)
__app__ = app # define the __app__ variable

# define a route for incoming WhatsApp messages
@app.route('/incoming', methods=['GET','POST'])
def handle_incoming_message():
    # get the incoming message data
    data = request.get_json()
    app.logger.debug('Incoming request: {}'.format(data))
    print(data)

    # extract the sender ID and message text
    sender_id = data['sender']
    message_text = data['text']

    # Define the prompt you want to generate text from
    prompt = message_text

    # Set up the API client with your API key
    openai.api_key = "OPENAI_KEY"

    # Call the API to generate text
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=prompt,
        max_tokens=500,
        n=1,
        stop=None,
        temperature=0.5,
    )

    # Get the generated response text
    generated_text = response.choices[0].text.strip()

    # Send the generated response back to the user on WhatsApp
    account_sid = 'TWILIO_ACC_SID'
    auth_token = 'TWILIO_AUTH_TOKEN'
    client = Client(account_sid, auth_token)

    message = client.messages.create(
        from_='whatsapp:+14155238886',
        body=generated_text,
        to=f'whatsapp:+',
        status_callback='SERVER_URL/whatsapp/status'
    )

    print(message.sid)

    # return an empty response (WhatsApp will expect this)
    return jsonify({})

if __name__ == '__main__':
    app.run(debug=False, port=int(os.environ.get('PORT', 5000)), host='127.0.0.1')

有了这段代码,我希望 Twilio 能够接受我在 Whatsapp 上发送给他们的任何提示,并生成响应并通过 Whatsapp 发回,就像聊天机器人所做的那样。

结果是这个错误: 在 Ngrok 服务器上运行代码后,通过 whatsapp 向 Twilio 发送消息 这出现在我的终端

127.0.0.1 - - [31/Mar/2023 17:22:44] "POST /incoming HTTP/1.1" 400 -

想看看哪里出了问题,我该怎么做才能让 Twilio 收到我的消息。 似乎 Twilio 识别出一条消息已发送,但无法分辨它是什么。

python flask chatbot whatsapp openai-api
© www.soinside.com 2019 - 2024. All rights reserved.