Coder Social home page Coder Social logo

archive / github-actions-slack Goto Github PK

View Code? Open in Web Editor NEW
77.0 2.0 32.0 1.1 MB

Github Action for sending message (and reactions/threads/update/blocks) to Slack - With support for Slack's optional arguments

License: MIT License

JavaScript 100.00%
github-actions integration messaging nodejs slack

github-actions-slack's Introduction

Github Action for sending message (and reactions/threads/update/blocks) to Slack

โ€” With support for Slack's optional arguments

This Action allows you to send messages (and reactions/threads/update/blocks) to Slack from your Github Actions. Supports Slack's required arguments as well as all the optional once. It's JavaScript-based and thus fast to run.

The goal is to have zero npm/yarn dependencies except the two from Github that is required for an action to work (@actions/core & @actions/github).

Slack result

This action is just an HTTPS call to Slack API, so you can easily build this by yourself, or use this action or any one of the hundred other Slack actions available.

Requirements

  1. Slack Workspace and Channel(s)
  2. A Slack App and Bot - the App and Bot will be used to send messages to your channel. It sounds hard, but it's not :)
  3. A Github Action - the place where you wants to send Slack messages
  4. Github Secret - the Slack Bot auth token, used when posting messages to Slack API

Important

With the latest changes to Slack API, please use channel id instead of channel name. E.g. use CPPUV5KU0 instead of test (You can find the ID in the API calls or https://stackoverflow.com/questions/40940327/what-is-the-simplest-way-to-find-a-slack-team-id-and-a-channel-id)

Setup

This action supports:

    1. Send messages
    1. Send thread response to message
    1. Send reaction on sent messages

1. Send messages to Slack

Required: Github Repository Secret:

  • SLACK_BOT_USER_OAUTH_ACCESS_TOKEN - This is the Slack App token, the credentials for allowing you to send messages from github to Slack

Required: Github Action Parameters:

  • slack-bot-user-oauth-access-token - SLACK_BOT_USER_OAUTH_ACCESS_TOKEN secret

  • slack-channel - The channel/channels where you want the message (comma separated)

  • slack-text - The text of the message (or use slack-optional-blocks)

Optional: Github Action Parameters:

All the optional parameters that Slack supports, can be sent via the slack-optional-xxx parameter.

Slack parameter name Yaml parameter name
icon_emoji slack-optional-icon_emoji
link_names slack-optional-link_names

and so forth.

Please see Slack API documentation for all available optional parameters: https://api.slack.com/methods/chat.postMessage

Result / return value

  • slack-result (.outputs.slack-result) - Contains the result of the sent message. This can be used for following steps like sending a reaction

Sample slack-result:

{
  "statusCode": 200,
  "statusMessage": "OK",
  "ok": true,
  "result": "<deprecated - same as response but as string>",
  "response": {
    "ok": true,
    "channel": "XXXX",
    "ts": "1612623790.009600",
    "message": {
      "type": "message",
      "subtype": "bot_message",
      "text": "Lipsum",
      "ts": "1612623790.009600",
      "username": "Lipsum",
      "bot_id": "XXXX"
    }
  }
}

If you want to output or debug the result, add:

      - name: Send Slack Message Result
        run: echo "${{ steps.send-message.outputs.slack-result }}"

Sample Action file with Slack Channel and Text

.github/workflows/2-slack-notification.yml

This will send a Slack message every time someone push, creates pull request or create an issue

name: slack-notification

on: [push, pull_request, issues]

jobs:
  slack-notifications:
    runs-on: ubuntu-20.04
    name: Sends a message to Slack when a push, a pull request or an issue is made
    steps:
      - name: Send message to Slack API
        uses: archive/[email protected]
        id: notify
        with:
          slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
          slack-channel: CPPUV5KU0
          slack-text: Hello! Event "${{ github.event_name }}" in "${{ github.repository }}" ๐Ÿค“
      - name: Result from "Send Message"
        run: echo "The result was ${{ steps.notify.outputs.slack-result }}"

Slack result

Sample Action file with Slack optional parameters

.github/workflows/2-slack-notification.yml

name: slack-notification-with-optional-parameters

on: [push, pull_request, issues]

jobs:
  slack-notification-with-optional-parameters:
    runs-on: ubuntu-20.04
    name: Sends a message to Slack when a push, a pull request or an issue is made
    steps:
      - name: Send message to Slack API
        uses: archive/[email protected]
        id: notify
        with:
          slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
          slack-channel: CPPUV5KU0 #USE CHANNEL ID, NOT CHANNEL NAME, SINCE ID IS USED IN NEW SLACK API's
          slack-text: Hello! Something is burning! Or not...
          slack-optional-icon_emoji: ":fire:"
      - name: Result from "Send Message"
        run: echo "The result was ${{ steps.notify.outputs.slack-result }}"

Slack result

2. Send thread response to message to Slack

To send a thread response you have the same setup as for sending a message, but you add some extra optional parameters:

  • slack-optional-thread_ts - The timestamp of the message you want to reply/send thread to. You can find the timestamp in the response payload after sending a message

  • slack-optional-reply_broadcast - To broadcast thread reply in channel

Sample Action file

.github/workflows/4-slack-thread.yml

See Send Thread Message part below:

name: slack-thread

on: [push, issues]

jobs:
  slack-thread:
    runs-on: ubuntu-20.04
    name: Sends a message to Slack when a push, a pull request or an issue is made

    steps:
      - name: Send Slack Message
        uses: archive/github-actions-slack@master
        id: send-message

        with:
          slack-function: send-message
          slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
          slack-channel: CPPUV5KU0
          slack-text: This is a message

      - name: Send "Slack Message" Result
        run: echo "Data - ${{ steps.send-message.outputs.slack-result }}"

      - name: Some step in between
        run: echo "..."

      - name: Send Thread Message
        uses: archive/github-actions-slack@master
        with:
          slack-function: send-message
          slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
          slack-channel: ${{ fromJson(steps.send-message.outputs.slack-result).response.channel }}
          slack-text: This is a thread reply
          slack-optional-thread_ts: ${{ fromJson(steps.send-message.outputs.slack-result).response.message.ts }}
          #slack-optional-reply_broadcast: true # To broadcast thread reply in channel

      - name: Send "Send Thread Message" Result
        run: echo "Data - ${{ steps.send-message.outputs.slack-result }}"

Slack result

3. Send reaction on sent messages to Slack

Required: Github Repository Secret:

  • SLACK_BOT_USER_OAUTH_ACCESS_TOKEN - This is the Slack App token, the credentials for allowing you to send messages from github to Slack

Required: Github Action Parameters:

  • slack-bot-user-oauth-access-token - SLACK_BOT_USER_OAUTH_ACCESS_TOKEN secret

  • slack-channel - The channel where you want the message. You can find the channel id in the response payload after sending a message

  • slack-emoji-name - The name of the emoji to send (e.g. "fire"/"thumbsup")

  • slack-message-timestamp - The unique ts/timestamp of the message you want to react to. You can find the timestamp in the response payload after sending a message

Result / return value

  • slack-result (.outputs.slack-result) - Contains the result of the sent reaction

Sample Action file with Slack Channel and Text

.github/workflows/3-slack-reaction.yml

This will send a Slack message every time someone push, creates pull request or create an issue, and then, create a reaction to it

name: slack-reaction

on: [push, issues]

jobs:
  slack-reaction:
    runs-on: ubuntu-20.04
    name: Sends a message to Slack when a push, a pull request or an issue is made

    steps:
      - name: Send Slack Message
        uses: archive/[email protected]
        id: send-message

        with:
          slack-function: send-message
          slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
          slack-channel: CPPUV5KU0
          slack-text: Time to react...

      - name: Send Slack Message Result
        run: echo "Data - ${{ steps.send-message.outputs.slack-result }}"

      - name: Some step in between
        run: echo "..."

      - name: Send Slack Reaction To Message
        uses: archive/[email protected]
        with:
          slack-function: send-reaction
          slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
          slack-channel: ${{ fromJson(steps.send-message.outputs.slack-result).response.channel }}
          slack-emoji-name: thumbsup
          slack-message-timestamp: ${{ fromJson(steps.send-message.outputs.slack-result).response.message.ts }}

      - name: Send Slack Reaction To Message Result
        run: echo "Data - ${{ steps.send-message.outputs.slack-result }}"

Slack result

4. Update message

Similar to Add Reaction, but with text instead.

Please see .github/workflows/5-slack-update-message.yml

5. Using blocks

With blocks you can create more rich and complex messages / message layouts: https://api.slack.com/messaging/composing/layouts

image

For some examples, please see:

How to setup your first Github Action in your repository that will call this Action

1. Create a Slack bot

Follow this guide on how to create a Slack App and Bot for your workspace:

You should:

  1. Create a new Slack App, https://api.slack.com/apps?new_app=1
  2. Go to "Basic Information" > "Display Information" > "App icon & Preview" and add avatar for you App. This will be shown in Slack when you receive messages
  3. Go to "Bot User" > "Add" and add a bot user to your Slack App
  4. Go to "Install App" > "Install App to Workspace" to install your Slack App into your Slack workspace
  5. Done

2. Save Bot Access Token on Github

To be able to send messages to slack, the Action needs the Auth Token for the Slack App. Since the Auth Token is sensitive information, you should NOT place it in the yaml file of the Action, but instead in the Github Secrets area.

  1. Go to your App on Slack, https://api.slack.com/apps/
  2. Go to "OAuth & Permissions" > "Bot User OAuth Access Token"
  3. Copy the Bot User OAuth Access Token
  4. Go to your Github Repo
  5. Go to "Settings" > "Secrets" for the repo
  6. Create a new secret called SLACK_BOT_USER_OAUTH_ACCESS_TOKEN with the value from Bot User OAuth Access Token
  7. Done

2. Create a new Github Action

  1. Go to your github repo
  2. Go to actions
  3. Create a new one, you can use the samples above

Q&A

It's not working

Please look at the individual steps on your Github Action. Maybe you have forgotten to set Channel or Token:

Sample Error

To debug action and see what payload is being sent to slack, enable debugging: https://docs.github.com/en/actions/configuring-and-managing-workflows/managing-a-workflow-run#enabling-debug-logging (ACTIONS_RUNNER_DEBUG=true and ACTIONS_STEP_DEBUG=true under Settings > Secrets)

What information about the repo etc is available?

You can easily print everything you have while running the action. It can be a good way to see what you can send to Slack.

on: push

jobs:
  one:
    runs-on: ubuntu-20.04
    steps:
      - name: Dump GitHub context
        env:
          GITHUB_CONTEXT: ${{ toJson(github) }}
        run: echo "$GITHUB_CONTEXT"
      - name: Dump job context
        env:
          JOB_CONTEXT: ${{ toJson(job) }}
        run: echo "$JOB_CONTEXT"
      - name: Dump steps context
        env:
          STEPS_CONTEXT: ${{ toJson(steps) }}
        run: echo "$STEPS_CONTEXT"
      - name: Dump runner context
        env:
          RUNNER_CONTEXT: ${{ toJson(runner) }}
        run: echo "$RUNNER_CONTEXT"
      - name: Dump strategy context
        env:
          STRATEGY_CONTEXT: ${{ toJson(strategy) }}
        run: echo "$STRATEGY_CONTEXT"
      - name: Dump matrix context
        env:
          MATRIX_CONTEXT: ${{ toJson(matrix) }}
        run: echo "$MATRIX_CONTEXT"

From: https://help.github.com/en/github/automating-your-workflow-with-github-actions/contexts-and-expression-syntax-for-github-actions

Why JavaScript and not Shell/etc?

"JavaScript actions can run directly on any of the GitHub-hosted virtual machines, and separate the action code from the environment used to run the code. Using a JavaScript action simplifies the action code and executes faster than a Docker container action." (https://help.github.com/en/github/automating-your-workflow-with-github-actions/about-actions)

How does the Action JavaScript code work

It's simple, it just takes all the parameters and does an HTTPS POST to api.slack.com.

I want another avatar to be used in Slack

By default the avatar in Slack will be the same as for the Slack App you created. If you want to change this based on action, look at the https://api.slack.com/methods/chat.postMessage icon_emoji parameter.

Why did you build your own?

It was a good way to learn more about Github Actions

Why should I use this?

This action is just an HTTPS POST to Slack API, so you can easily build this by yourself, or use this, or use any other action available on the marketplace :)

Development and testing

See package.json for yarn lint, yarn test, etc.

Remember to create the dist with yarn build.

To run local integration test (from this repository):

env BOT_USER_OAUTH_ACCESS_TOKEN=<YOUR TOKEN> CHANNEL=<YOUR CHANNEL> node integration-test/end-to-end.js

github-actions-slack's People

Contributors

archive avatar dependabot[bot] avatar kengotoda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

github-actions-slack's Issues

Include optional params on update?

Hello

Thanks for this action, very nice. One thing I'm wondering is whether it would be possible to add support for including optional params on message update. I'm thinking of appending block sections as new details become available during a build.

Also, would it be possible to include an example showing the use of attachments/blocks? I managed it but found it a bit tricky, and it wasn't 100% clear on what other params were mandatory - I had to go to the code for that. Also, I believe it's possible to send just a block section, so maybe don't make the text field mandatory?

Thanks again.

Emojis Do not work

Tried this workflow and the message I get in slack is not showing and emoji. Not sure why but I tried a non custom one. I would ultimately like to send a custom one.

This is the message I received but no icon. In the input you can see the fire icon is shown and so its enabled but through this action icon_emoji does not work.

Screenshot 2024-05-29 at 2 35 07โ€ฏPM
name: Manual Test of Slack Messaging

on:
  workflow_dispatch:

jobs:
  slack-notifications:
    runs-on: ubuntu-20.04
    name: Sends a message to Slack when a push, a pull request or an issue is made
    steps:
      - name: Send message to Slack API
        uses: archive/[email protected]
        id: notify
        with:
          slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_TOKEN }}
          slack-channel: *********
          slack-text: Hello! Event "${{ github.event_name }}" in "${{ github.repository }}"
          slack-optional-icon_emoji: ":fire:"
      - name: Result from "Send Message"
        run: echo "The result was ${{ steps.notify.outputs.slack-result }}"  

