Dreamstime

Thursday 5 May 2016

Python Script For Posting To Blogger (Via OAuth2)

I hope somebody will find this Python script useful. I actually used this Python script to test things out first (and make sure that everything works) before I started work on fixing RavenPlus last year. I can't remember now, but I think the gist of this script came off from b.py - a Python script for posting blog posts to Blogger and Wordpress.

To post to your blog from this script, remember to replace the blogID "1087XXX5764091XXX95" in the line

post = service.posts().insert(blogId="1087XXX5764091XXX95", body=body, isDraft=False).execute(credentials.authorize(Http()))

with your blog's blogID.

To update an existing blog post, just replace the line above with the following (NOTE: you will need to find out what your blog post postID is, otherwise the statement will fail):

post = service.posts().update(blogId="1087XXX5764091XXX95", postId="4781959859649019078", body=body, publish=True).execute(credentials.authorize(Http()))


The OAuth2 login credentials is named 'plus.dat' and it must be located in the same directory as this Python script file.

I ran this script file under Python 2.4 with some customisation made to the Google API Python Client Library Version 1.2.



The Source Code

==== BEGIN ====

import sys

from oauth2client import client # , file, tools  # file and tools added by Chuah TC
from apiclient import sample_tools
# Chuah TC:  6-6-2015
from apiclient.discovery import build
from httplib2 import Http

# Chuah TC:  7-6-2015 - To fix [No handlers could be found for logger "oauth2client.util"] error message.
import logging
# 


def main(argv):
  # Chuah TC:  7-6-2015 - To fix [No handlers could be found for logger "oauth2client.util"] error message.
  logging.basicConfig(filename='debug.log',level=logging.WARNING)


  # Authenticate and construct service.
  print "--- 111 ---"
  credentials, service, flags = sample_tools.init(
      argv, 'plus', 'v1', __doc__, __file__,
      # CTC: OAuth 2.0 scope information for the Blogger API
      scope='https://www.googleapis.com/auth/blogger')

  print "--- 222 ---"
  
  
  service = build('blogger', 'v3', http=credentials.authorize(Http()))
  
  print "--- 333 ---"

  try:


      # "labels" : ["test", "test - don't read"],
      body = {
        "kind": "blogger#post",
        "published": u'2015-06-18T02:30:00-07:00',
        "title": "Date:19-7-2015 - Can we back date? - Posted Via PostNew.py",
        "content": "<p>Can we back date a new post?</p><p>Another Paragraph</p><p>Don't Read</p><p>Test posted via PostNew.py</p><p>Another Paragraph</p><p>Don't Read</p>"
        }

      post = service.posts().insert(blogId="1087XXX5764091XXX95", body=body, isDraft=False).execute(credentials.authorize(Http()))
      print post
      print "====="
      print "post url = ", post["url"]
      print "====="
      
      

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run'
      'the application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)


==== END ====




2 comments:

  1. Hi, very interesting your project, I used your example I want to create post from python and run me generates the following error because the application is authorized and created the plus.dat and change the blogid:

    ---- 111 ----
    Traceback (most recent call last):
    File "blog1.py", line 57, in
    main(sys.argv)
    File "blog1.py", line 24, in main
    scope='https://www.googleapis.com/auth/blogger')
    ValueError: need more than 2 values to unpack


    line # 57 if __name__ == '__main__':
    Line # 24 scope = 'https: //www.googleapis.com/auth/blogger')

    another question ... could attach images to blogger with this api?
    Thanks for your attention..

    ReplyDelete
    Replies
    1. First a confession: Although I have many years of programming experience, I am just a novice in Python.

      I have only tested my Python script above using Python version 2.4 with Google API Python Client Library Version 1.2. It may not work with any other versions. In fact, I did some customization of the Google API to get it working with Python version 2.4 (see here: http://chuahtc.blogspot.com/2015/09/customizing-google-api-python-client.html).

      I have had many challenges while learning OAuth2 and Python, and I find the site stackoverflow.com to be of immense help during this time.

      For image and picture uploads to Google Picasa, I use a difference API called 'gdata'. That was the only way to do it 6 months ago; not sure about now.

      Delete