Need help to get DZVents posting to Slack working.  [Solved]

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Post Reply
Bikey
Posts: 331
Joined: Sunday 22 February 2015 12:19
Target OS: Linux
Domoticz version: 2020.x
Location: Netherlands
Contact:

Need help to get DZVents posting to Slack working.

Post by Bikey »

Hi guys,

I'm really breaking my head why the following script does not work. This is to post a message to Slack using the Bot-API.

I have a similar script working with the webhook API, but that only works on a single channel, whereas I would like to post to different channels. Therefore I would like to get this working.

The problem is also that I do not get proper error logging as well (even with the level set to Debug in settings), the log-line after the "if (item.isHTTPResponse) then" does not seem to get hit?

However If I move that part to separate script, I can catch the HTTPResponse, which shows that Slack says ""invalid_form_data".
If I change the header info to say that the content-type is "application/x-www-form-urlencoded" I get an error "not_authed"

Can anybody see what is wrong in this script?

Code: Select all

return {
    on = {
        devices = {'TestContact' }
        },
	    httpResponses = {
			'slackrequest'
	},
	logging = {
        level = domoticz.LOG_DEBUG,
        marker = "Slack-script"
    },
	execute = function(domoticz, item)
	    
	    local function SendSlackMessage (message)
            local token = 'xoxb-my-bot-token'
            local channel = 'sensors'
			domoticz.openURL({
				url = 'https://slack.com/api/chat.postMessage',
				method = 'POST',
				headers = { ['content-Type'] = 'application/json' },				
				postData = { ['text'] = message , ['token'] = token, ['channel'] = channel },
				callback = 'slackrequest',
			})
        end
    
	if (item.isDevice) then
           local results = SendSlackMessage ('This is a test message')
	end
	if (item.isHTTPResponse) then
            domoticz.log('OK we got a response',domoticz.LOG_DEBUG)		    
	      if (item.ok) then
                  domoticz.log('Ok result. Slack response is: Ok',domoticz.LOG_DEBUG)
	      else
		domoticz.log('Slack response is: Not OK', domoticz.LOG_DEBUG)
	     end
	end

end
}

User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Need help to get DZVents posting to Slack working.  [Solved]

Post by waaren »

Bikey wrote: Thursday 04 June 2020 0:21 Can anybody see what is wrong in this script?
You have some misplaced brackets in your script, causing httpResponses not being evaluated in the on is section.
Corrected script:

Code: Select all

