Try to operate Facebook with Python

Purpose

Try to operate facebook using Python

** Demo page ** https://needtec.sakura.ne.jp/check_facebook/

Github https://github.com/mima3/check_facebook

Library used

facebook-sdk facebook-sdk is an API that operates the Facebook Graph API in Python.

https://github.com/pythonforfacebook/facebook-sdk

easy_install facebook-sdk

bottle Python web framework. Installation is easy because it consists of only one file.

http://bottlepy.org/docs/dev/index.html

beaker Library for session management in Python

https://beaker.readthedocs.org/en/latest/#

easy_install Beaker

How to operate Facebook

How to register the application

  1. Register as a developer on facebook.

** Developer registration procedure ** http://fb.dev-plus.jp/what-devplus/dev_register/

  1. Run [Apps]-> [Add a New App] on the developer page. https://developers.facebook.com/

facebook1.png

  1. Select [Website] as the application type facebook2.png

  2. Enter the application name and select Create New Facebook APP ID

facebook3.png

  1. Select a category and enter the Create APP ID. facebook4.png

  2. If you scroll down the created page, you can enter the "Site URL", so enter it and click "Next".

facebook5.png

facebook6.png

The redirect_url specified in the Facebook API must be the domain name specified in this Sai. It seems that you cannot specify the IP address, so if you want to run it locally, set it to localhost.

  1. After reloading the page, you will be able to select the created application from the menu. facebook8.png

  2. When you select an app, you can see the "App ID" and "App Secret". You can use this value to authenticate and get an access token.

facebook9.png

Get an access token

The method of obtaining an access token is shown below.

  1. Connect to oauth and get the code

end point: https://www.facebook.com/dialog/oauth

** Parameters: ** client_id: app ID of facebook app redirect_url: The redirect URL after authentication. An error will occur if the domain is not set. scope: Specify permissions separated by ",". https://developers.facebook.com/docs/facebook-login/permissions/v2.2?locale=ja_JP

** Example: ** https://www.facebook.com/dialog/oauth?client_id=XXXXX&redirect_uri=http%3A%2F%2Flocalhost%2Fcheck_facebook&scope=read_stream

Redirect URL when OK

https://localhost/check_facebook/index.cgi/?code=XXXXX#_=_

Redirect URL in case of cancellation

https://localhost/check_facebook/?error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied#_=_
  1. Connect to access_token and get access_token

end point: https://graph.facebook.com/oauth/access_token

** Parameters: ** client_id: app ID of facebook app client_secret: facebook app Secret redirect_url: The redirect URL after authentication. An error will occur if the domain is not set. code: Code obtained by oauth

** Example: ** https://graph.facebook.com/oauth/access_token?client_id=facebookアプリのAppID&client_secret=facebookアプリのSecret&redirect_uri=http%3A%2F%2Flocalhost%2Fcheck_facebook&code=oauthで取得したCode

In case of error:

{
   "error": {
      "message": "Error validating application. Invalid application ID.",
      "type": "OAuthException",
      "code": 101
   }
}

If you can get access_token:

access_token=XXX&expires=5183979

Access Graph API using access_token obtained here

How to use a session with Bottle + Beaker in Python

Below is a sample when bottle is operated with CGI.

index.cgi


from bottle import run
from application import app
from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.data_dir': './session',
    'session.cookie_expires': True,
    'session.auto': True
}
appSession = SessionMiddleware(app, session_opts)
run(appSession, server='cgi')

application.py


from bottle import get, post, template, Bottle, response, request, redirect
import os

app = Bottle()

@app.get('/')
def index():
    session = request.environ.get('beaker.session')
    session['counter'] = session.get('counter', 0) + 1
    session.save()
    return template('<b>Hello {{name}}</b>!', name=session['counter'])

The session.data_dir file is updated each time the page is accessed. Beaker does not delete the created file, so delete it regularly with cron etc.

find /hoge/session -type f -mmin +60 -exec rm {} \;

Operation example using facebook-sdk

# -*- coding: utf-8 -*-
import facebook
graph = facebook.GraphAPI('Obtained API')
profile = graph.get_object('facebook page ID or name')
print profile
posts = graph.get_connections(profile['id'], 'posts')
print posts

Summary

By using facebook-sdk, bottle, and Beaker, you can create applications using facebook API even in Python.

Recommended Posts

Try to operate Facebook with Python
Try to operate DB with Python and visualize with d3
Try to reproduce color film with Python
Try logging in to qiita with Python
Try to operate Excel using Python (Xlwings)
Try scraping with Python.
Operate Kinesis with Python
Operate Blender with Python
Operate Excel with Python (1)
Operate Excel with Python (2)
Try to solve the man-machine chart with Python
Try to draw a life curve with python
Try to make a "cryptanalysis" cipher with Python
Try to automatically generate Python documents with Sphinx
Try to make a dihedral group with Python
Try to detect fish with python + OpenCV2.4 (unfinished)
Try to factorial with recursion
Connect to BigQuery with Python
Operate TwitterBot with Lambda, Python
Try to understand Python self
Try Python output with Haxe 3.2
Connect to Wikipedia with Python
Post to slack with Python 3
[Note] Operate MongoDB with Python
Try running Python with Try Jupyter
Switch python to 2.7 with alternatives
Write to csv with Python
[Python] [SQLite3] Operate SQLite with Python (Basic)
Try face recognition with Python
Try to solve the programming challenge book with python3
[First API] Try to get Qiita articles with Python
Try to make a command standby tool with python
Try to solve the internship assignment problem with Python
Try to automate pdf format report creation with Python
How to operate Discord API with Python (bot registration)
[Automation] Operate GitLab with Python to facilitate inquiry management
Try scraping with Python + Beautiful Soup
Python: How to use async with
Operate a receipt printer with python
Link to get started with python
Try to display various information useful for debugging with python
[Python] Write to csv file with Python
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate an Excel file using Python (Pandas / XlsxWriter) ①
Post from python to facebook timeline
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
Try singular value decomposition with Python
Output to csv file with Python
Try to operate an Excel file using Python (Pandas / XlsxWriter) ②
Try python
Try to profile with ONNX Runtime
Convert list to DataFrame with python
MP3 to WAV conversion with Python
To do tail recursion with Python2
Try to calculate Trace in Python
How to get started with Python
Try to bring up a subwindow with PyQt5 and Python
Try converting cloudmonkey CLI to python3 -1
What to do with PYTHON release?
Operate ECHONET Lite appliances with Python