# Examples of implementing notificaiton plugins

Reference

The examples of notification plugins given in this document are for informational purposes only and can be changed to fit your needs.

# Plugin "E-mail"

print("subject:" .. subject)
print("body:" .. body)
print("")
print("recipients: ")

for k,v in pairs(recipients) do
  print(v)
end

local from = { title = "<Sender Name>", address = 
 "<Sender address>"}

local result = smtp({
  host = "<Mail server>", --string
  port = <Port>, --int
  useSsl = true, --bool
  username = "<Login>", --string
  password = "<Password>", --string
  subject = subject,
  body = body,
  mailType = "plain",
  from = from,
  recipients = recipients
})

if (result.err ~= nil) then
  print(result.err)
  return -- Exit the script early if an error occurs
end
 
print("result:".. tostring(result.data))

In this example change the following parameters to your own:

  • <Mail server> - address of your SMTP server
  • <Port> - SMTP server port
  • <Login> - login to access the mailbox
  • <Password> - mailbox access password
  • <Sender name> - name of the sender
  • <Sender address> - address of the sender

# Plugin Telegram

local botId = "<BotToken>"

local function sendMessage(recipient)
  local requestBody = {
    chat_id = recipient,
    text = subject .. "\n" .. body
  }

  local args = {
    uri = "https://api.telegram.org/bot" .. botId .. "/sendMessage",
    method = "POST",
    mediaType = "application/json",
    body = json.encode(requestBody)
  }
  local response = curl(args)
  if (response.err ~= nil) then
    print(response.err)
    return -- Exit the script early if an error occurs
  end

  if (response.data.isSuccessStatusCode) == true then
    print(response.data.content)
  else
    print(":( status code " .. response.data.statusCode)
  end
end

for k, v in pairs(recipients) do
  sendMessage(v)
end

In this example, you need to change <BotToken> to a token that belongs to your Telegram bot.

# Plugin Slack

local botToken = "<SlackToken>"

local function getUserId(email)
  local args = {
    uri = "https://slack.com/api/users.lookupByEmail",
    method = "POST",
    mediaType = "application/x-www-form-urlencoded",
    headers =  { authorization = "Bearer " ..  botToken },
    body = "email=" .. email
  }

  local response = curl(args)
  if (response.err ~= nil) then
    print(response.err)
    return -- Exit the script early if an error occurs
  end

  if (response.data.isSuccessStatusCode) == true then
    local responseJsonTable =  json.decode(response.data.content)
    local userId =responseJsonTable["user"]["id"]
    print("Got user Id for " .. email .. " : " .. userId)
    return userId
  else
    print(":( status code " .. response.data.statusCode)
  end
end

local function openDirectChat(userId)
  local requestBody = {
    users = userId,
    return_im = true
  }

  local args = {
    uri = "https://slack.com/api/conversations.open",
    method = "POST",
    mediaType = "application/json",
    headers =  { authorization = "Bearer " ..  botToken },
    body = json.encode(requestBody)
  }

  local response = curl(args)
  if (response.err ~= nil) then
    print(response.err)
    return -- Exit the script early if an error occurs
  end

  if (response.data.isSuccessStatusCode) == true then
    local responseJsonTable =  json.decode(response.data.content)
    local channelId =responseJsonTable["channel"]["id"]
    print("Created direct chat with user " .. userId .. ". ChannelId: " .. channelId)
    return channelId
  else
    print(":( status code " .. response.data.statusCode)
  end
end

local function sendMessage(conversation)
  local requestBody = {
    channel = conversation,
    text= "*" .. subject .. "*" .. "\n" .. body
  }

  local args = {
    uri = "https://slack.com/api/chat.postMessage",
    method = "POST",
    mediaType = "application/json",
    headers =  { authorization = "Bearer " ..  botToken },
    body = json.encode(requestBody)
  }

  local response = curl(args)
  if (response.err ~= nil) then
    print(response.err)
    return -- Exit the script early if an error occurs
  end

  if (response.data.isSuccessStatusCode) == true then
    local responseJsonTable =  json.decode(response.data.content)
    local sentOk=responseJsonTable["ok"]
    if (sentOk == true) then
      print("Message sent successfully.")
      end
    print(response.data.content)
  else
    print(":( status code " .. response.data.statusCode)
  end
end

