Emacs のミニバッファから(タイムラインを開かずに)Twitter に投稿する2

emacs_tweet.rb の設定

前回は、準備段階として Windows 7 (64bit) の Cygwin 上で Ruby とその Twitter パッケージを使えるようにした。今回は、Emacs の設定をする。

まず、emacs_tweet.rb というファイルを作り、以下の内容を記入した上で Path が通った場所に置く。


require 'rubygems'
require 'twitter'
require 'kconv'


USERNAME = '*****' # Twitter の自分のアカウント名
PASSWORD = '*****' # 同パスワード


client = Twitter::REST::Client.new do |config|
config.consumer_key = '******************************'
config.consumer_secret = '***************************'
config.oauth_token = '*******************************'
config.oauth_token_secret = '************************'
#config.proxy = 'http://proxy:port'
end


ARGV[0]&&(Twitter::Client.new())
client.update(Kconv.toutf8(ARGV[0])) rescue puts "error:"+$!.to_s


consumer_key, consumer_secret, oauth_token, oauth_token_secret の4つのキーは、Twitterで、emacs_tweet.rb を登録して取得したものを記す(この過程は、Ruby を使った bot 作成などでよく紹介されているので省略)。



なお、Ruby のバージョンアップに伴い、元々の emacs_tweet.rb の記述が使えなくなっているので、上記は次のような変更を行っている。


新:client = Twitter::REST::Client.new do |config|
旧:Twitter.configure do |config|


新:client.update(Kconv.toutf8(ARGV[0])) rescue puts "error:"+$!.to_s
旧:Twitter.update(Kconv.toutf8(ARGV[0])) rescue puts "error:"+$!.to_s


Emacs の設定

次に ~/.emacs(最近では ~/.emacs.d/init.el に書けと言われている)に、以下を記す。


;; ミニバッファーから Tweet する。
(defun tweet (tweet)
(let* *1
(command (concat "ruby -Ku -W0 " ruby-script " \"" (encode-coding-string tweet shell-char-code) "\""))
(result (shell-command-to-string command)))
(if (equal "" result)
(message "投稿が完了しました。")
(message result))))


(defun tweet-from-minibuffer ()
(interactive)
(let ((tweet (read-from-minibuffer "tweet: ")))
(when tweet
(message "投稿中です。")
(tweet tweet))))
;; キーバインド
(global-set-key "\C-ct" 'tweet-from-minibuffer)

これで、M-x tweet-from-minibuffer(または上記の例では C-x t)とすると、ミニバッファから Twitter に投稿できる。制限文字数のカウントといったおしゃれなものはないが、私には十分である。



なお、Cygwin のインストーラ経由 Ruby の古いバージョンが残っていると、Emacs がそちらを参照してしまいエラーが出るようである。その場合は、~/.emacs で以下にように指定すれば良い。


;; rbenv でインストールした Ruby を使うための設定
(setenv "PATH" (concat (getenv "HOME") "/.rbenv/shims:"
(getenv "HOME") "/.rbenv/bin:" (getenv "PATH")))
(setq exec-path (cons (concat (getenv "HOME") "/.rbenv/shims")
(cons (concat (getenv "HOME") "/.rbenv/bin") exec-path)))



*1:ruby-script "c:/bin/emacs_tweet.rb") ;; emacs_tweet.rb へのパス (shell-char-code 'sjis) ;; シェルの文字コード: sjis, utf-8 or euc-jp (tweet (replace-regexp-in-string "\"" "\\\\\"" tweet