|
| 1 | +from slack_sdk import WebClient |
| 2 | +from slack_sdk.errors import SlackApiError |
| 3 | +import os |
| 4 | +import sys |
| 5 | + |
| 6 | +channels_list = {} |
| 7 | + |
| 8 | +def fetch_channels(client: WebClient, next_cursor: str = ""): |
| 9 | + try: |
| 10 | + result = client.conversations_list( |
| 11 | + exclude_archived=True, |
| 12 | + limit=500, |
| 13 | + types="public_channel,private_channel", |
| 14 | + cursor=next_cursor, |
| 15 | + ) |
| 16 | + for channel in result["channels"]: |
| 17 | + channels_list[channel["name"]] = channel["id"] |
| 18 | + return result |
| 19 | + except SlackApiError as e: |
| 20 | + print(f"Slack error: {e}") |
| 21 | + |
| 22 | + |
| 23 | +def validate_vars(): |
| 24 | + MANDATORY_ENV_VARS = ["SLACK_CHANNEL", "MESSAGE_CONTENT", "PIPELINE_NAME", "SLACK_BOT_TOKEN"] |
| 25 | + for var in MANDATORY_ENV_VARS: |
| 26 | + if var not in os.environ: |
| 27 | + raise EnvironmentError("Error. Env var {} is not set and is required to run.".format(var)) |
| 28 | + |
| 29 | + |
| 30 | +def main(): |
| 31 | + validate_vars() |
| 32 | + |
| 33 | + slack_channel = os.environ["SLACK_CHANNEL"] |
| 34 | + message_content = os.environ["MESSAGE_CONTENT"] |
| 35 | + pipeline_name = os.environ["PIPELINE_NAME"] |
| 36 | + slack_bot_token = os.environ["SLACK_BOT_TOKEN"] |
| 37 | + |
| 38 | + try: |
| 39 | + client = WebClient(token=slack_bot_token) |
| 40 | + |
| 41 | + # Get the channel ID from the name |
| 42 | + next_cursor = fetch_channels(client)["response_metadata"]["next_cursor"] |
| 43 | + while next_cursor: |
| 44 | + next_cursor = fetch_channels(client, next_cursor)["response_metadata"][ |
| 45 | + "next_cursor" |
| 46 | + ] |
| 47 | + |
| 48 | + channel_id = channels_list[slack_channel] |
| 49 | + |
| 50 | + # Send the slack message, if it fails an exception will fire |
| 51 | + client.chat_postMessage( |
| 52 | + channel=channel_id, text=message_content, username=pipeline_name |
| 53 | + ) |
| 54 | + print("Message sent.") |
| 55 | + except SlackApiError as e: |
| 56 | + print(f"Error posting message: {e}") |
| 57 | + sys.exit(1) |
| 58 | + except KeyError: |
| 59 | + print( |
| 60 | + f"Channel {slack_channel} not found. If it a private channel: Mention @Github_Actions & invite them to the channel first" |
| 61 | + ) |
| 62 | + sys.exit(1) |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + main() |
0 commit comments