Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Integrate slack (#560)

Wendong-Fanc28bae63ba00
diff --git a/camel/functions/__init__.py b/camel/functions/__init__.py
index 4abb1cc4b..1f63cdfb8 100644
--- a/camel/functions/__init__.py
+++ b/camel/functions/__init__.py
@@ -25,6 +25,7 @@ from .retrieval_functions import RETRIEVAL_FUNCS
from .search_functions import SEARCH_FUNCS
from .twitter_function import TWITTER_FUNCS
from .weather_functions import WEATHER_FUNCS
+from .slack_functions import SLACK_FUNCS
__all__ = [
'OpenAIFunction',
@@ -37,4 +38,5 @@ __all__ = [
'SEARCH_FUNCS',
'TWITTER_FUNCS',
'WEATHER_FUNCS',
+ 'SLACK_FUNCS',
]
diff --git a/camel/functions/slack_functions.py b/camel/functions/slack_functions.py
new file mode 100644
index 000000000..49a54b2c5
--- /dev/null
+++ b/camel/functions/slack_functions.py
@@ -0,0 +1,275 @@
+# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+# Licensed under the Apache License, Version 2.0 (the ā€œLicenseā€);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an ā€œAS ISā€ BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+from typing import TYPE_CHECKING, List, Optional
+
+if TYPE_CHECKING:
+ from ssl import SSLContext
+
+ from slack_sdk import WebClient
+
+from slack_sdk.errors import SlackApiError
+
+from camel.functions import OpenAIFunction
+
+logger = logging.getLogger(__name__)
+
+
+def _login_slack(
+ slack_token: Optional[str] = None,
+ ssl: Optional[SSLContext] = None,
+) -> WebClient:
+ r"""Authenticate using the Slack API.
+
+ Args:
+ slack_token (str, optional): The Slack API token. If not provided, it
+ attempts to retrieve the token from the environment variable
+ SLACK_BOT_TOKEN or SLACK_USER_TOKEN.
+ ssl (SSLContext, optional): SSL context for secure connections.
+ Defaults to `None`.
+
+ Returns:
+ WebClient: A WebClient object for interacting with Slack API.
+
+ Raises:
+ ImportError: If slack_sdk package is not installed.
+ KeyError: If SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment variables
+ are not set.
+ """
+ try:
+ from slack_sdk import WebClient
+ except ImportError as e:
+ raise ImportError(
+ "Cannot import slack_sdk. Please install the package with \
+ `pip install slack_sdk`."
+ ) from e
+ if not slack_token:
+ slack_token = os.environ.get("SLACK_BOT_TOKEN") or os.environ.get(
+ "SLACK_USER_TOKEN"
+ )
+ if not slack_token:
+ raise KeyError(
+ "SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment variable not set."
+ )
+
+ client = WebClient(token=slack_token, ssl=ssl)
+ logger.info("Slack login successful.")
+ return client
+
+
+def create_slack_channel(name: str, is_private: Optional[bool] = True) -> str:
+ r"""Creates a new slack channel, either public or private.
+
+ Args:
+ name (str): Name of the public or private channel to create.
+ is_private (bool, optional): Whether to create a private channel
+ instead of a public one. Defaults to `True`.
+
+ Returns:
+ str: JSON string containing information about Slack channel created.
+
+ Raises:
+ SlackApiError: If there is an error during get slack channel
+ information.
+ """
+ try:
+ slack_client = _login_slack()
+ response = slack_client.conversations_create(
+ name=name, is_private=is_private
+ )
+ channel_id = response["channel"]["id"]
+ response = slack_client.conversations_archive(channel=channel_id)
+ return str(response)
+ except SlackApiError as e:
+ return f"Error creating conversation: {e.response['error']}"
+
+
+def join_slack_channel(channel_id: str) -> str:
+ r"""Joins an existing Slack channel.
+
+ Args:
+ channel_id (str): The ID of the Slack channel to join.
+
+ Returns:
+ str: A confirmation message indicating whether join successfully or an
+ error message.
+
+ Raises:
+ SlackApiError: If there is an error during get slack channel
+ information.
+ """
+ try:
+ slack_client = _login_slack()
+ response = slack_client.conversations_join(channel=channel_id)
+ return str(response)
+ except SlackApiError as e:
+ return f"Error creating conversation: {e.response['error']}"
+
+
+def leave_slack_channel(channel_id: str) -> str:
+ r"""Leaves an existing Slack channel.
+
+ Args:
+ channel_id (str): The ID of the Slack channel to leave.
+
+ Returns:
+ str: A confirmation message indicating whether leave successfully or an
+ error message.
+
+ Raises:
+ SlackApiError: If there is an error during get slack channel
+ information.
+ """
+ try:
+ slack_client = _login_slack()
+ response = slack_client.conversations_leave(channel=channel_id)
+ return str(response)
+ except SlackApiError as e:
+ return f"Error creating conversation: {e.response['error']}"
+
+
+def get_slack_channel_information() -> str:
+ r"""Retrieve Slack channels and return relevant information in JSON format.
+
+ Returns:
+ str: JSON string containing information about Slack channels.
+
+ Raises:
+ SlackApiError: If there is an error during get slack channel
+ information.
+ """
+ try:
+ slack_client = _login_slack()
+ response = slack_client.conversations_list()
+ conversations = response["channels"]
+ # Filtering conversations and extracting required information
+ filtered_result = [
+ {
+ key: conversation[key]
+ for key in ("id", "name", "created", "num_members")
+ }
+ for conversation in conversations
+ if all(
+ key in conversation
+ for key in ("id", "name", "created", "num_members")
+ )
+ ]
+ return json.dumps(filtered_result, ensure_ascii=False)
+ except SlackApiError as e:
+ return f"Error creating conversation: {e.response['error']}"
+
+
+def get_slack_channel_message(channel_id: str) -> str:
+ r"""Retrieve messages from a Slack channel.
+
+ Args:
+ channel_id (str): The ID of the Slack channel to retrieve messages
+ from.
+
+ Returns:
+ str: JSON string containing filtered message data.
+
+ Raises:
+ SlackApiError: If there is an error during get slack channel message.
+ """
+ try:
+ slack_client = _login_slack()
+ result = slack_client.conversations_history(channel=channel_id)
+ messages = result["messages"]
+ filtered_messages = [
+ {key: message[key] for key in ("user", "text", "ts")}
+ for message in messages
+ if all(key in message for key in ("user", "text", "ts"))
+ ]
+ return json.dumps(filtered_messages, ensure_ascii=False)
+ except SlackApiError as e:
+ return f"Error retrieving messages: {e.response['error']}"
+
+
+def send_slack_message(
+ message: str,
+ channel_id: str,
+ user: Optional[str] = None,
+) -> str:
+ r"""Send a message to a Slack channel.
+
+ Args:
+ message (str): The message to send.
+ channel_id (str): The ID of the Slack channel to send message.
+ user (Optional[str]): The user ID of the recipient. Defaults to `None`.
+
+ Returns:
+ str: A confirmation message indicating whether the message was sent
+ successfully or an error message.
+
+ Raises:
+ SlackApiError: If an error occurs while sending the message.
+ """
+ try:
+ slack_client = _login_slack()
+ if user:
+ response = slack_client.chat_postEphemeral(
+ channel=channel_id, text=message, user=user
+ )
+ else:
+ response = slack_client.chat_postMessage(
+ channel=channel_id, text=message
+ )
+ return str(response)
+ except SlackApiError as e:
+ return f"Error creating conversation: {e.response['error']}"
+
+
+def delete_slack_message(
+ time_stamp: str,
+ channel_id: str,
+) -> str:
+ r"""Delete a message to a Slack channel.
+
+ Args:
+ time_stamp (str): Timestamp of the message to be deleted.
+ channel_id (str): The ID of the Slack channel to delete message.
+
+ Returns:
+ str: A confirmation message indicating whether the message was delete
+ successfully or an error message.
+
+ Raises:
+ SlackApiError: If an error occurs while sending the message.
+ """
+ try:
+ slack_client = _login_slack()
+ response = slack_client.chat_delete(channel=channel_id, ts=time_stamp)
+ return str(response)
+ except SlackApiError as e:
+ return f"Error creating conversation: {e.response['error']}"
+
+
+SLACK_FUNCS: List[OpenAIFunction] = [
+ OpenAIFunction(func) # type: ignore[arg-type]
+ for func in [
+ create_slack_channel,
+ join_slack_channel,
+ leave_slack_channel,
+ get_slack_channel_information,
+ get_slack_channel_message,
+ send_slack_message,
+ delete_slack_message,
+ ]
+]
diff --git a/poetry.lock b/poetry.lock
index 604e8bea5..e0b3ebd7f 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -5369,6 +5369,20 @@ files = [
{file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"},
]
+[[package]]
+name = "slack-sdk"
+version = "3.27.2"
+description = "The Slack API Platform SDK for Python"
+optional = true
+python-versions = ">=3.6"
+files = [
+ {file = "slack_sdk-3.27.2-py2.py3-none-any.whl", hash = "sha256:af97158e6ac7f667e158e8036e63dc1f79db9bd36216a33c10fcc49be7c2f30c"},
+ {file = "slack_sdk-3.27.2.tar.gz", hash = "sha256:bb145bf2bd93b60a17cd55c05cb15868c9a07d845b6fb608c798b50bce21cb99"},
+]
+
+[package.extras]
+optional = ["SQLAlchemy (>=1.4,<3)", "aiodns (>1.0)", "aiohttp (>=3.7.3,<4)", "boto3 (<=2)", "websocket-client (>=1,<2)", "websockets (>=9.1,<13)"]
+
[[package]]
name = "sniffio"
version = "1.3.1"
@@ -7062,16 +7076,16 @@ docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.link
testing = ["big-O", "jaraco.functools", "jaraco.itertools", "jaraco.test", "more-itertools", "pytest (>=6,!=8.1.*)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-ignore-flaky", "pytest-mypy", "pytest-ruff (>=0.2.1)"]
[extras]
-all = ["PyMuPDF", "accelerate", "beautifulsoup4", "cohere", "datasets", "diffusers", "docx2txt", "googlemaps", "neo4j", "openapi-spec-validator", "opencv-python", "prance", "pydub", "pygithub", "pymilvus", "pyowm", "qdrant-client", "rank-bm25", "requests_oauthlib", "sentence-transformers", "sentencepiece", "soundfile", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]
+all = ["PyMuPDF", "accelerate", "beautifulsoup4", "cohere", "datasets", "diffusers", "docx2txt", "googlemaps", "neo4j", "openapi-spec-validator", "opencv-python", "prance", "pydub", "pygithub", "pymilvus", "pyowm", "qdrant-client", "rank-bm25", "requests_oauthlib", "sentence-transformers", "sentencepiece", "slack-sdk", "soundfile", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]
encoders = ["sentence-transformers"]
graph-storages = ["neo4j"]
huggingface-agent = ["accelerate", "datasets", "diffusers", "opencv-python", "sentencepiece", "soundfile", "torch", "transformers"]
retrievers = ["cohere", "rank-bm25"]
test = ["mock", "pytest"]
-tools = ["PyMuPDF", "beautifulsoup4", "docx2txt", "googlemaps", "openapi-spec-validator", "prance", "pydub", "pygithub", "pyowm", "requests_oauthlib", "unstructured", "wikipedia", "wolframalpha"]
+tools = ["PyMuPDF", "beautifulsoup4", "docx2txt", "googlemaps", "openapi-spec-validator", "prance", "pydub", "pygithub", "pyowm", "requests_oauthlib", "slack-sdk", "unstructured", "wikipedia", "wolframalpha"]
vector-databases = ["pymilvus", "qdrant-client"]
[metadata]
lock-version = "2.0"
python-versions = ">=3.8.1,<3.12"
-content-hash = "8de82f2fd542a53ff7185ddaaf92f33a227971118c18b7d281d9aff9dbcf2250"
+content-hash = "4e22773023f79ee56f30597046ad95cc5b87d3e1a27b3e7b99ba79e7622f0723"
diff --git a/pyproject.toml b/pyproject.toml
index 72994b9eb..811917585 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -61,6 +61,7 @@ requests_oauthlib = { version = "^1.3.1", optional = true }
prance = { version = "^23.6.21.0", optional = true }
openapi-spec-validator = { version = "^0.7.1", optional = true }
unstructured = { extras = ["all-docs"], version = "^0.10.30", optional = true }
+slack-sdk = { version = "^3.27.2", optional = true }
pydub = { version = "^0.25.1", optional = true }
pygithub = { version = "^2.3.0", optional = true }
@@ -113,6 +114,7 @@ tools = [
"prance",
"openapi-spec-validator",
"unstructured",
+ "slack-sdk",
"pydub",
"pygithub",
]
@@ -154,6 +156,7 @@ all = [
"prance",
"openapi-spec-validator",
"unstructured",
+ "slack-sdk",
"pydub",
# vector-database
"qdrant-client",
@@ -273,6 +276,7 @@ module = [
"cohere",
"sentence_transformers.*",
"pymilvus",
+ "slack-sdk",
"pydub",
"pygithub"
]
diff --git a/test/functions/test_slack_functions.py b/test/functions/test_slack_functions.py
new file mode 100644
index 000000000..333ed5185
--- /dev/null
+++ b/test/functions/test_slack_functions.py
@@ -0,0 +1,119 @@
+# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+# Licensed under the Apache License, Version 2.0 (the ā€œLicenseā€);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an ā€œAS ISā€ BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+from unittest.mock import MagicMock, patch
+
+from camel.functions.slack_functions import (
+ create_slack_channel,
+ delete_slack_message,
+ get_slack_channel_information,
+ get_slack_channel_message,
+ join_slack_channel,
+ leave_slack_channel,
+ send_slack_message,
+)
+
+
+def test_create_slack_channel():
+ with patch(
+ 'camel.functions.slack_functions._login_slack'
+ ) as mock_login_slack:
+ mock_client = MagicMock()
+ mock_login_slack.return_value = mock_client
+
+ mock_response = {'channel': {'id': 'fake_channel_id'}}
+ mock_client.conversations_create.return_value = mock_response
+ mock_client.conversations_archive.return_value = {
+ 'fake_response_key': 'fake_response_value'
+ }
+
+ result = create_slack_channel('test_channel', is_private=True)
+
+ assert result == "{'fake_response_key': 'fake_response_value'}"
+ mock_client.conversations_create.assert_called_once_with(
+ name='test_channel', is_private=True
+ )
+ mock_client.conversations_archive.assert_called_once_with(
+ channel='fake_channel_id'
+ )
+
+
+def test_join_slack_channel():
+ with patch("camel.functions.slack_functions._login_slack") as mock_login:
+ mock_client = MagicMock()
+ mock_login.return_value = mock_client
+ mock_client.conversations_join.return_value = {}
+ response = join_slack_channel("123")
+ assert response == "{}"
+
+
+def test_leave_slack_channel():
+ with patch("camel.functions.slack_functions._login_slack") as mock_login:
+ mock_client = MagicMock()
+ mock_login.return_value = mock_client
+ mock_client.conversations_leave.return_value = {}
+ response = leave_slack_channel("123")
+ assert response == "{}"
+
+
+def test_get_slack_channel_information():
+ with patch("camel.functions.slack_functions._login_slack") as mock_login:
+ mock_client = MagicMock()
+ mock_login.return_value = mock_client
+ mock_client.conversations_list.return_value = {
+ "channels": [
+ {
+ "id": "123",
+ "name": "test_channel",
+ "created": 123,
+ "num_members": 5,
+ }
+ ]
+ }
+ response = get_slack_channel_information()
+ expected_result = '[{"id": "123", "name": "test_channel", "created": 123, "num_members": 5}]'
+ assert response == expected_result
+
+
+def test_get_slack_channel_message():
+ with patch("camel.functions.slack_functions._login_slack") as mock_login:
+ mock_client = MagicMock()
+ mock_login.return_value = mock_client
+ mock_client.conversations_history.return_value = {
+ "messages": [
+ {"user": "user_id", "text": "test_message", "ts": "123"}
+ ]
+ }
+ response = get_slack_channel_message("123")
+ expected_result = (
+ '[{"user": "user_id", "text": "test_message", "ts": "123"}]'
+ )
+ assert response == expected_result
+
+
+def test_send_slack_message():
+ with patch("camel.functions.slack_functions._login_slack") as mock_login:
+ mock_client = MagicMock()
+ mock_login.return_value = mock_client
+ mock_client.chat_postMessage.return_value = {}
+ response = send_slack_message("test_message", "123")
+ assert response == "{}"
+
+
+def test_delete_slack_message():
+ with patch("camel.functions.slack_functions._login_slack") as mock_login:
+ mock_client = MagicMock()
+ mock_login.return_value = mock_client
+ mock_client.chat_delete.return_value = {}
+ response = delete_slack_message("123", "123")
+ assert response == "{}"