用 Ruby 將訊息傳到 LINE 群組 (LINE Notify API)

被端走的小菜
6 min readJan 30, 2022

前言

首先你要先有 LINE,若沒有,可以左轉離開了 XD

步驟

1. 登入到 LINE Notify,並登入個人的 LINE 帳號

LINE Notify 頁面

登入自己的 LINE

2. 點自己的名字,進入「個人頁面」

3. 選「發行權杖」

4. 輸入想要加入 LINE Notify 的 LINE 群組,接著點「發行」

注意: 若離開此頁面,將不會再顯示新發行的權杖。 離開頁面前,請先複製權杖。

5. 用 curl 測試看看

記得先把 LINE Notify 官方帳號加入群組中

# 記得換成自己的 token
curl -X POST -H 'Authorization: Bearer <access_token>' -F 'message=測試發訊息' https://notify-api.line.me/api/notify
# 範例
curl -X POST -H 'Authorization: Bearer tsxxxxxxxxxIV' -F 'message=測試發訊息' https://notify-api.line.me/api/notify

官方文件 LINE Notify API Document 提供的範例

6. 用 Postman 測試看看

Postman 點 </> icon ,可以選各式程式語言的範例

7. 用 Ruby 的 irb 測試看看

require('net/http')
token = 'tsxxxxxxxxxIV' # 換成自己的 Token
url = 'https://notify-api.line.me/api/notify'
message = "測試要傳的訊息\nHello World!!"
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
http.open_timeout = 10
http.continue_timeout = 10
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{token}"
request.set_form_data(message: "\n#{message}")
response = http.request(request)
response

將 Ruby 那段寫得更嚴謹些

不能保證每次打 API 都是正常的,有可能剛好遇到 LINE 服務異常,導致 Timeout 等問題,應該要針對已知可能會發生的問題,進行預防和處理。

另外也應該針對 response 和 exception 存 logger,後續有異常要追問題時,才會有比較多線索和方向

class ChatBotNotifier
require('logger')
require('net/http')
LINE_NOTIFY_URL = 'https://notify-api.line.me/api/notify'.freeze def line_notify(token, message)
uri = URI(LINE_NOTIFY_URL)
http = init_http(uri)
call_line_api(uri, http, token, message)
end
private def logger
@logger ||= Logger.new('message.log')
end
def init_http(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
http.open_timeout = 10
http.continue_timeout = 10
http
end
def call_line_api(uri, http, token, message, error_retry = 0)
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{token}"
request.set_form_data(message: "\n#{message}")
response = http.request(request)
logger.info("#{__FILE__}##{__method__} response: #{response.body}")
rescue StandardError => e
if error_retry < 5
sleep(10)
error_retry += 1
retry
else
logger.error("#{__FILE__}##{__method__} exception: #{e.inspect}")
end
end
end
token = 'tsxxxxxxxxxIV' # 換成自己的 Token
message = "測試要傳的訊息\nHello World!!"
ChatBotNotifier.new.line_notify(token, message)

小結

若有例行要傳的訊息,可以用 Linux crontab 做排程,也可用 Sidekiq 的 scheduler 處理。

參考文件

LINE Notify API Document

medium 文章連結:https://link.medium.com/gkQQBO1Henb
本文同步發布於 小菜的 Blog https://riverye.com/

備註:之後文章修改更新,以個人部落格為主

--

--

被端走的小菜

大家好,我是被端走的小菜。以個人部落格更新為主:https://riverye.com/