如何在发送用户的WhatsApp API中下载媒体文件



我目前正在为WhatsApp编写聊天机器人。我使用360dialog平台,这使得使用WhatsApp Business API成为可能。

当客户端发送消息时,我在应用程序的日志中看到以下JSON对象:

{
"messages": [
{
"from": "77773336633",
"id": "ABGGd3c1cGY_Ago61ytHsZknvtLv",
"image": {
"id": "ffd23134-2dae-4fed-b5f8-0ce7867b6ddd",
"mime_type": "image/jpeg",
"sha256": "bd02100d961b5a1dbaae1dd645485ebbfeda77b44e82c015f1cf29b05654ccb9"
},
"timestamp": "1605703542",
"type": "image"
}
],
"contacts": [
{
"profile": {
"name": "Nurzhan Nogerbek"
},
"wa_id": "77773336633"
}
]
}

我在文档中找不到任何关于如何下载此文件的信息。在我的情况下,我想上传客户端发送到我的文件存储的这个图像文件。请告诉我WhatsApp API的哪个URL方法负责此机制?

p.S.同时,我可以向客户端发送文件。官方文件中提供了这些信息。

这很棘手,因为poster工作了,但c#不适合我,我花了两天时间试图找到解决方案,最终完成了以下代码,它在c#中工作:

using HttpClient _httpClient = new HttpClient();
Uri uri = new Uri(mediaUrl);
var fileName = $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.jpeg";
string filePath = $"Files\{fileName}";
// NOTE: to save bandwidth, request compressed content
_httpClient.DefaultRequestHeaders.AcceptEncoding.Clear();
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
// NOTE: accept all languages
_httpClient.DefaultRequestHeaders.AcceptLanguage.Clear();
_httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("*"));
// NOTE: accept all media types
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg"));
var productValue = new ProductInfoHeaderValue("ScraperBot", "1.0");
var commentValue = new ProductInfoHeaderValue("(+http://www.API.com/ScraperBot.html)");
_httpClient.DefaultRequestHeaders.UserAgent.Add(productValue);
_httpClient.DefaultRequestHeaders.UserAgent.Add(commentValue);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", {WhatsApp_Access_Token});

HttpResponseMessage response = await _httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode();
var mediaType = response?.Content?.Headers?.ContentType?.MediaType ?? string.Empty;
var imageBytes = await response.Content.ReadAsByteArrayAsync();
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
fs.Write(imageBytes, 0, imageBytes.Length);
}

这里,{WhatsApp_Access_Token}是您的WhatsApp API永久令牌。

如果你有任何问题或疑问,请给我留言。

也许会有所帮助,试着看看吧:-

const URL = `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=1104480873777230&ext=1662705250&hash=ATuMx352sLrhKUegbQZSC8oLl3J5Vy3Z49lO4HwTUKWRYQ`;
const FROM = `video`;
const config = {
method: 'get',
url: URL, //PASS THE URL HERE, WHICH YOU RECEIVED WITH THE HELP OF MEDIA ID
headers: {
'Authorization': `Bearer ${token}`
},
responseType: 'arraybuffer'
};
axios(config)
.then(function (response) {
const ext = response.headers['content-type'].split("/")[1];
fs.writeFileSync(`${FROM}.${ext}`, response.data);
})
.catch(function (error) {
console.log(error);
});

我看到了这个线程,它最终帮助我获得了解决方案。以下是从whatsapp消息中检索媒体id的整个C#代码。没有代理的问题是,脸书会回复一条消息,说没有代理就不支持浏览器。

string whatsappBaseUrl = "https://graph.facebook.com/v15.0/";
string mediaId = "id you received in message";
string accesstoken =  "Your Whatsapp Access Token";
string agentHeader =  "WhatsApp/2.19.81 A";
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesstoken);
string url = $"{whatsappBaseUrl}{mediaId}";
var getMediaUrl = await _httpClient.GetAsync(url);
if (getMediaUrl.IsSuccessStatusCode)
{
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(agentHeader);

var response = await _httpClient.GetByteArrayAsync(mediaUrl);
Stream stream = new MemoryStream(response);
}

官方文档在https://developers.facebook.com/docs/whatsapp/api/media.中有一个会议

基本上,您必须发出GET请求才能下载媒体。

curl --request GET 
--url https://waba.360dialog.io/v1/media/{media id} 
--header 'D360-API-KEY: {your api token}'

对于整个消息周期(接收请求,下载音频文件,并使用OpenAI的Whisper进行转录(,在Python中:

定义检索文件、保存和转录的功能:

def retrieve_text(media_id, audio_name = 'received_audio'):
url = f"https://graph.facebook.com/v17.0/{media_id}/" # the media id obtained in the webhook
headers = {'Authorization': f'Bearer {access_token}' } # enter your access token here
response = requests.get(url, headers=headers) # get the message
file_url = response.json()['url'] # get the file url
response = requests.get(file_url, headers=headers) # get the file binary
open(audio_name+'.ogg', 'wb').write(response.content) # save the received file
audio_file = open(audio_name+'.ogg', "rb") # open the file
transcript = openai.Audio.transcribe("whisper-1", audio_file) # transcribe with OpenAI API
return transcript.text # return the transcription

然后,在您的Webhook中收到请求时:

incoming_msg = request.json
#messages = incoming_msg['entry'][0]['changes'][0]['value']['messages'][0]
media_id = message[0]['audio']['id']
retrieve_text(media_id)

最新更新