使用 Python Facebook SDK 读取页面消息

Reading page's messages with Python Facebook SDK

基本上我需要在 python 中使用 facebook SDK 获取页面的所有消息。 按照一些教程我到达了这一点:

import facebook

def main():
  cfg = {
    "page_id"      : "MY PAGE ID", 
    "access_token" : "LONG LIVE ACCESS TOKEN"  
    }

  api = get_api(cfg)
  msg = "Hre"
  status = api.put_wall_post(msg) #used to post to wall message Hre
  x = api.get_object('/'+str(MY PAGE ID)+"/conversations/") #Give actual  conversations


def get_api(cfg):
  graph = facebook.GraphAPI(cfg['access_token'])
  resp = graph.get_object('me/accounts')
  page_access_token = None
  for page in resp['data']:
    if page['id'] == cfg['page_id']:
      page_access_token = page['access_token']
  graph = facebook.GraphAPI(page_access_token)
  return graph

if __name__ == "__main__":
  main()

第一个问题是 api.get_object('/'+str(MY PAGE ID)+"/conversations/")returns 一个包含许多信息的字典,但我想看到的是他们发送给我的消息,而现在它打印用户 ID给我发了一条消息。

输出如下所示:

{u'paging': {u'next': u'https://graph.facebook.com/v2.4/571499452991432/conversations?access_token=Token&limit=25&until=1441825848&__paging_token=enc_AdCqaKAP3e1NU9MGSsvSdzDPIIDtB2ZCe2hCYfk7ft5ZAjRhsuVEL7eFYOOCdQ8okvuhZA5iQWaYZBBbrZCRNW8uzWmgnKGl69KKt4catxZAvQYCus7gZDZD', u'previous': u'https://graph.facebook.com/v2.4/571499452991432/conversations?access_token=token&limit=25&since=1441825848&__paging_token=enc_AdCqaKAP3e1NU9MGSsvSdzDPIIDtB2ZCe2hCYfk7ft5ZAjRhsuVEL7eFYOOCdQ8okvuhZA5iQWaYZBBbrZCRNW8uzWmgnKGl69KKt4catxZAvQYCus7gZDZD&__previous=1'}, u'data': [{u'link': u'/communityticino/manager/messages/?mercurythreadid=user%3A1055476438&threadid=mid.1441825847634%3Af2e0247f54f5c4d222&folder=inbox', u'id': u't_mid.1441825847634:f2e0247f54f5c4d222', u'updated_time': u'2015-09-09T19:10:48+0000'}]}

基本上是 pagingdata。 鉴于此,有没有办法阅读对话?

为了获取消息内容,您首先需要请求对话中的单个消息,可通过您复制的字典中的 'id' 字段访问,结果为 x = api.get_object('/'+str(MY PAGE ID)+"/conversations/") #给出实际对话

您可以通过调用

请求对话中的消息
msg = api.get_object('/'+<message id>)

这里有点棘手,因为按照图表 api 文档,您应该收到一个字典,其中包含所有可能的字段,包括 'message'(内容)字段。但是函数 returns 仅字段 'created_time' 和 'id'。 感谢这个其他问题 Request fields in Python Facebook SDK 我发现您可以通过添加一个字典来请求这些字段,其中包含在 graph.get_object() 函数的参数中指定的此类字段。据我所知,这在 python.

的 facebook sdk 参考中没有记录

正确的代码是

args = {'fields' : 'message'}
msg = api.get_object('/'+<message id>, **args)

类似问题: