0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Lua on RTX1210 (2) - Slack投稿

Posted at

検証環境

RTX1210 BootROM Ver. 1.04
RTX1210 FlashROM Table Ver. 1.00
RTX1210 Rev.14.01.38 (Fri Jul 10 09:41:02 2020)

経緯

rt.syslog() には半角で最大231文字、全角で最大115文字の制限もあるし、そもそもsyslogを読みにいくのが面倒なので、Slackに投稿できるようにする。

前提

json.lua

Special thanks, rxi!
GitHub - rxi/json からPure Luaで書かれたJSONライブラリ(MITライセンス)を使わせていただく。

slack.lua

slack.lua
--
-- slack.lua
--

require "strict"
json = require("json")

local slack = {
  -- Slack Incoming Webhook URL
  url = os.getenv("SLACK_URL"),
  -- Slack Channel Name
  channel = os.getenv("SLACK_CHANNEL"),
  -- Slack User Name
  username = os.getenv("SLACK_USERNAME")
}

local function get_log_level_color(log_level)
  if log_level == "INFO" then
    return "#14dc3c"
  elseif log_level == "ERROR" then
    return "#dc143c"
  elseif log_level == "WARN" then
    return "#dcdc14"
  elseif log_level == "DEBUG" then
    return "#148cdc"
  else
    return "#e3e3e3"
  end
end

local function post(log_level, message)
  local log_level = string.upper(log_level)
  local color_rgb = get_log_level_color(log_level)
  local payload = {
    channel = slack.channel,
    username = slack.username,
    color = color_rgb,
    icon_emoji = ":globe_with_meridians:",
    attachments = {
      {
        color = color_rgb,
        text = $[[*${log_level}* ${message}]] -- (1)
      }
    }
  }
  local request_slack = {
    url = slack.url,
    method = "POST",
    content_type = "application/json;charset=UTF-8",
    post_text = json.encode(payload)
  }
  rt.syslog("notice", "(slack.lua) DEBUG: " .. request_slack.post_text) -- for DEBUG
  local response_slack = rt.httprequest(request_slack)
  if response_slack.code == 200 then
    rt.syslog("info", "(slack.lua) Successfully posted: " .. message)
  else
    rt.syslog("info", "(slack.lua) Failed to post: " .. message)
    if response_slack.body then
      rt.syslog("info", "(slack.lua) Posting Error: " .. response_slack.body)
    end
  end
end

return { post = post }

(1): こういった式展開の書き方はRT_LUA専用らしく、それほど便利さも感じないので多用しないほうがいいかも。

Slack側でIncoming Webhookを有効化し、環境変数に設定する。

set SLACK_URL="https://hooks.slack.com/services/xxxxxxxx/xxxxxxxx"
set SLACK_CHANNEL="#yyyyyyyy"
set SLACK_USERNAME="zzzzzzzz"

次回予告

strict.luaslack.lua を使って、ログインの監視などをやっていく。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?