Add Slack messaging
This commit is contained in:
55
slack.py
Normal file
55
slack.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from langchain_core.documents import Document
|
||||
from slack_sdk import WebClient
|
||||
from slack_sdk.errors import SlackApiError
|
||||
|
||||
|
||||
def prepare_message_blocks(stories: list[Document]) -> list:
|
||||
blocks = []
|
||||
for story in stories:
|
||||
block = [
|
||||
{
|
||||
"type": "header",
|
||||
"text": {"type": "plain_text", "text": story.metadata["title"]},
|
||||
},
|
||||
{
|
||||
"type": "context",
|
||||
"elements": [
|
||||
{
|
||||
"type": "plain_text",
|
||||
"text": f"Categories: {', '.join(story.metadata.get('categories', []))}",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"type": "context",
|
||||
"elements": [
|
||||
{
|
||||
"type": "plain_text",
|
||||
"text": f"Posted on: {story.metadata['created_at']}",
|
||||
}
|
||||
],
|
||||
},
|
||||
{"type": "section", "text": {"type": "mrkdwn", "text": story.page_content}},
|
||||
]
|
||||
|
||||
blocks.append(block)
|
||||
return blocks
|
||||
|
||||
|
||||
def send_message(channel: str, text: str) -> None:
|
||||
client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
|
||||
|
||||
try:
|
||||
response = client.chat_postMessage(
|
||||
channel=channel,
|
||||
username="HN Ragandy",
|
||||
text=text,
|
||||
unfurl_links=False,
|
||||
)
|
||||
response.validate()
|
||||
logging.info(f"Message sent successfully to channel {channel}")
|
||||
except SlackApiError as e:
|
||||
logging.error(f"Error sending message: {e.response['error']}")
|
||||
Reference in New Issue
Block a user