Skip to content

Commit a876246

Browse files
lrochettekl4w
andauthored
Slack post channel (#477)
* new step to send to slack using token and channel names instead of webhook * Fix docker to reflect python3 usage * Update version to 0.0.2 to solve discrepancy * Fixing CVEs * Version 0.0.4: adding log info and env var checks * Missing default value * Improve argument descriptions * option to send messages to a user via ID or email (#476) * prep work for official release Signed-off-by: Laurent <laurent.rochette@codefresh.io> Co-authored-by: Kash Law <ka.shing.law@gmail.com>
1 parent cde73ef commit a876246

File tree

5 files changed

+170
-0
lines changed

5 files changed

+170
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FROM python:3.11.0a7-alpine3.15
2+
RUN pip3 install slack_sdk
3+
4+
COPY lib/slack.py /slack/slack.py
5+
ENTRYPOINT [ "python3", "/slack/slack.py" ]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Slack message sender
2+
3+
A plugin for easy sending messages to Slack from a Codefresh pipeline using channel name
4+
5+
## Usage
6+
```
7+
sendSlack:
8+
title: notifySlack
9+
type: 'slack-post-channel'
10+
arguments:
11+
SLACK_CHANNEL: "mychannel" # or xxx@mycompany.com
12+
SLACK_TOKEN: "xxxx-xxxxx-xxxxx-xxxx"
13+
SLACK_MESSAGE: "this is my awesome message. Please <@U02M8S1BW7W> have a look
14+
```
Lines changed: 1 addition & 0 deletions
Loading
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/env python3
2+
'''
3+
Script to send a message to a named Slack channel
4+
'''
5+
6+
import os
7+
import sys
8+
import logging
9+
from slack_sdk import WebClient
10+
from slack_sdk.errors import SlackApiError
11+
12+
def main():
13+
log_format = "%(asctime)s:%(levelname)s:%(name)s.%(funcName)s: %(message)s"
14+
logging.basicConfig(format = log_format, level = os.environ['LOG_LEVEL'].upper())
15+
16+
channel=os.getenv('SLACK_CHANNEL')
17+
message=os.getenv('SLACK_MESSAGE', "")
18+
token =os.getenv('SLACK_TOKEN')
19+
20+
if ( channel == None ):
21+
logging.error("SLACK_CHANNEL is not defined")
22+
sys.exit(1)
23+
24+
if ( token == None ):
25+
logging.error("SLACK_TOKEN is not defined")
26+
sys.exit(1)
27+
28+
logging.info("Connecting to Slack")
29+
client = WebClient(token=token)
30+
31+
if ( not channel.startswith('@') and '@' in channel ):
32+
try:
33+
response = client.users_lookupByEmail(email=channel)
34+
assert response["user"]["profile"]["email"] == channel
35+
channel = response["user"]["id"]
36+
except SlackApiError as e:
37+
# You will get a SlackApiError if "ok" is False
38+
assert e.response["ok"] is False
39+
assert e.response["error"] # str like 'users_not_found'
40+
logging.error("Lookup error: %s",e.response['error'])
41+
sys.exit(3)
42+
43+
try:
44+
response = client.chat_postMessage(channel=channel, text=message)
45+
assert response["message"]["text"] == message
46+
except SlackApiError as e:
47+
# You will get a SlackApiError if "ok" is False
48+
assert e.response["ok"] is False
49+
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
50+
logging.error("Post error: %s",e.response['error'])
51+
sys.exit(2)
52+
logging.info("Message posted to Slack")
53+
54+
if __name__ == "__main__":
55+
main()
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
kind: step-type
2+
version: '1.0'
3+
metadata:
4+
name: slack-post-channel
5+
version: 0.0.6
6+
title: Send a Slack message to a channel
7+
isPublic: true
8+
description: Send a message to a named Slack channel (instead of using a webhook URL)
9+
sources:
10+
- >-
11+
https://github.com/codefresh-io/steps/tree/master/incubating/slack-post-channel
12+
stage: incubating
13+
maintainers:
14+
- name: Laurent Rochette
15+
email: laurent.rochette@codefresh.io
16+
categories:
17+
- notifications
18+
official: true
19+
tags: []
20+
icon:
21+
type: svg
22+
url: https://cdn.jsdelivr.net/gh/codefresh-io/steps/incubating/slack-post-channel/icon.svg
23+
background: "#49154B"
24+
examples:
25+
- description: example-1
26+
workflow:
27+
sendSlack:
28+
type: slack-post-channel
29+
arguments:
30+
SLACK_TOKEN: xxxxxx
31+
SLACK_CHANNEL: channel1
32+
SLACK_MESSAGE: message
33+
spec:
34+
arguments: |-
35+
{
36+
"definitions": {},
37+
"$schema": "http://json-schema.org/draft-07/schema#",
38+
"type": "object",
39+
"additionalProperties": false,
40+
"patterns": [],
41+
"required": [
42+
"SLACK_TOKEN",
43+
"SLACK_CHANNEL",
44+
"SLACK_MESSAGE"
45+
],
46+
"properties": {
47+
"SLACK_IMAGE": {
48+
"type": "string",
49+
"default": "quay.io/codefreshplugins/slack-post-channel",
50+
"description": "The slack-post-channel registry/image for the step."
51+
},
52+
"SLACK_IMAGE_VERSION": {
53+
"type": "string",
54+
"default": "0.0.6",
55+
"description": "Version (tag) of the slack-post-channel image to use."
56+
},
57+
"SLACK_TOKEN": {
58+
"type": "string",
59+
"description": "The token to connect to Slack API."
60+
},
61+
"SLACK_CHANNEL": {
62+
"type": "string",
63+
"description": "Name or ID of the channel to send the message to. Use <@ID> or email to send to a user as display names are not unique (https://api.slack.com/changelog/2017-09-the-one-about-usernames)."
64+
},
65+
"SLACK_MESSAGE": {
66+
"type": "string",
67+
"description": "The message to send to the channel. Use <@ID> to tag a user. Check https://api.slack.com/reference/surfaces/formatting for details.",
68+
"default": "Message sent from Codefresh was not defined explicitely."
69+
},
70+
"LOG_LEVEL": {
71+
"type": "string",
72+
"description": "Set log level, default info",
73+
"default": "info",
74+
"enum": [
75+
"info",
76+
"debug",
77+
"warning",
78+
"error",
79+
"critical"
80+
]
81+
}
82+
83+
}
84+
}
85+
stepsTemplate: |-
86+
post-to-channel:
87+
name: slack-post-channel
88+
image: [[.Arguments.SLACK_IMAGE]]:[[.Arguments.SLACK_IMAGE_VERSION]]
89+
environment:
90+
[[ range $key, $val := .Arguments ]]
91+
- '[[ $key ]]=[[ $val ]]'
92+
[[- end ]]
93+
delimiters:
94+
left: '[['
95+
right: ']]'

0 commit comments

Comments
 (0)