LoginSignup
84
77

More than 5 years have passed since last update.

RubyからMacの通知センターで通知する簡単な方法 (AppleScript)

Last updated at Posted at 2014-04-17

(追記: 2015/2/25 今見ると変なコード書いてるので書き直したいけど書き直さないでしょうね)

Rubyで通知させたかったので簡単な方法を調べました。
Rubyっていうか、ただのAppleScriptです。

AppleScript

Marvericksから、AppleScriptで通知センターに通知できるようになりました。

notification.scpt
display notification "めっせーじ"

スクリーンショット 2014-04-17 18.19.27.png

オプションとしてタイトル、サブタイトル、音を指定できます。
それ以外は変更できません。アイコンとかも。

notification_with_options.scpt
display notification "めっせーじ" with title "たいとる" subtitle "さぶたいとる" sound name "Purr"

スクリーンショット 2014-04-17 18.19.37.png

通知センターではこんな感じ。消去は×ボタン。
クリックするとAppleScriptエディタが立ち上がります。(変更不可)
スクリーンショット 2014-04-17 18.20.47.png

使い方は「AppleScriptエディタ」の以下を参照。

[ ファイル > 用語説明を開く > StandardAdditions.osax > User Interaction > display notification]

display notification v : Display a notification. At least one of the body text and the title must be specified.
display notification [text] : the body text of the notification
[with title text] : the title of the notification (default is the name of the calling application).
[subtitle text] : the subtitle of the notification
[sound name text] : the name of the sound to play

Ruby

で、Rubyから利用する簡単な方法はシェルからosascriptコマンドを実行する方法と思います。
Rubyみたいに-eオプションをつければ、文字列をAppleScriptとして実行できます。

Terminal
osascript -e 'display notification "hello"'

「``」を使えば、そのままの形でRubyで実行可能。

notification_test.rb
`osascript -e 'display notification "hello"'`

メソッドにしてみます。
こっちはコマンドの実行を「``」でなくsystemメソッドにしました。

notification
def notification(message, title:"Ruby", subtitle:"", sound:"")
  [message, title, subtitle, sound].each{|arg| arg.gsub!(/"/, '\\\\\"')}

  scpt = 'display notification "%s"' % message
  scpt << ' with title "%s"' % title
  scpt << ' subtitle "%s"' % subtitle unless subtitle.empty?
  scpt << ' sound name "%s"' % sound unless sound.empty?

  system %|osascript -e "#{scpt.gsub(/"/, '\"')}"|
end

# ダブルクォーテーション、シングルクォーテーションが問題なく使えること確認
notification %q|"I thought what I'd do was, I'd pretend I was one of those deaf-mutes."|, sound:'Glass'

AppleScriptの文字列にはダブルクォーテーションしか使えません。
だからosascriptに渡す文字列はシングルで囲おうと思ったんですが、シェルでシングルをエスケープするのがやたらめんどくさかったのでいっそぜんぶダブルにしました。
(参考: bashなどのshellでシングルクオートをエスケープする方法 - 中野智文)

動かなかった場合はコメントいただけると助かります。

sound nameについて

sound nameは省略した場合、音がなりません。
存在しない音を指定するとデフォルトの音(トライトーン)が鳴ります。

音には[システム環境設定 > サウンド > サウンドエフェクト]にある名前を指定します。
ただ、トライトーンはそこにないので、他にも指定できる音があるのかもしれません。(情報求ム)

代わりにsay "hello"とかやって喋らせるのもいいかもです。

参考

Mavericksでは通知センターをスクリプトから使えるようになった | Blog by msyk
Mavericksでrequire 'osx/cocoa'が出来ない - rcmdnk's blog

84
77
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
84
77