You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Twilio API获取WhatsApp音频消息时遇HTTP 401未授权错误

Twilio API获取WhatsApp音频时遭遇HTTP 401未授权错误

尝试通过Twilio API获取用户发送的WhatsApp音频消息时,触发了HTTP 401未授权错误,错误详情如下:

ERROR:services.audio_processing:HTTP error: 401 Client Error:
Unauthorized for url:
https://api.twilio.com/2010-04-01/Accounts/ACa6d0fade9bfb1f8bfdd3238b6ca522b1/Messages/MM503f349644b344315426b6cb68e37ea9/Media/ME0bdd87db3d7c7e7fef2e153694b669e1
INFO:twilio.http_client:-- BEGIN Twilio API Request --
INFO:twilio.http_client:POST Request:
https://api.twilio.com/2010-04-01/Accounts/ACa6d0fade9bfb1f8bfdd3238b6ca522b1/Messages.json

用于提取音频的代码如下:

import os
import logging
import uuid
import requests
import urllib.request
from config.env_var import *

import openai
from twilio.rest import Client
from pydub import AudioSegment

logger = logging.getLogger(__name__)

# Find your Account SID and Auth Token at twilio.com/console
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

def process_audio(media_url):
    ogg_file_path = f'{OUTPUT_DIR}/{uuid.uuid1()}.ogg'
    mp3_file_path = f'{OUTPUT_DIR}/{uuid.uuid1()}.mp3'
    
    try:
        # Authenticated request to get the media file
        response = client.request("GET", media_url)
        print("Response status code: ", response.status_code)
        if response.status_code == 200:
            with open(ogg_file_path, 'wb') as file:
                file.write(response.content)
        else:
            raise Exception(f'Failed to download file: {response.status_code}')
        
        # Load the OGG file
        audio_file = AudioSegment.from_ogg(ogg_file_path)
        # Export the file as MP3
        audio_file.export(mp3_file_path, format="mp3")
        
        with open(mp3_file_path, 'rb') as audio_file:
            transcript = openai.Audio.transcribe(
                'whisper-1', audio_file, api_key=OPENAI_API_KEY)
        
        return {
            'status': 1,
            'text': transcript['text']
        }
    except Exception as e:
        logger.error(f'Error at transcript_audio: {e}')
        return {
            'status': 0,
            'text': 'Transcription failed'
        }
    finally:
        for path in [ogg_file_path, mp3_file_path]:
            if os.path.exists(path):
                os.unlink(path)

已确认Twilio Account SID和Auth Token无误,需排查错误原因。


可能的原因与解决办法

  • 媒体URL格式错误:直接传入完整媒体URL调用client.request时,Twilio客户端可能会重复拼接账户SID等信息,导致请求地址无效。应改为传递媒体资源的相对路径,比如/2010-04-01/Accounts/ACxxxx/Messages/MMxxxx/Media/MExxxx。
  • 环境变量加载异常:打印TWILIO_ACCOUNT_SID和TWILIO_AUTH_TOKEN的值,确认没有空格、换行或拼写错误,确保环境变量正确加载到代码中。
  • Twilio客户端版本问题:旧版本库可能存在请求处理bug,执行以下命令升级到最新版:
    pip install --upgrade twilio
    
  • 账户权限限制:检查Twilio账户是否被限制访问WhatsApp媒体资源,确认账户处于正常状态且无权限封禁。

内容的提问来源于stack exchange,提问作者Ari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 01:38:33