motionの結果をWordPressに投稿

もるこむ日記の拡張

別途作っている我が家のコーギーのブログ「もるこむ日記」は、現状ほぼ100%がinstagram連携。
motion結果の犬認識もできたことだし、もるこむが水を飲んだ場合はWordPressに投稿させる。

WordPress連携

pythonの準備

sudo pip install python-wordpress-xmlrpc

スクリプト

WordPressへの投稿本体

#coding: utf-8

import mimetypes
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media, posts

def WPpost(argtitle, argcategory, argmessage,argfilepath, argfilename,
           argxrurl, arguname, argpword):

  wp_xrurl = argxrurl
  wp_uname = arguname
  wp_pword = argpword

  wp = Client(wp_xrurl, wp_uname, wp_pword)

  fname = '{path}/{name}'.format(
          path=argfilepath,
          name=argfilename)

  data = {
          'name': argfilename,
          'type': 'image/jpeg',
          'overwrite': True
  }

  data['type'] = mimetypes.guess_type(fname)[0]

  with open(fname, 'rb') as img:
    data['bits'] = xmlrpc_client.Binary(img.read())
  response = wp.call(media.UploadFile(data))
  attach_img = response['url']

  post = WordPressPost()
  post.title = argtitle
  post.content = \
      '<p>'+argmessage+ \
      '</p><br><img src="'+attach_img+ \
      '" />'
  post.terms_names = {
      'category': [argcategory]
  }

#  post.post_status = 'publish'
  post.post_status = 'draft'

  post_id = wp.call(posts.NewPost(post))

  return post_id

前回の画像認識と組み合わせて、犬か判断and投稿のスクリプトを作成

#coding: utf-8
import watson_recognition
import post_wordpress
import sys
import os

args = sys.argv

title    = 'ごくごく'
category = 'drinking'
message  = 'もるつかこむぎがお水をのんでます by 監視bot'
filepath = os.path.dirname(args[1])
filename = os.path.basename(args[1])
xrurl    = 'https://morukomu.tim6300243.0t0.jp/xmlrpc.php'
uname    = 'hogehoge'
pword    = 'hogehogehogehoge'

result = watson_recognition.recognition_image(filepath,filename,'dog',0.75)

if result == 1:
  post_wordpress.WPpost(title,category,message,filepath,filename,xrurl,uname,pword)

参考にさせていただいたサイト
python-wordpress-xmlrpc ライブラリで投稿

motion.confの修正

on_picture_save python /var/motion/script/hogehoge.py %f

動作結果

うまくいった