Feature request: Attachments

Can we attach files?

We are running some automated tests. I'd really like it if I could attach failed testing results as a .txt file to a Slack message, to alert the developer.

This is a little easier than having them dig through GitHub log files.

Is there any way to do this? I didn't see it listed in the features, so this could be a useful add.

I may have a work around with my product to just use Sendmail, but slack is really our preferred communication channel!

== John ==

GitHub Workflows YAML Files uses incorrect parameter

The sample action files that use the Slack's Block Kit uses the slack-blocks parameter instead of slack-optional-blocks in .github/workflows/12-slack-message-blocks-update.yml and .github/workflows/11-slack-message-blocks.yml.

Is Windows supported?

Hi, when I try the API with my own user (I copied my channel ID), I get this error:

image

New lines not working during slack-update-message-text

It looks like it is impossible to use text with new lines \n when using update-message

  uses: archive/github-actions-slack@master
  if: failure()
  with:
    slack-function: update-message
    slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_TOKEN }}
    slack-channel: ${{ fromJson(steps.send-message.outputs.slack-result).response.channel }}
    slack-update-message-text: ${{ steps.messages.outputs.failed }}
    slack-update-message-ts: ${{ fromJson(steps.send-message.outputs.slack-result).response.message.ts }}
    slack-optional-unfurl_media: false
    slack-optional-unfurl_links: false