return
{
    on =
    {
        devices =
        {
            'TestContact'
        },

        httpResponses =
        {
            'slackrequest',
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG,
        marker = "Slack-script"
    },

    execute = function(domoticz, item)

        local function SendSlackMessage (message)
            local token = 'xoxb-my-bot-token'
            local channel = 'sensors'
            domoticz.openURL({
                url = 'https://slack.com/api/chat.postMessage',
                method = 'POST',
                headers = { ['content-Type'] = 'application/json' },
                postData = { ['text'] = message , ['token'] = token, ['channel'] = channel },
                callback = 'slackrequest',
            })
        end

    if (item.isDevice) then
           local results = SendSlackMessage ('This is a test message')
    end
    if (item.isHTTPResponse) then
         domoticz.log('OK we got a response',domoticz.LOG_DEBUG)
         domoticz.log(item,domoticz.LOG_DEBUG)
          if (item.ok) then
                  domoticz.log('Ok result. Slack response is: Ok',domoticz.LOG_DEBUG)
          else
        domoticz.log('Slack response is: Not OK', domoticz.LOG_DEBUG)
         end
    end

end
}
Spoiler: show

Code: Select all


2020-06-04 07:46:07.843  Status: dzVents: Info: Handling events for: "TestContact", value: "On"
2020-06-04 07:46:07.843  Status: dzVents: Info: Slack-script: ------ Start internal script: 20200604 dz slackMessage: Device: "TestContact (Virtual)", Index: 312
2020-06-04 07:46:07.844  Status: dzVents: Debug: Slack-script: OpenURL: url = https://slack.com/api/chat.postMessage
2020-06-04 07:46:07.844  Status: dzVents: Debug: Slack-script: OpenURL: method = POST
2020-06-04 07:46:07.844  Status: dzVents: Debug: Slack-script: OpenURL: post data = {"channel":"sensors","text":"This is a test message","token":"xoxb-my-bot-token"}
2020-06-04 07:46:07.844  Status: dzVents: Debug: Slack-script: OpenURL: headers = {["content-Type"]="application/json"}
2020-06-04 07:46:07.844  Status: dzVents: Debug: Slack-script: OpenURL: callback = slackrequest
2020-06-04 07:46:07.844  Status: dzVents: Info: Slack-script: ------ Finished 20200604 dz slackMessage


2020-06-04 07:46:08.189  Status: dzVents: Info: Handling httpResponse-events for: "slackrequest"
2020-06-04 07:46:08.189  Status: dzVents: Info: Slack-script: ------ Start internal script: 20200604 dz slackMessage: HTTPResponse: "slackrequest"
2020-06-04 07:46:08.189  Status: dzVents: Debug: Slack-script: OK we got a response
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse> _contentType: application/json; charset=utf-8
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse> isHardware: false
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse> isCustomEvent: false
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse> protocol: HTTP/2
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse> trigger: slackrequest
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse> data: {"ok":false,"error":"not_authed","warning":"missing_charset","response_metadata":{"warnings":["missing_charset"]}}
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse> json:
2020-06-04 07:46:08.189  Status: dzVents: HTTPResponse>         response_metadata:
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>                 warnings:
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>                         1: missing_charset
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         error: not_authed
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         warning: missing_charset
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         ok: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> baseType: httpResponse
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isXML: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> headers:
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         server: Apache
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         content-length: 104
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         access-control-allow-origin: *
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         x-xss-protection: 0
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         x-content-type-options: nosniff
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         x-via: haproxy-www-tbq6
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         content-type: application/json; charset=utf-8
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         content-encoding: gzip
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         strict-transport-security: max-age=31536000; includeSubDomains; preload
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         x-accepted-oauth-scopes: chat:write:bot
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         x-slack-backend: h
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         access-control-expose-headers: x-slack-req-id, retry-after
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         access-control-allow-headers: slack-route, x-slack-version-ts, x-b3-traceid, x-b3-spanid, x-b3-parentspanid, x-b3-sampled, x-b3-flags
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         referrer-policy: no-referrer
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         vary: Accept-Encoding
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         date: Thu, 04 Jun 2020 05:46:08 GMT
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse>         x-slack-req-id: 5ec6cde4386738058bfcc2ca270cf6a8
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> callback: slackrequest
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isVariable: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isSystem: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isGroup: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isHTTPResponse: true
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isSecurity: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isDevice: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isTimer: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> statusCode: 200
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> statusText: OK
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isScene: false
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> dump()
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> isJSON: true
2020-06-04 07:46:08.190  Status: dzVents: HTTPResponse> ok: true
2020-06-04 07:46:08.190  Status: dzVents: Debug: Slack-script: {["_contentType"]="application/json; charset=utf-8", ["isHardware"]=false, ["isCustomEvent"]=false, ["protocol"]="HTTP/2", ["trigger"]="slackrequest", ["data"]="{"ok":false,"error":"not_authed","warning":"missing_charset","response_metadata":{"warnings":["missing_charset"]}}", ["json"]={["response_metadata"]={["warnings"]={"missing_charset"}}, ["error"]="not_authed", ["warning"]="missing_charset", ["ok"]=false}, ["baseType"]="httpResponse", ["isXML"]=false, ["headers"]={["server"]="Apache", ["content-length"]="104", ["access-control-allow-origin"]="*", ["x-xss-protection"]="0", ["x-content-type-options"]="nosniff", ["x-via"]="haproxy-www-tbq6", ["content-type"]="application/json; charset=utf-8", ["content-encoding"]="gzip", ["strict-transport-security"]="max-age=31536000; includeSubDomains; preload", ["x-accepted-oauth-scopes"]="chat:write:bot", ["x-slack-backend"]="h", ["access-control-expose-headers"]="x-slack-req-id, retry-after", ["access-control-allow-headers"]="slack-route, x-slack-version-ts, x-b3-traceid, x-b3-spanid, x-b3-parentspanid, x-b3-sampled, x-b3-flags", ["referrer-policy"]="no-referrer", ["vary"]="Accept-Encoding", ["date"]="Thu, 04 Jun 2020 05:46:08 GMT", ["x-slack-req-id"]="5ec6cde4386738058bfcc2ca270cf6a8"}, ["callback"]="slackrequest", ["isVariable"]=false, ["isSystem"]=false, ["isGroup"]=false, ["isHTTPResponse"]=true, ["isSecurity"]=false, ["isDevice"]=false, ["isTimer"]=false, ["statusCode"]=200, ["statusText"]="OK", ["isScene"]=false, ["dump"]=nil, ["isJSON"]=true, ["ok"]=true}
2020-06-04 07:46:08.190  Status: dzVents: Debug: Slack-script: Ok result. Slack response is: Ok
2020-06-04 07:46:08.191  Status: dzVents: Info: Slack-script: ------ Finished 20200604 dz slackMessage
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Bikey
Posts: 331
Joined: Sunday 22 February 2015 12:19
Target OS: Linux
Domoticz version: 2020.x
Location: Netherlands
Contact:

Re: Need help to get DZVents posting to Slack working.

Post by Bikey »

Thank you!
This helped my to do the debugging. I kept getting the "not_authed" reply, and finally found out in the documentation that you should put the token in the header when using a JSON body.

So for others who want to use this, this is a working script.

Code: Select all

return
{
    on =
    {
        devices =
        {
            'TestContact'
        },

        httpResponses =
        {
            'slackrequest',
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG,
        marker = "Slack-script"
    },

    execute = function(domoticz, item)

        local function SendSlackMessage (message)
            local token = 'xoxb-put_your_token_here'
            local channel = 'sensors'
            domoticz.openURL({
                url = 'https://slack.com/api/chat.postMessage',
                method = 'POST',
                headers = { ['content-Type'] = 'application/json', ['Authorization'] = 'Bearer '..token  },
                postData = { ['text'] = message , ['channel'] = channel, ['as_user'] = 'false' , ['username'] = 'DzVents' },
                callback = 'slackrequest',
            })
        end

    if (item.isDevice) then
           local results = SendSlackMessage ('This is a test message: long live DzVents!')
    end
    if (item.isHTTPResponse) then
         domoticz.log('OK we got a response',domoticz.LOG_DEBUG)
         domoticz.log(item,domoticz.LOG_DEBUG)
          if (item.ok) then
            domoticz.log('Ok result. Slack response is: Ok',domoticz.LOG_DEBUG)
          else
            domoticz.log('Slack response is: Not OK', domoticz.LOG_DEBUG)
         end
    end

end
}
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest