From b7b5556013d58a317a588c3989aaf68da3284420 Mon Sep 17 00:00:00 2001 From: Kye Gomez Date: Thu, 16 Jan 2025 00:43:05 -0500 Subject: [PATCH] [README] --- .env.example | 3 +- README.md | 172 +++++++++++++++++++++- swarms_tools/social_media/__init__.py | 0 swarms_tools/social_media/telegram_api.py | 168 +++++++++++++++++++++ swarms_tools/social_media/twitter.py | 0 5 files changed, 339 insertions(+), 4 deletions(-) create mode 100644 swarms_tools/social_media/__init__.py create mode 100644 swarms_tools/social_media/telegram_api.py create mode 100644 swarms_tools/social_media/twitter.py diff --git a/.env.example b/.env.example index d5dcdad..4d721f6 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,3 @@ EODHD_API_KEY="" -COINMARKETCAP_API_KEY="" \ No newline at end of file +COINMARKETCAP_API_KEY="" +TELEGRAM_API_KEY="" \ No newline at end of file diff --git a/README.md b/README.md index b7c3fe4..6cb677f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,176 @@ -# swarm tools +# Swarms Tools [![Join our Discord](https://img.shields.io/badge/Discord-Join%20our%20server-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/agora-999382051935506503) [![Subscribe on YouTube](https://img.shields.io/badge/YouTube-Subscribe-red?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@kyegomez3242) [![Connect on LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/kye-g-38759a207/) [![Follow on X.com](https://img.shields.io/badge/X.com-Follow-1DA1F2?style=for-the-badge&logo=x&logoColor=white)](https://x.com/kyegomezb) -## Install + +![Swarms Tools Banner](https://user-images.githubusercontent.com/banner_placeholder) + +Welcome to **Swarms Tools**, the ultimate package for integrating **cutting-edge APIs** into Python functions with seamless multi-agent system compatibility. Designed for enterprises at the forefront of innovation, **Swarms Tools** is your key to simplifying complexity and unlocking operational excellence. + +--- + +## 🌌 Vision + +At Swarms Corporation, we envision a world where **intelligent agents collaborate autonomously** to advance humanity. **Swarms Tools** delivers the building blocks for an interconnected, automated, and infinitely scalable future. Join us as we pioneer the tools of tomorrow, today. + +--- + +## 🚀 Features + +- **Unified API Integration**: Ready-to-use Python functions for financial data, social media, IoT, and more. +- **Enterprise-Grade Design**: Comprehensive type hints, structured outputs, and robust documentation. +- **Agent-Ready Framework**: Optimized for seamless integration into Swarms' multi-agent orchestration systems. +- **Expandable Architecture**: Easily extend functionality with a standardized schema for new tools. + +--- + +## 🔧 Installation ```bash pip3 install -U swarms-tools -``` \ No newline at end of file +``` + +--- + +## 📂 Directory Structure + +```plaintext +swarms-tools/ +├── swarms_tools/ +│ ├── financial_data/ +│ │ ├── htx_tool.py +│ │ ├── eodh_api.py +│ │ └── coingecko_tool.py +│ ├── social_media/ +│ │ ├── telegram_tool.py +│ ├── utilities/ +│ │ └── logging.py +├── tests/ +│ ├── test_financial_data.py +│ └── test_social_media.py +└── README.md +``` + +--- + +## 💼 Use Cases + +### Financial Data Retrieval +Enable precise and actionable financial insights: + +#### Example 1: Fetch Historical Data +```python +from swarms_tools.financial_data.htx_tool import fetch_htx_data + +# Fetch historical trading data for "Swarms Corporation" +response = fetch_htx_data("swarms") +print(response) +``` + +#### Example 2: Stock News Analysis +```python +from swarms_tools.financial_data.eodh_api import fetch_stock_news + +# Retrieve latest stock news for Apple +news = fetch_stock_news("AAPL") +print(news) +``` + +#### Example 3: Cryptocurrency Metrics +```python +from swarms_tools.financial_data.coingecko_tool import coin_gecko_coin_api + +# Fetch live data for Bitcoin +crypto_data = coin_gecko_coin_api("bitcoin") +print(crypto_data) +``` + +### Social Media Automation +Streamline communication and engagement: + +#### Example: Telegram Bot Messaging +```python +from swarms_tools.social_media.telegram_tool import telegram_dm_or_tag_api + +def send_alert(response: str): + telegram_dm_or_tag_api(response) + +# Send a message to a user or group +send_alert("Mission-critical update from Swarms.") +``` + +--- + +## 🧩 Standardized Schema + +Every tool in **Swarms Tools** adheres to a strict schema for maintainability and interoperability: + +### Schema Template + +1. **Functionality**: + - Encapsulate API logic into a modular, reusable function. + +2. **Typing**: + - Leverage Python type hints for input validation and clarity. + + Example: + ```python + def fetch_data(symbol: str, date_range: str) -> str: + """ + Fetch financial data for a given symbol and date range. + + Args: + symbol (str): Ticker symbol of the asset. + date_range (str): Timeframe for the data (e.g., '1d', '1m', '1y'). + + Returns: + dict: A dictionary containing financial metrics. + """ + pass + ``` + +3. **Documentation**: + - Include detailed docstrings with parameter explanations and usage examples. + +4. **Output Standardization**: + - Ensure consistent outputs (e.g., strings) for easy downstream agent integration. + + +--- + +## 📖 Documentation + +Comprehensive documentation is available to guide developers and enterprises. Visit our [official docs](https://docs.swarms.world) for detailed API references, usage examples, and best practices. + +--- + +## 🛠 Contributing + +We welcome contributions from the global developer community. To contribute: + +1. **Fork the Repository**: Start by forking the repository. +2. **Create a Feature Branch**: Use a descriptive branch name: `feature/add-new-tool`. +3. **Commit Your Changes**: Write meaningful commit messages. +4. **Submit a Pull Request**: Open a pull request for review. + +--- + +## 🛡️ License + +This project is licensed under the **MIT License**. See the [LICENSE](LICENSE) file for details. + +--- + +## 🌠 Join the Future + +Explore the limitless possibilities of agent-based systems. Together, we can build a smarter, faster, and more interconnected world. + +**Visit us:** [Swarms Corporation](https://swarms.ai) +**Follow us:** [Twitter](https://twitter.com/swarms_corp) + +--- + +**"The future belongs to those who dare to automate it."** +**— The Swarms Corporation** + diff --git a/swarms_tools/social_media/__init__.py b/swarms_tools/social_media/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/swarms_tools/social_media/telegram_api.py b/swarms_tools/social_media/telegram_api.py new file mode 100644 index 0000000..a900c9a --- /dev/null +++ b/swarms_tools/social_media/telegram_api.py @@ -0,0 +1,168 @@ +import os +import sys +import subprocess + +from loguru import logger + +try: + from telegram import Update + from telegram.ext import ( + ApplicationBuilder, + CommandHandler, + ContextTypes, + MessageHandler, + filters, + ) +except ImportError as error: + logger.error( + f"Telegram API not installed {error}. Attempting to install..." + ) + subprocess.run( + [ + sys.executable, + "-m", + "pip", + "install", + "python-telegram-bot", + ], + check=True, + ) + logger.info("Telegram API installed successfully.") + + +def check_mention(update: Update) -> bool: + """Check if the bot was mentioned in the message""" + message = update.message + bot_username = update.get_bot().username + + # Check for @mentions + if message.entities: + for entity in message.entities: + if entity.type == "mention": + mention = message.text[ + entity.offset : entity.offset + entity.length + ] + if mention.lower() == f"@{bot_username.lower()}": + return True + + # Check for text_mentions + if message.entities: + for entity in message.entities: + if entity.type == "text_mention" and entity.user.is_bot: + if ( + entity.user.username.lower() + == bot_username.lower() + ): + return True + + return False + + +async def process_message(update: Update) -> str: + """Clean up message by removing bot mention""" + message = update.message.text + bot_username = update.get_bot().username + + # Remove @username + cleaned_message = message.replace(f"@{bot_username}", "").strip() + + # If the message starts with the bot's username without @, remove it too + if cleaned_message.lower().startswith(bot_username.lower()): + cleaned_message = cleaned_message[len(bot_username) :].strip() + + return cleaned_message + + +async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Handle /start command - only works in DMs""" + if update.message.chat.type != "private": + return + + welcome_message = "👋 Hello! I am your medical coding assistant bot. Send me any medical coding question!" + await update.message.reply_text(welcome_message) + logger.info(f"Start command from user {update.effective_user.id}") + + +async def help(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Handle /help command - only works in DMs""" + if update.message.chat.type != "private": + return + + help_message = ( + "Just send me any medical coding question and I'll help you!\n" + "Commands:\n" + "/start - Start the bot\n" + "/help - Show this help message\n\n" + "In groups, tag me with @botname to get my attention!" + ) + await update.message.reply_text(help_message) + logger.info(f"Help command from user {update.effective_user.id}") + + +async def handle_message( + update: Update, + context: ContextTypes.DEFAULT_TYPE, + response: str = None, +): + """Handle incoming messages - works in DMs and when mentioned in groups""" + # Check if it's a DM or mention + if update.message.chat.type != "private" and not check_mention( + update + ): + return + + user_id = update.effective_user.id + logger.info( + f"Message received from {user_id} in {update.message.chat.type} chat" + ) + + try: + # Clean up the message + cleaned_message = await process_message(update) + if not cleaned_message: + return + + # Send response + await update.message.reply_text(response) + logger.info(f"Sent response to user {user_id}") + + except Exception as e: + logger.error( + f"Error processing message: {str(e)}", exc_info=True + ) + await update.message.reply_text( + "Sorry, I encountered an error while processing your request. Please try again." + ) + + +def telegram_dm_or_tag_api(response: str): + # Get token from environment variable + token = os.getenv("TELEGRAM_KEY") + if not token: + logger.error( + "TELEGRAM_KEY not found in environment variables" + ) + sys.exit(1) + + try: + # Create application + application = ApplicationBuilder().token(token).build() + + # Add handlers + application.add_handler(CommandHandler("start", start)) + application.add_handler(CommandHandler("help", help)) + application.add_handler( + MessageHandler( + filters.TEXT & ~filters.COMMAND, + response, + handle_message, + ) + ) + + # Run the bot + logger.info("Bot started successfully") + application.run_polling(allowed_updates=Update.ALL_TYPES) + + except Exception as e: + logger.error(f"Critical error: {str(e)}", exc_info=True) + sys.exit(1) diff --git a/swarms_tools/social_media/twitter.py b/swarms_tools/social_media/twitter.py new file mode 100644 index 0000000..e69de29