In my case in ${{ steps.messages.outputs.failed }} I have complex message with new lines and emojis. Original text will edited but text will be in one line

Build: Android 1.5.5.0 (1567) \n failed

Update existing message

I was thinking that since lack-optional-thread_ts is already supported, it would be neat if (like with voxmedia/github-action-slack-notify-build) it was possible to update an existing message with new content. Mostly to change status during deployment from initial started to failure or success. Would that be difficult to implement?

Error: Not In Channel

I'm trying to use this action but I keep getting an error

Run archive/[email protected]
  with:
    slack-bot-user-oauth-access-token: ***
    slack-channel: software-website
    slack-text: just work
    slack-optional-icon_emoji: :rocket:
DEBUG: Payload {"channel":"software-website","text":"just work","icon_emoji":":rocket:"}
Error: ["\"Error! {\\\"statusCode\\\":200,\\\"result\\\":\\\"{\\\\\\\"ok\\\\\\\":false,\\\\\\\"error\\\\\\\":\\\\\\\"not_in_channel\\\\\\\"}\\\"}\""]

It doesn't make any sense because I have the app installed to my workspace and the bot seems to be in the channel:

Screen Shot 2021-02-05 at 5 00 40 PM

I tried both channel IDs and names. This shit just doesn't work lol.

