Aim:
Methods to send the post messages to slack channels.
Solution:
There are two ways to post a message directly from any system to the Slack channel
-
- Incoming Webhooks
-
- Slack App
1. Incoming Webhooks:
It is an integration plugin that we can add manually to any group channel. Adding it creates a unique HTTPS URL.
EXAMPLE CODE
import jsonimport requests
def send_slack_message(payload, webhook): """Send a Slack message to a channel via a webhook.
Args: payload (dict): Dictionary containing Slack message, i.e. {"text": "This is a test"} webhook (str): Full Slack webhook URL for your chosen channel.
Returns: HTTP response code, i.e. <Response [503]> """
return requests.post(webhook, json.dumps(payload))
webhook = 'https://hooks.slack.com/services/T2HSR4Y3D/B04FR9ADC4V/Lqg9CHyR0EddV3U' # MODIFY WITH YOUR URL
payload = {"text": "Anomaly detected!"}send_slack_message(payload, webhook)
2. Slack App
Slack provides an SDK to develop an app that can control and simulates the workflow in slack. Sending messages to multiple channels, auto-response, and managing the scopes for permissions many features available in it. Slack recommends the Slack App creation, as the incoming webhooks feature will be deprecated in the future.
URL - https://api.slack.com/apps?new_app=1
Sample Code - https://api.slack.com/messaging/sending
import loggingimport os# Import WebClient from Python SDK (github.com/slackapi/python-slack-sdk)from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiError
# WebClient instantiates a client that can call API methods# When using Bolt, you can use either `app.client` or the `client` passed to listeners.client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))logger = logging.getLogger(__name__)# TS of message you want to post thread tomessage_ts = "1610144875.000600"
# ID of channel you want to post message tochannel_id = "C01JASD6802"
try: # Call the chat.postMessage method using the WebClient # The client passes the token you included in initialization result = client.chat_postMessage( channel=channel_id, thread_ts=message_ts, text="Hello again :wave:" # You could also use a blocks[] array to send richer content )
print(result)
except SlackApiError as e: print(f"Error: {e}")
Kafka Bot Message Template
Standanlone script to send messages to slack channel (incoming webhook) using python (requests)
import jsonimport sysimport randomimport requests
"""Reference -https://api.slack.com/reference/messaging/attachments
Examples - https://app.slack.com/block-kit-builder/T02GEFU92#%7B%22blocks%22:%5B%7B%22type%22:%22section%22,%22text%22:%7B%22type%22:%22mrkdwn%22,%22text%22:%22%E2%80%A2%20Detective%20Chimp%5Cn%E2%80%A2%20Bouncing%20Boy%5Cn%E2%80%A2%20Aqualad%22%7D%7D,%7B%22type%22:%22image%22,%22title%22:%7B%22type%22:%22plain_text%22,%22text%22:%22I%20Need%20a%20Marg%22,%22emoji%22:true%7D,%22image_url%22:%22https://assets3.thrillist.com/v1/image/1682388/size/tl-horizontal_main.jpg%22,%22alt_text%22:%22marg%22%7D,%7B%22type%22:%22context%22,%22elements%22:%5B%7B%22type%22:%22image%22,%22image_url%22:%22https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg%22,%22alt_text%22:%22cute%20cat%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Cat*%20has%20approved%20this%20message.%22%7D%5D%7D,%7B%22type%22:%22header%22,%22text%22:%7B%22type%22:%22plain_text%22,%22text%22:%22This%20is%20a%20header%20block%22,%22emoji%22:true%7D%7D,%7B%22type%22:%22divider%22%7D,%7B%22type%22:%22section%22,%22text%22:%7B%22type%22:%22mrkdwn%22,%22text%22:%22This%20is%20a%20mrkdwn%20section%20block%20:ghost:%20*this%20is%20bold*,%20and%20~this%20is%20crossed%20out~,%20and%20%3Chttps://google.com%7Cthis%20is%20a%20link%3E%22%7D%7D%5D%7Dhttps://app.slack.com/block-kit-builder/T02GEFU92#%7B%22blocks%22:%5B%7B%22type%22:%22header%22,%22text%22:%7B%22type%22:%22plain_text%22,%22text%22:%22New%20request%22,%22emoji%22:true%7D%7D,%7B%22type%22:%22section%22,%22fields%22:%5B%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Type:*%5CnPaid%20Time%20Off%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Created%20by:*%5Cn%3Cexample.com%7CFred%20Enriquez%3E%22%7D%5D%7D,%7B%22type%22:%22section%22,%22fields%22:%5B%7B%22type%22:%22mrkdwn%22,%22text%22:%22*When:*%5CnAug%2010%20-%20Aug%2013%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Type:*%5CnPaid%20time%20off%22%7D%5D%7D,%7B%22type%22:%22section%22,%22fields%22:%5B%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Hours:*%5Cn16.0%20(2%20days)%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Remaining%20balance:*%5Cn32.0%20hours%20(4%20days)%22%7D%5D%7D,%7B%22type%22:%22section%22,%22text%22:%7B%22type%22:%22mrkdwn%22,%22text%22:%22%3Chttps://example.com%7CView%20request%3E%22%7D%7D%5D%7D"""# PASTE YOUR SLACK CHANNEL WEBHOOK URL HEREurl = 'https://hooks.slack.com/services/XXXXX/XXXXX/XXXXX'# TYPE YOUR SLACK CHANNEL NAME HEREchannel_name = "#dev-rd"
emoji_data = ''':sunny::umbrella::cyclone::snowflake::zap::snowman::snake::earth_asia::computer::loudspeaker::hourglass::loop::satellite::mag::high_brightness::bomb::simple_smile::traffic_light::beginner::circus_tent::performing_arts:'''name_data = '''botloadadminbotincredibotvotebotokokbothumanbotslavebotbotamotabagbotblitzbotfabbotfatbotbotroverfancybothelpingbotgoodbotbotsaucebatbotbabybotunseenbotremotebotzoombotsuperbotcoolbotwackybotwickedbotmodernbotsavagebotblasterbotprimebotspiderbot'''
name_data = name_data.split("\n")emoji_data = emoji_data.split("\n")# Getting random bot namebot_name = random.choice(name_data)# Getting random slack emojiemoji_id = random.choice(emoji_data)# Generating random hex color codehex_number = '#' + str(hex(random.randint(1118481, 16777215)))[2:]
sample_attachment1 = [ { "fallback": "New open task [Urgent]:<https://www.vijayanandrp.com/|Vijay Profile>", "pretext": "New open task [Urgent]:<https://www.vijayanandrp.com/|Vijay Profile>", # "color": "#D00000", "color": hex_number, "unfurl_links": True, "fields": [ { "title": """A Sample Message from Python. This is much easier than I thought it would be. <http://www.youtube.com/watch?v=wq1R93UMqlk| Youtube>""", "value": f"New Incoming Message {emoji_id}", "short": False, } ] }]
sample_attachment = [ { "mrkdwn_in": ["text"], "color": "#36a64f", "pretext": "Optional pre-text that appears above the attachment block", "author_name": "Vijay_Anand", "author_link": "http://flickr.com/bobby/", "author_icon": "https://placeimg.com/16/16/people", "title": "title", "title_link": "https://api.slack.com/", "text": "Optional `text` that appears within the attachment", "fields": [ { "title": "A field's title", "value": "This field's value", "short": False }, { "title": "A short field's title", "value": "A short field's value", "short": True }, { "title": "A second short field's title", "value": "A second short field's value", "short": True } ], "thumb_url": "http://placekitten.com/g/200/200", "footer": "footer", "footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png", "ts": 123456789 }]
sample_attachment2 = [{ "blocks": [ { "type": "header", "text": { "type": "plain_text", "text": "New request", "emoji": True } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Type:*\nPaid Time Off" }, { "type": "mrkdwn", "text": "*Created by:*\n<example.com|Fred Enriquez>" } ] }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*When:*\nAug 10 - Aug 13" }, { "type": "mrkdwn", "text": "*Type:*\nPaid time off" } ] }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Hours:*\n16.0 (2 days)" }, { "type": "mrkdwn", "text": "*Remaining balance:*\n32.0 hours (4 days)" } ] }, { "type": "section", "text": { "type": "mrkdwn", "text": "<https://example.com|View request>" } } ]}]
if __name__ == '__main__': for attachment in [sample_attachment1, sample_attachment, sample_attachment2]: bot_name = random.choice(name_data) emoji_id = random.choice(emoji_data) hex_number = '#' + str(hex(random.randint(1118481, 16777215)))[2:] print(bot_name, emoji_id, hex_number) slack_data = { "username": bot_name, "icon_emoji": emoji_id, "channel": channel_name,
"attachments": attachment } byte_length = str(sys.getsizeof(slack_data)) headers = {'Content-Type': "application/json", 'Content-Length': byte_length} response = requests.post(url, data=json.dumps(slack_data), headers=headers) print(response)
if response.status_code != 200: raise Exception(response.status_code, response.text)
#mythoughts