š« CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: Telegram bot (#608)
Ruslan Serebriakov27cfb19354bc
diff --git a/camel/bots/__init__.py b/camel/bots/__init__.pyindex 0a95ed0d0..4bca8342b 100644--- a/camel/bots/__init__.py+++ b/camel/bots/__init__.py@@ -11,9 +11,10 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========-from .discord_bot import DiscordBot+from .telegram_bot import TelegramBot__all__ = ['DiscordBot',+ 'TelegramBot',]diff --git a/camel/bots/telegram_bot.py b/camel/bots/telegram_bot.pynew file mode 100644index 000000000..374afd97b--- /dev/null+++ b/camel/bots/telegram_bot.py@@ -0,0 +1,84 @@+# =========== 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. ===========+import os+from typing import TYPE_CHECKING, Optional++from camel.agents import ChatAgent+from camel.messages import BaseMessage++# Conditionally import telebot types only for type checking+if TYPE_CHECKING:+ from telebot.types import Message # type: ignore[import-untyped]+++class TelegramBot:+ r"""Represents a Telegram bot that is powered by an agent.++ Attributes:+ chat_agent (ChatAgent): Chat agent that will power the bot.+ telegram_token (str, optional): The bot token.+ """++ def __init__(+ self,+ chat_agent: ChatAgent,+ telegram_token: Optional[str] = None,+ ) -> None:+ self.chat_agent = chat_agent++ if not telegram_token:+ self.token = os.getenv('TELEGRAM_TOKEN')+ if not self.token:+ raise ValueError(+ "`TELEGRAM_TOKEN` not found in environment variables. "+ "Get it from t.me/BotFather."+ )+ else:+ self.token = telegram_token++ try:+ import telebot # type: ignore[import-untyped]+ except ImportError:+ raise ImportError(+ "Please install `telegram_bot` first. "+ "You can install it by running "+ "`pip install pyTelegramBotAPI`."+ )+ self.bot = telebot.TeleBot(token=self.token)++ # Register the message handler within the constructor+ self.bot.message_handler(func=lambda message: True)(self.on_message)++ def run(self) -> None:+ r"""Start the Telegram bot."""+ print("Telegram bot is running...")+ self.bot.infinity_polling()++ def on_message(self, message: 'Message') -> None:+ r"""Handles incoming messages from the user.++ Args:+ message (types.Message): The incoming message object.+ """+ self.chat_agent.reset()++ if not message.text:+ return++ user_msg = BaseMessage.make_user_message(+ role_name="User", content=message.text+ )+ assistant_response = self.chat_agent.step(user_msg)++ self.bot.reply_to(message, assistant_response.msg.content)diff --git a/examples/bots/telegram_bot_example.py b/examples/bots/telegram_bot_example.pynew file mode 100644index 000000000..da7d45940--- /dev/null+++ b/examples/bots/telegram_bot_example.py@@ -0,0 +1,32 @@+# =========== 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 camel.agents import ChatAgent+from camel.bots.telegram_bot import TelegramBot+from camel.messages import BaseMessage+++def main(model=None) -> None:+ assistant_sys_msg = BaseMessage.make_assistant_message(+ role_name="Assistant",+ content="You are a helpful assistant.",+ )++ agent = ChatAgent(assistant_sys_msg, model_type=model)+ bot = TelegramBot(agent)+ bot.run()+++if __name__ == "__main__":+ main()diff --git a/poetry.lock b/poetry.lockindex cc2b46684..bd09a9eca 100644--- a/poetry.lock+++ b/poetry.lock@@ -956,18 +956,18 @@ dev = ["PyTest", "PyTest-Cov", "bump2version (<1)", "sphinx (<2)", "tox"][[package]]name = "diffusers"-version = "0.28.2"+version = "0.29.0"description = "State-of-the-art diffusion in PyTorch and JAX."optional = truepython-versions = ">=3.8.0"files = [- {file = "diffusers-0.28.2-py3-none-any.whl", hash = "sha256:9713b7666510723ad6b7e8f4702664ef20c59e4bc241d26c7ca086be3041082e"},- {file = "diffusers-0.28.2.tar.gz", hash = "sha256:0e1e881c821bd6dc2d88252a228a2532ae3577eb4f8b351c9c4abb184aee9b3f"},+ {file = "diffusers-0.29.0-py3-none-any.whl", hash = "sha256:4c194d2379644a0f7ef9b4ff12c8cf5de4c6324e811265754f08e2f839b8cedb"},+ {file = "diffusers-0.29.0.tar.gz", hash = "sha256:0212030a8fabe7a07d1c8e925ccdf7a529a98b0425fa078900a679b2451a8ac2"},][package.dependencies]filelock = "*"-huggingface-hub = ">=0.20.2"+huggingface-hub = ">=0.23.2"importlib-metadata = "*"numpy = "*"Pillow = "*"@@ -1339,18 +1339,18 @@ files = [[[package]]name = "filelock"-version = "3.14.0"+version = "3.15.1"description = "A platform independent file lock."optional = falsepython-versions = ">=3.8"files = [- {file = "filelock-3.14.0-py3-none-any.whl", hash = "sha256:43339835842f110ca7ae60f1e1c160714c5a6afd15a2873419ab185334975c0f"},- {file = "filelock-3.14.0.tar.gz", hash = "sha256:6ea72da3be9b8c82afd3edcf99f2fffbb5076335a5ae4d03248bb5b6c3eae78a"},+ {file = "filelock-3.15.1-py3-none-any.whl", hash = "sha256:71b3102950e91dfc1bb4209b64be4dc8854f40e5f534428d8684f953ac847fac"},+ {file = "filelock-3.15.1.tar.gz", hash = "sha256:58a2549afdf9e02e10720eaa4d4470f56386d7a6f72edd7d0596337af8ed7ad8"},][package.extras]docs = ["furo (>=2023.9.10)", "sphinx (>=7.2.6)", "sphinx-autodoc-typehints (>=1.25.2)"]-testing = ["covdefaults (>=2.3)", "coverage (>=7.3.2)", "diff-cover (>=8.0.1)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)", "pytest-timeout (>=2.2)"]+testing = ["covdefaults (>=2.3)", "coverage (>=7.3.2)", "diff-cover (>=8.0.1)", "pytest (>=7.4.3)", "pytest-asyncio (>=0.21)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)", "pytest-timeout (>=2.2)"]typing = ["typing-extensions (>=4.8)"][[package]]@@ -2470,9 +2470,13 @@ files = [{file = "lxml-5.2.2-cp36-cp36m-win_amd64.whl", hash = "sha256:edcfa83e03370032a489430215c1e7783128808fd3e2e0a3225deee278585196"},{file = "lxml-5.2.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:28bf95177400066596cdbcfc933312493799382879da504633d16cf60bba735b"},{file = "lxml-5.2.2-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3a745cc98d504d5bd2c19b10c79c61c7c3df9222629f1b6210c0368177589fb8"},+ {file = "lxml-5.2.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b590b39ef90c6b22ec0be925b211298e810b4856909c8ca60d27ffbca6c12e6"},{file = "lxml-5.2.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b336b0416828022bfd5a2e3083e7f5ba54b96242159f83c7e3eebaec752f1716"},+ {file = "lxml-5.2.2-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:c2faf60c583af0d135e853c86ac2735ce178f0e338a3c7f9ae8f622fd2eb788c"},{file = "lxml-5.2.2-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:4bc6cb140a7a0ad1f7bc37e018d0ed690b7b6520ade518285dc3171f7a117905"},+ {file = "lxml-5.2.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:7ff762670cada8e05b32bf1e4dc50b140790909caa8303cfddc4d702b71ea184"},{file = "lxml-5.2.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:57f0a0bbc9868e10ebe874e9f129d2917750adf008fe7b9c1598c0fbbfdde6a6"},+ {file = "lxml-5.2.2-cp37-cp37m-musllinux_1_2_aarch64.whl", hash = "sha256:a6d2092797b388342c1bc932077ad232f914351932353e2e8706851c870bca1f"},{file = "lxml-5.2.2-cp37-cp37m-musllinux_1_2_x86_64.whl", hash = "sha256:60499fe961b21264e17a471ec296dcbf4365fbea611bf9e303ab69db7159ce61"},{file = "lxml-5.2.2-cp37-cp37m-win32.whl", hash = "sha256:d9b342c76003c6b9336a80efcc766748a333573abf9350f4094ee46b006ec18f"},{file = "lxml-5.2.2-cp37-cp37m-win_amd64.whl", hash = "sha256:b16db2770517b8799c79aa80f4053cd6f8b716f21f8aca962725a9565ce3ee40"},@@ -3337,13 +3341,13 @@ sympy = "*"[[package]]name = "openai"-version = "1.33.0"+version = "1.34.0"description = "The official Python library for the openai API"optional = falsepython-versions = ">=3.7.1"files = [- {file = "openai-1.33.0-py3-none-any.whl", hash = "sha256:621163b56570897ab8389d187f686a53d4771fd6ce95d481c0a9611fe8bc4229"},- {file = "openai-1.33.0.tar.gz", hash = "sha256:1169211a7b326ecbc821cafb427c29bfd0871f9a3e0947dd9e51acb3b0f1df78"},+ {file = "openai-1.34.0-py3-none-any.whl", hash = "sha256:018623c2f795424044675c6230fa3bfbf98d9e0aab45d8fd116f2efb2cfb6b7e"},+ {file = "openai-1.34.0.tar.gz", hash = "sha256:95c8e2da4acd6958e626186957d656597613587195abd0fb2527566a93e76770"},][package.dependencies]@@ -3420,13 +3424,13 @@ numpy = [[[package]]name = "openpyxl"-version = "3.1.3"+version = "3.1.4"description = "A Python library to read/write Excel 2010 xlsx/xlsm files"optional = true-python-versions = ">=3.6"+python-versions = ">=3.8"files = [- {file = "openpyxl-3.1.3-py2.py3-none-any.whl", hash = "sha256:25071b558db709de9e8782c3d3e058af3b23ffb2fc6f40c8f0c45a154eced2c3"},- {file = "openpyxl-3.1.3.tar.gz", hash = "sha256:8dd482e5350125b2388070bb2477927be2e8ebc27df61178709bc8c8751da2f9"},+ {file = "openpyxl-3.1.4-py2.py3-none-any.whl", hash = "sha256:ec17f6483f2b8f7c88c57e5e5d3b0de0e3fb9ac70edc084d28e864f5b33bbefd"},+ {file = "openpyxl-3.1.4.tar.gz", hash = "sha256:8d2c8adf5d20d6ce8f9bca381df86b534835e974ed0156dacefa76f68c1d69fb"},][package.dependencies]@@ -4429,6 +4433,32 @@ files = [{file = "PySocks-1.7.1.tar.gz", hash = "sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0"},]+[[package]]+name = "pytelegrambotapi"+version = "4.19.1"+description = "Python Telegram bot api."+optional = true+python-versions = ">=3.8"+files = [+ {file = "pytelegrambotapi-4.19.1-py3-none-any.whl", hash = "sha256:22b0835f06a79eea93cc2c29079e4bb10f706b282ae10a3e537557b4679b12f2"},+ {file = "pytelegrambotapi-4.19.1.tar.gz", hash = "sha256:cd5e5188a49f50a5c1fb1d8d195a852a05ae3525d21f26fbe8365cb408ee1342"},+]++[package.dependencies]+requests = "*"++[package.extras]+aiohttp = ["aiohttp"]+aioredis = ["aioredis"]+coloredlogs = ["coloredlogs"]+fastapi = ["fastapi"]+json = ["ujson"]+pil = ["pillow"]+psutil = ["psutil"]+redis = ["redis (>=3.4.1)"]+uvicorn = ["uvicorn"]+watchdog = ["watchdog"]+[[package]]name = "pytesseract"version = "0.3.10"@@ -7351,16 +7381,16 @@ doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linketest = ["big-O", "importlib-resources", "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", "discord.py", "docx2txt", "duckduckgo-search", "googlemaps", "neo4j", "newspaper3k", "openapi-spec-validator", "opencv-python", "pillow", "prance", "pydub", "pygithub", "pymilvus", "pyowm", "qdrant-client", "rank-bm25", "requests_oauthlib", "sentence-transformers", "sentencepiece", "slack-sdk", "soundfile", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]+all = ["PyMuPDF", "accelerate", "beautifulsoup4", "cohere", "datasets", "diffusers", "discord.py", "docx2txt", "duckduckgo-search", "googlemaps", "neo4j", "newspaper3k", "openapi-spec-validator", "opencv-python", "pillow", "prance", "pyTelegramBotAPI", "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", "pytest-asyncio"]-tools = ["PyMuPDF", "beautifulsoup4", "discord.py", "docx2txt", "duckduckgo-search", "googlemaps", "newspaper3k", "openapi-spec-validator", "pillow", "prance", "pydub", "pygithub", "pyowm", "requests_oauthlib", "slack-sdk", "unstructured", "wikipedia", "wolframalpha"]+tools = ["PyMuPDF", "beautifulsoup4", "discord.py", "docx2txt", "duckduckgo-search", "googlemaps", "newspaper3k", "openapi-spec-validator", "pillow", "prance", "pyTelegramBotAPI", "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 = "99d3e2383e7f5667a52a5c015ffbc9384be61fa73e0ea39fb2a788cc6ee2cf9e"+content-hash = "5509468c11a6c9f34eb104fac711c81cc22167e82ba8044ab4b65fe202f59d65"diff --git a/pyproject.toml b/pyproject.tomlindex 636e43d36..84e471eaf 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,6 +68,7 @@ pillow = { version = "^10.2.0", optional = true }slack-sdk = { version = "^3.27.2", optional = true }pydub = { version = "^0.25.1", optional = true }pygithub = { version = "^2.3.0", optional = true }+pyTelegramBotAPI = { version = "^4.18.0", optional = true }"discord.py" = { version = "^2.3.2", optional = true }# encoders@@ -126,6 +127,7 @@ tools = ["slack-sdk","pydub","pygithub",+ "pyTelegramBotAPI","discord.py",]@@ -157,6 +159,7 @@ all = ["beautifulsoup4","docx2txt","pygithub",+ "pyTelegramBotAPI","discord.py","PyMuPDF","wikipedia",@@ -303,6 +306,7 @@ module = ["slack-sdk","pydub","pygithub",+ "pyTelegramBotAPI","discord.py"]ignore_missing_imports = true\ No newline at end of filediff --git a/test/bots/test_telegram_bot.py b/test/bots/test_telegram_bot.pynew file mode 100644index 000000000..8a3901b9c--- /dev/null+++ b/test/bots/test_telegram_bot.py@@ -0,0 +1,75 @@+# =========== 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. ===========+import unittest+from unittest.mock import MagicMock, patch++from camel.agents import ChatAgent+from camel.bots.telegram_bot import TelegramBot+from camel.messages import BaseMessage+++class TestTelegramBot(unittest.TestCase):+ def setUp(self):+ self.chat_agent_mock = MagicMock(spec=ChatAgent)+ self.telegram_token = "fake_token"++ def test_init_token_provided_uses_provided_token(self):+ bot = TelegramBot(+ self.chat_agent_mock, telegram_token=self.telegram_token+ )+ self.assertEqual(bot.token, self.telegram_token)++ @patch('telebot.TeleBot')+ def test_on_message(self, mock_telebot):+ # Setup bot and mocks for message handling+ bot = TelegramBot(+ self.chat_agent_mock, telegram_token=self.telegram_token+ )+ mock_bot_instance = mock_telebot.return_value++ message_mock = MagicMock()+ message_mock.text = "Hello, world!"++ user_msg_mock = BaseMessage.make_user_message(+ "User", content="Hello, world!"+ )+ response_msg_mock = MagicMock(msg=MagicMock(content="Hello back!"))++ self.chat_agent_mock.reset = MagicMock()+ self.chat_agent_mock.step = MagicMock(return_value=response_msg_mock)++ # Test the message handling+ bot.on_message(message_mock)++ # Check if the chat agent's methods are called appropriately+ self.chat_agent_mock.reset.assert_called_once()+ self.chat_agent_mock.step.assert_called_once_with(user_msg_mock)++ # Check if the bot replies with the correct message+ mock_bot_instance.reply_to.assert_called_once_with(+ message_mock, "Hello back!"+ )++ @patch('telebot.TeleBot')+ def test_run_starts_polling(self, mock_telebot):+ bot = TelegramBot(+ self.chat_agent_mock, telegram_token=self.telegram_token+ )+ mock_bot_instance = mock_telebot.return_value+ bot.run()+ mock_bot_instance.infinity_polling.assert_called_once()+++if __name__ == '__main__':+ unittest.main()