Add reaction to existing message

Hi, great library!

We use this to send a message like

๐Ÿš€ Deploying to production

Just before a deployment kicks off.

Since the slack-result output contains channel and timestamp fields, it'd be very useful to be able to add a โœ”๏ธ emoji to the same message after the deployment is complete (or โŒ if it failed). I was imagining something like this, with a new method input corresponding to https://api.slack.com/methods/chat.postMessage, https://api.slack.com/methods/reactions.add etc.:

- id: notify
  uses: archive/[email protected]
  with:
    method: chat.postMessage # this would be the default method for backwards compatibility
    slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
    slack-channel: deployments
    slack-text: ':rocket: Deploying to production'

- run: ./deploy.sh

- uses: archive/[email protected]
  with:
    method: reactions.add
    slack-bot-user-oauth-access-token: ${{ secrets.SLACK_BOT_USER_OAUTH_ACCESS_TOKEN }}
    slack-channel: ${{ steps.notify.outputs.slack-result.channel }}
    timestamp: ${{ steps.notify.outputs.slack-result.ts }}
    name: white_check_mark

Improve error handling

Currently, I can see Error: {} in the output which is not very useful. Maybe you can add more information when the error occurs.
In my case, I'm trying to replay in the thread and I guess the message format is wrong (I guess)

