我有一种方法可以在Generic template向Facebook发送消息。 我的代码:
def send_receipt(self, fbid, title, url, img_url, summary):
return self._send(message={
"recipient": {
"id": fbid
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": title,
"item_url": url,
"image_url": img_url,
"subtitle": summary
}
]
}
}
}
})
它适用于我,但它只返回1个元素。我想从JSON中获取2或3个元素,所以我认为我可以通过创建一个元素对象来使它工作,并且该对象返回数组列表。
def send_receipt(self, fbid, elements):
return self._send(message={
"recipient": {
"id": fbid
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": elements
}
}
}
})
我确实制作了返回元素的方法。但我是蟒蛇新手,所以我所做的并不适合我。
elements = [{
"title": title,
"item_url": url,
"image_url": img_url,
"subtitle": summary }]
答案 0 :(得分:2)
我所做的是制作一个将结果转换为列表元素的方法
temp = []
for index, product in enumerate(products):
element = {'title': title,
'subtitle': sumary,
'item_url': item_url}
#not every product has image_url so to prevent KeyError, I have a if
if 'image_url' in product:
element['image_url'] = image_url
temp.append(element)
# In Facebook API element is limited to 10
if index == 9:
break
return temp