Facebook Publishing with python

reference to blog SSFacebook 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)



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值