Python Twitter
since 2013-06-12
http://d.hatena.ne.jp/Wacky/20120527/1338118005
https://github.com/bear/python-twitter
Windows 8 + Python 2.7 で頑張ってみる:
> easy_install pip > git clone git@github.com:bear/python-twitter.git > cd python-twitter > pip install -r requirements.txt > python setup.py build > python setup.py install > python setup.py test ... ... ... Ran 37 tests in 0.188s OK
さっそく import して何が出てくるか見てみる:
from __future__ import unicode_literals, print_function import twitter print(dir(twitter))
> python hello_twitter.py ['ACCESS_TOKEN_URL', 'AUTHORIZATION_URL', 'Api', 'CHARACTER_LIMIT', 'DEFAULT_CACHE', 'DirectMessage', 'Hashtag', 'List', 'REQUEST_TOKEN_URL', 'SIGNIN_URL', 'Status', 'StringIO', 'Trend', 'TwitterError', 'Url', 'User', '_FileCache', '_FileCacheError', '__author__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__version__', 'calendar', 'datetime', 'gzip', 'httplib', 'md5', 'oauth', 'os', 'parse_qs', 'parse_qsl', 'rfc822', 'simplejson', 'sys', 'tempfile', 'textwrap', 'time', 'urllib', 'urllib2', 'urlparse']
https://dev.twitter.com/ でアプリケーションを新規作成して CONSUMER_KEY などを取得しておく。
python を実行して import twitter すれば help(twitter.Api) などができる。
音声エンジンとくっつける
くっつけてみた。
SAPI の処理は python_windows 参照。
事前に COM のライブラリを作っておく必要がある。
- スタートメニュー - すべてのプログラム - Python 2.7 - PythonWin
- Tools - Com Makepy Utility
- Select Library で Microsoft Speech Object Library 5.4 を選択。
Windows 8 で動作確認。
<html>
<blockquote class="twitter-tweet" lang="ja"><p>今日はWindowsで音声認識を使うプログラムを作りました</p>— 24motz 西本卓也さん (@24motz) <a href="https://twitter.com/24motz/status/344821605853167617">2013年6月12日</a></blockquote>
<script async src="platform.twitter.com/widgets.js" charset="utf-8"></script>
</html>
<code python>
# coding: UTF-8
from future import unicode_literals, print_function
CONSUMER_KEY = 
CONSUMER_SECRET = 
ACCESS_KEY = 
ACCESS_SECRET = 
from win32com.client import constants
import win32com.client
import pythoncom
# https://github.com/bear/python-twitter
import twitter
twitter_api = twitter.Api(
	consumer_key = CONSUMER_KEY,
	consumer_secret = CONSUMER_SECRET,
	access_token_key = ACCESS_KEY,
	access_token_secret = ACCESS_SECRET)
speaker = win32com.client.Dispatch("SAPI.SpVoice")
message = 
def say(phrase):
	print(phrase.encode('mbcs', 'ignore'))
	speaker.Speak(phrase)
class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")):
	def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result):
		global message
		newResult = win32com.client.Dispatch(Result)
		cmd = newResult.PhraseInfo.GetText()
		print(cmd)
		if "ついったーをよんで" in cmd:
			for s in twitter_api.GetHomeTimeline()[:3]:
				say(s.text)
				pythoncom.PumpWaitingMessages()
		elif message and ("いまのをついーとして" in cmd):
			status = twitter_api.PostUpdate(message)
			say(message+ ' とツイートしました')
			message = 
		else:
			say('あなたは ' + cmd + ' と言いました')
			message = cmd
class SpeechRecognition:
	def init(self, wordsToAdd):
		self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer")
		self.context = self.listener.CreateRecoContext()
		self.grammar = self.context.CreateGrammar()
		self.grammar.DictationSetState(1)
		self.wordsRule = self.grammar.Rules.Add("wordsRule",
						constants.SRATopLevel + constants.SRADynamic, 0)
		self.wordsRule.Clear()
		[ self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd ]
		self.grammar.Rules.Commit()
		self.grammar.CmdSetRuleState("wordsRule", 1)
		self.grammar.Rules.Commit()
		self.eventHandler = ContextEvents(self.context)
if name=='main':
	wordsToAdd = [ "こんぴゅーたーついったーをよんで",  "こんぴゅーたーいまのをついーとして" ]
	speechReco = SpeechRecognition(wordsToAdd)
	say("こんばんは")
	while 1:
		pythoncom.PumpWaitingMessages()
</code>
  * DictationSetState(1) で、ディクテーション(大語彙音声認識)を有効にする。wordsToAdd のコマンド認識も同時に実行されている。
