Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slack agent to send message to slack #21

Merged
merged 10 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion backend/.env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ OUTRO_VIDEO_ID=
BRAND_IMAGE_ID=

# Profanity Remover Agent
BEEP_AUDIO_ID=
BEEP_AUDIO_ID=

# Slack Agent
SLACK_CHANNEL_NAME=
SLACK_BOT_TOKEN=
1 change: 1 addition & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ python-dotenv==1.0.1
replicate==1.0.1
yt-dlp==2024.10.7
videodb==0.2.5
slack_sdk==3.33.2
93 changes: 93 additions & 0 deletions backend/spielberg/agents/slack_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import logging
import os

from spielberg.agents.base import BaseAgent, AgentResponse, AgentStatus
from spielberg.core.session import (
Session,
TextContent,
MsgStatus,
ContextMessage,
RoleTypes,
)
from spielberg.tools.slack import send_message_to_channel
from spielberg.llm.base import LLMResponseStatus

logger = logging.getLogger(__name__)

# Slack App Setup:
# 1. Go to https://api.slack.com/apps and create a new app
# 2. Add the 'chat:write' OAuth scope under 'Bot Token Scopes'
# 3. Install the APP in your slack workspace
# 4. Copy the 'Bot User OAuth Token' and set it as an environment variable SLACK_BOT_TOKEN
# 5. Invite the bot to the channel where you want to send messages
# 6. Set the channel name where bot can send the message to SLACK_CHANNEL_NAME


class SlackAgent(BaseAgent):
def __init__(self, session: Session, **kwargs):
self.agent_name = "slack"
self.description = "Messages to a Slack channel"
self.parameters = self.get_parameters()
super().__init__(session=session, **kwargs)

def run(self, message: str, *args, **kwargs) -> AgentResponse:
"""
Send a message to a Slack channel.
:param str message: The message to send to the Slack channel_name.
:param args: Additional positional arguments.
:param kwargs: Additional keyword arguments.
:return: The response containing information about the Slack message operation.
:rtype: AgentResponse
"""
channel_name = os.getenv("SLACK_CHANNEL_NAME")
if not channel_name:
return AgentResponse(
status=AgentStatus.ERROR,
message="Please set the SLACK_CHANNEL_NAME in the .env",
)
text_content = TextContent(
agent_name=self.agent_name,
status=MsgStatus.progress,
status_message="Sending message to Slack...",
)
self.output_message.content.append(text_content)
self.output_message.push_update()
try:
# TOOD: Need improvemenents in below prompt
slack_llm_prompt = (
"Format the following message that slack can render nicely.\n"
"Give the output which can be directly passed to slack (no blockquotes until required because of code etc.)\n"
"Also, don't include you can copy this message etc.\n"
f"message: {message}"
)
slack_message = ContextMessage(
content=slack_llm_prompt, role=RoleTypes.user
)
llm_response = self.llm.chat_completions([slack_message.to_llm_msg()])
if llm_response.status == LLMResponseStatus.ERROR:
raise Exception(f"LLM Failed with error {llm_response.content}")
formatted_message = llm_response.content
self.output_message.actions.append("Sending message to Slack...")
response = send_message_to_channel(formatted_message, channel_name)
text_content.text = formatted_message
text_content.status = MsgStatus.success
text_content.status_message = (
f"Here is the slack message sent to {channel_name}"
)
self.output_message.publish()
return AgentResponse(
status=AgentStatus.SUCCESS,
message=f"Message sent to Slack channel: {channel_name}",
data={
"channel_name": channel_name,
"message": formatted_message,
"ts": response["ts"],
},
)
except Exception as e:
logger.exception(f"Error in {self.agent_name}")
text_content.status = MsgStatus.error
text_content.status_message = f"Error sending message to Slack: {str(e)}"
self.output_message.publish()
error_message = f"Agent failed with error: {str(e)}"
return AgentResponse(status=AgentStatus.ERROR, message=error_message)
2 changes: 2 additions & 0 deletions backend/spielberg/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from spielberg.agents.profanity_remover import ProfanityRemoverAgent
from spielberg.agents.image_generation import ImageGenerationAgent
from spielberg.agents.stream_video import StreamVideoAgent
from spielberg.agents.slack_agent import SlackAgent

from spielberg.core.session import Session, InputMessage, MsgStatus
from spielberg.core.reasoning import ReasoningEngine
Expand Down Expand Up @@ -43,6 +44,7 @@ def __init__(self, db, **kwargs):
ProfanityRemoverAgent,
ImageGenerationAgent,
StreamVideoAgent,
SlackAgent,
]

def add_videodb_state(self, session):
Expand Down
10 changes: 10 additions & 0 deletions backend/spielberg/tools/slack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import os

from slack_sdk import WebClient


def send_message_to_channel(message, channel_name):
slack_token = os.environ.get("SLACK_BOT_TOKEN")
slack_client = WebClient(token=slack_token)
response = slack_client.chat_postMessage(channel=channel_name, text=message)
return response