使用 Twilio,我可以在调用中使用 POST 方法在 python 中创建 status_callback_method 并获取参数值吗

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

我已经使用 GET 方法成功完成了此操作:

    call = client.calls.create(
          method='POST',
          status_callback=twilioUrl+'/api/callstatus',
          status_callback_event=['initiated', 'ringing', 'answered', 'completed'],
          status_callback_method='GET',
          url=twilioUrl+'/api/createcallback',
          to=self.to_number,
          from_=self.from_number
          )

FastAPI回调中对应的回调如下:

@app.get("/api/callstatus")
async def get(request: Request):
    query_params = request.query_params
    to_number = query_params.get('To', None)
    from_number = query_params.get('From', None)
    status = query_params.get('CallStatus', None)
    print("Call from: ",from_number," to: ", to_number," has status: ",status)

但是如果我尝试切换到 POST 方法,我无法获得相同的参数。关于如何从类似的 POST 方法中提取相同的值有什么建议吗?谢谢!

python callback twilio
1个回答
0
投票

当您明确声明许多默认值(例如

method='POST'
)时,您的代码可能可以实现相同的效果,同时减少行数。此代码应该是一个最小的示例,展示了如何拨打电话并注册回调。

请记住,webhook 需要指向 FQDN,例如

https://mobert.ngrok.io/callback
:

import os

import twilio.jwt.access_token
import twilio.jwt.access_token.grants
import twilio.rest
import logging
from dotenv import load_dotenv
from flask import Flask, request

# Load environment variables from a .env file
load_dotenv()

# Create a Twilio client
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
api_key = os.environ["TWILIO_API_KEY_SID"]
api_secret = os.environ["TWILIO_API_KEY_SECRET"]
caller = os.environ["TWILIO_NUMBER"]
callee = os.environ["MARIUS_NUMBER"]
twilio_client = twilio.rest.Client(api_key, api_secret, account_sid)

# Create a Flask app
app = Flask(__name__)


# Create a route that just returns "In progress"
@app.route("/")
def serve_homepage():
    return "In progress!"


@app.route('/callback', methods=['POST'])
def outbound():
    status = request.values.get('CallbackSource', None)
    from_number = request.values.get('From', None)
    logging.warning('Status: {}'.format(status))
    logging.warning('From: {}'.format(from_number))
    return ('', 204)


# Start the server when this file runs
if __name__ == "__main__":

    twilio_client.calls.create(
        url='http://demo.twilio.com/docs/voice.xml',
        to=callee,
        from_=caller,
        status_callback="https://mobert.ngrok.io/callback"
    )
    app.run(host="0.0.0.0", port=3000, debug=True)

© www.soinside.com 2019 - 2024. All rights reserved.