reference to blog SS, Facebook Publishing with python
There are many methods to publish posts on facebook such as http request and the SDK others offer. Briefly, the principle is to get oauth2 authentication first then post commands to facebook server with the access token returned. In this article, the code still needs to be optimized for automatically running. For example, use library re to extract the access token from web browser url so the user need not to copy or paste.
Below is the code:
#!/usr/bin/python
# coding: utf-8
import urllib2
import webbrowser
import os
from facepy import GraphAPI
def initial():
#Application Information
FACEBOOK_APP_ID = 'Will I tell you?'
FACEBOOK_APP_SECRET = 'I will not tell you...'
FACEBOOK_PROFILE_ID = '466578516807107'
#Facebook Oauth2 Information
FACEBOOK_URI = 'http://autoidlab.cs.adelaide.edu.au/'
FACEBOOK_CODE = 'token'
FACEBOOK_SCOPE = 'user_about_me,publish_actions,manage_pages'
#Dictionary of Oauth2 Information
oauth2=dict(
client_id = FACEBOOK_APP_ID,
client_secret = FACEBOOK_APP_SECRET,
grant_type = 'client_credentials',
redirect_uri=FACEBOOK_URI,
response_type=FACEBOOK_CODE ,
scope=FACEBOOK_SCOPE
)
#Request For Permissions
userMainUrl = 'https://www.facebook.com/dialog/oauth?client_id='+oauth2['client_id']+'&redirect_uri='+oauth2['redirect_uri']+'&response_type='+oauth2['response_type']+'&scope='+oauth2['scope']
webbrowser.open(userMainUrl)
#Get User AccessToken
UserAccessToken = raw_input("input the user code : ")
graphaa = GraphAPI(UserAccessToken)
#Request For Page AccessToken
print graphaa.get('466578516807107/accounts?fields=access_token')
PageAccessToken = raw_input("input the page code : ")
return PageAccessToken
#save log in current folder
def log(code):
path = os.path.join(os.getcwd(), 'log.txt')
f = open(path, 'a')
f.write('\nlast access token is:\n'+code+'\n')
f.close()
#Publish Posts In My Timeline
def txt(code):
graph = facebook.GraphAPI(code)
graph.put_object("me", "feed", message='Welcome to the Auto-ID Lab')
#Publish Photos In Certain Albulm
def pic(code):
graph = facebook.GraphAPI(code)
photo = open('E:\\Dropbox\\SpecialtyFiles\\Rasppi\\Facebook\\1.jpg')
graph.put_object('274289659369328', photo.read())
#Publish Posts In Certain Page
def mypage(code):
grapha = GraphAPI(code)
grapha.post('386278881514022/feed?message=Have a nice week!')
if __name__ == "__main__":
AccessToken = initial()
#Choose where to publish
mypage(AccessToken)
#txt(AccessToken)
#pic(AccessToken)
log(AccessToken)