web-dev-qa-db-ja.com

pythonを使用してFacebookに投稿を書く方法

私はgoogle。で見つけたサンプルコードを試してみました。

_import facebook

def main():
   # Fill in the values noted in previous steps here
    cfg = {
    "page_id"      : "XXXXXXXXXXXXXX",  # Step 1
    "access_token" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"   # Step 3
    }

    api = get_api(cfg)
    msg = "Hello, world!"
    status = api.put_wall_post(msg)

def get_api(cfg):
     graph = facebook.GraphAPI(cfg['access_token'])
     # Get page token to post as the page. You can skip 
     # the following if you want to post as yourself. 
     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()
_

しかし、私はこのエラーを得ています:

AssertionError:書き込み操作には、status = api.put_wall_post(msg)行にアクセストークンが必要です。

誰かが問題を解決するのを手伝ってくれる?

images

6
sowmya

上記のコードは、ページIDとアクセストークンを指定すると問題なく機能します。以下の手順に従って、アクセストークンとページIDを取得してください。

  1. Graph API Explorer に移動します

2.ドロップダウンメニューからアプリを選択します。

3.「アクセストークンを取得」をクリックします

4. manage_pages権限を選択します(user_events権限も必要な場合がありますが、わかりません)。

5. me/accounts接続にアクセスして、ページのaccess_tokenをコピーします。

6.ページのIDをクリックします

7. GETフィールドにページのaccess_tokenを追加します

8.必要な接続を呼び出します(例:PAGE_ID/events)

このトピックは、 ページのFacebookアクセストークン ですでに説明されています。

1
sandeep kumar

Pythonを使用してFacebookに投稿を書き込むには、そのためのaccess_tokenが必要です。

graph = facebook.GraphAPI(access_token="XXXXXXXX")
print graph
#to post to your wall
graph.put_object("me", "feed", message="Posting on my wall1!")
#to get your posts/feed
feed = graph.get_connections("me", "feed")
post = feed["data"]
print post
#to put comments for particular post id
graph.put_object(post["id"], "comments", message="First!")
1
sowmya

2020年3月現在で確認済み:

!pip install facebook-sdk==2.0.0

次に:

import facebook

def main():
   # Fill in the values noted in previous steps here
   cfg = {
   "page_id"      : "1xxxxx48480xxxx",  # Step 1
   "access_token" : "xxxxxxxxxxxxxxxxxxxxxxxnp3QApxv12gjGnV99BNnhxxxxxxxxxx"   # Step 3
    }

    api = get_api(cfg)
    msg = "Hello, world!"
    status = api.put_wall_post(msg)

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()

権限の検討:manage_pages publish_pages権限が必要です。

ページIDページの概要セクションの下部にあります。

0
Sourabh Sinha