local function processNotify(recipient)
  if (recipient:match('[%w]*[%p]*%@+[%w]*[%.]?[%w]*')) then
    -- if the recipient is email
    local userId = getUserId(recipient)
    local chatId = openDirectChat(userId)
    sendMessage(chatId)
  else
    -- if the recipient is channel Id
    sendMessage(recipient)
  return true
  end
end

local function tablelength(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end

if (recipients == nil or recipients == "") then
  print("The recipient list is empty")
end

print("Number of recipients: " .. tablelength(recipients))

for k, v in pairs(recipients) do
  local status, retval = pcall(processNotify, v)
end

For this example, change the <SlackToken> to your own.

# Plugin Zulip

-- Variables section 
local botEmail = "someemail@mail.com" 
local botToken = "some_token"
local zulipUri = "http://some.uri" 
local defaultTopic = "someTopic" 

-- Function for sending message  
local function sendMessage(stream, topic, body)
  local args = {
    uri = zulipUri .. "/api/v1/messages",
    method = "POST",
    mediaType = "application/x-www-form-urlencoded",
    basicAuth = {
      login = botEmail,
      password = botToken
    },
    body = "type=stream&to=" .. stream .. "&topic=" .. topic .. "&content=" .. body

  }
  local response = curl(args)
  if (response.err ~= nil) then
    print(response.err)
    return -- Exit the script early if an error occurs
  end

  if (response.data.isSuccessStatusCode) == true then
    print(response.data.content)
  else
    print(":( status code " .. response.data.statusCode .. ". " .. response.data.content)
  end
end

-- Checking for a topic
if (string.len(subject) > 0) then
  topic = subject
else
  topic = defaultTopic
end

-- Cycle of sending alert to all recipients 
for k, stream in pairs(recipients) do
  sendMessage(stream, topic, body)
end

In this example, change the variables to your own:

  • botEmail - Email of the bot from which notifications will be sent.
  • botToken - Bot token from which notifications will be sent.
  • zulipUri - URI where your zulip instance is available.
  • defaultTopic - Default topic, messages without a subject will be sent with the default topic.

# Plugin msTeams

The full webhookUri is used as the recipient.

The plugin implements the functionality for selecting the format of the notification text: Plaintext or AdaptiveCard:

  • Plaintext: You don't need to do anything to send in this format, just fill in the template as you like.
  • AdaptiveCard: specify AdaptiveCard in the subject field, In the body, place the JSON describing the Adaptive Card.

Description of cards is here (opens new window).

Tip

Since the notification constructor does not allow sending json, the curly braces have been replaced: { -> ```, } -> '''

Documentation about the methods used is here (opens new window).

-- Function for sending Adaptive card 
local function sendAdaptiveCard(webhookUri)
  local requestBody = '{"type":"message","attachments":[{"contentType":"application/vnd.microsoft.card.adaptive","contentUrl":null,"content":' .. string.gsub(string.gsub(body,"```","{"),"'''","}") ..'}]}'
  local args = {
    uri = webhookUri,
    method = "POST",
    mediaType = "application/json",
    body = requestBody
  }
  local response = curl(args)
  if (response.err ~= nil) then
    print(response.err)
    return -- Exit the script early if an error occurs
  end

  if (response.data.isSuccessStatusCode) == true then
    print(response.data.content)
  else
    print(":( status code " .. response.data.statusCode)
  end
end

-- Function of sending a plaintext message 
local function sendMessage(webhookUri)
  local requestBody = {
    text = subject .. " " .. body
  }

  local args = {
    uri = webhookUri,
    method = "POST",
    mediaType = "application/json",
    body = json.encode(requestBody)
  }
  local response = curl(args)
  if (response.err ~= nil) then
    print(response.err)
    return -- Exit the script early if an error occurs
  end

  if (response.data.isSuccessStatusCode) == true then
    print(response.data.content)
  else
    print(":( status code " .. response.data.statusCode)
  end
end

-- Check for the "AdaptiveCard" flag in the message subject
-- If the flag is present, then we send as AdaptiveCard 
if (subject == "AdaptiveCard") then
  for k, v in pairs(recipients) do
    sendAdaptiveCard(v)
  end
-- Otherwise as text 
else
  for k, v in pairs(recipients) do
    sendMessage(v)
  end
end