LoginSignup
16
16

More than 5 years have passed since last update.

[Ruby] Line NotifyでLineにメッセージ送信する手順メモ

Last updated at Posted at 2016-10-10

※こちらがLineのWeb管理画面からトークン取得までのキャプチャ画像有りの詳細手順です。
文章では分かりづらい場合はこちらも合わせてご参照ください。
RubyからLine NotifyでLineにメッセージを送るかんたん手順

アクセストークンの取得

  • Line Web管理画面にログイン

こちらから、LineのWeb管理画面にいきます。

  • トークン名、トークルームを選択

続いて、Lineへのメッセージ送信の際の通知名や、送信先チャットルーム(トークルーム)を選択します。

curlで送信テスト

curlでAPIの動作確認します。詳細はAPIドキュメント参照

$ curl -X POST -H 'Authorization: Bearer KorehaDummyNoTokenIdDayo3kmr5aQjM7kZ4swehzPBY' -F "message=ビルの窓ガラスによく張ってある、「▼」のマークってなんなの?" 'https://notify-api.line.me/api/notify'
{"status":200,"message":"ok"}

こんな感じで届きます → スマホに届くメッセージ画面キャプチャ

先程のトークン作成時のトークン名などが結構関わってくるので受信画面のイメージを頭に持っておくのが大事です。

Rubyで送信スクリプトを作成する

curlをRubyで再現しただけのかんたんスクリプト。トークン文字列だけ入れ替えればどの環境でも動くと思います。

send_msg_with_line_Notify.rb
require 'net/http'
require 'uri'

class Line
  TOKEN = "KorehaDummyNoTokenIdDayo3kmr5aQjM7kZ4swehzPBY"
  URI = URI.parse("https://notify-api.line.me/api/notify")

  def make_request(msg)
    request = Net::HTTP::Post.new(URI)
    request["Authorization"] = "Bearer #{TOKEN}"
    request.set_form_data(message: msg)
    request
  end

  def send(msg)
    request = make_request(msg)
    response = Net::HTTP.start(URI.hostname, URI.port, use_ssl: URI.scheme == "https") do |https|
      https.request(request)
    end
  end
end

line = Line.new
msg = ARGV[0]

res = line.send(msg)
puts res.code
puts res.body
実行方法
$ ruby send_msg_with_line_notify.rb 'ビルの窓ガラスによく張ってある、「▼」のマークってなんなの?'
200
{"status":200,"message":"ok"}
16
16
1

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
16
16