Upgrade from NodeJS12 to NodeJS 16 - Deprecation warning

Hello!

Thanks for the great action @archive!

With regards to:
https://github.blog/changelog/2022-09-22-github-actions-all-actions-will-begin-running-on-node16-instead-of-node12/

It would be great to get this action updated to reduce deprecation warnings ๐Ÿ™‡
Not urgent otherwise as NodeJS12 isn't going anywhere soon.

Happy to raise a PR, but maybe easiest for someone with push access to bump the version and check everything looks OK!

using: "node12"

Cheers!

Breaks newline and tab

When passing slack example from the documentation

This is a line of text.\nAnd this is another one.

Should appear on slack like:

This is a line of text.
And this is another one.

But instead it shows

This is a line of text.\nAnd this is another one.

This is likely because you're escaping the escape character, in the payload...

{"channel":"some-channel","text":"This is a line of text.\\nAnd this is another one."}

node 20 support

Hello, thanks for the work done.
Do you plan to support node 20 ?

Wildcard inputs don't work anymore

Hi, thanks for this Action. It seems that around May 2020, GitHub added validation resulting in warnings like this:

##[warning]Unexpected input(s) 'slack-optional-icon_emoji', valid inputs are ['slack-bot-user-oauth-access-token', 'slack-channel', 'slack-text', 'slack-optional-x']

The icon_emoji input also isn't passed in as an INPUT_... environment variable. So this mechanism will, unfortunately, need to be rethought.

Discussion/similar issue in another Action: cypress-io/github-action#141

The `set-output` command is deprecated and will be disabled soon.

Action is producing warning below:

Warning: The `set-output` command is deprecated and will be disabled soon. Please upgrade to using Environment Files. 
For more information see: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.