簡體   English   中英

在Facebook Messenger Bot中向用戶發送音頻

[英]Sending audio to user in Facebook messenger bot

我正在嘗試使用文件上傳功能將音頻文件發送給Facebook Messenger bot中的用戶。 官方文檔說,您可以通過終端中的curl命令來執行此操作。 該命令有效:

curl  \
  -F 'recipient={"id":user_id}' \
  -F 'message={"attachment":{"type":"audio", "payload":{}}}' \
  -F 'filedata=@mymp3.mp3;type=audio/mp3' \
  "https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN"

其中ACCESS_TOKEN是我頁面的令牌,“ mymp3.mp3”是我要發送的文件。

問題-如何使用請求庫在python中做同樣的事情?

我嘗試了這個:

with open("mymp3.mp3", "rb") as o:
    payload = {
        'recipient': "{id: 1336677726453307}",
        'message': {'attachment': {'type': 'audio', 'payload':{}}},
        'filedata':o, 'type':'audio/mp3'
    }
    files = {'recipient': {'id': '1336677726453307'},'filedata':o}
    headers = {'Content-Type': 'audio/mp3'}
    r = requests.post(fb_url, data=payload)
print r.text

我收到此錯誤:

{"error":{"message":"(#100) Message cannot be empty, must provide valid attachment or text","type":"OAuthException","code":100,"error_subcode":2018034,"fbtrace_id":"E5d95+ILnf5"}}

另外,嘗試了這個:

import requests
from requests_toolbelt import MultipartEncoder

m = MultipartEncoder(
    fields={
        'recipient': {'id': '1336677726453307'},
        'message': {'attachment': {'type': 'audio', 'payload':{}}},
        'filedata':(open("mymp3.mp3", "rb"), 'audio/mp3')
    }
)
headers = {'Content-Type': m.content_type}
r = requests.post(fb_url, data=m, headers=headers)
print r.text

我收到此錯誤:AttributeError:'dict'對象沒有屬性'encode'

好,我明白了(非常感謝我的同事!)

fb_url = 'https://graph.facebook.com/v2.6/me/messages'
data = {
    'recipient': '{"id":1336677726453307}',
    'message': '{"attachment":{"type":"audio", "payload":{}}}'
}
files = {
    'filedata': ('mymp3.mp3', open("mymp3.mp3", "rb"), 'audio/mp3')}
params = {'access_token': ACCESS_TOKEN}
resp = requests.post(fb_url, params=params, data=data, files=files)

我認為您的首次嘗試已接近目標,但您似乎在文件上傳方面遇到了困難。 首先,您需要了解curl作用。 curl文檔在這里 然后對請求執行相同的操作; 文檔在這里

據我了解,您可以嘗試:

with open("mymp3.mp3", "rb") as finput:
    data = {
        'recipient': "{id: 1336677726453307}",
        'message': {'attachment': {'type': 'audio', 'payload':{}}},
    }
    #
    files = {'filedata': ('mymp3.mp3', finput, 'audio/mp3')}
    # BTW you can remove the ACCESS_TOKEN from fb_url and pass it as params instead
    params = {'access_token': 'ACCESS_TOKEN'}
    resp = requests.post(fb_url, params=params, data=data, files=files)

print r.text

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM