Metadata-Version: 2.4
Name: pyalerts
Version: 0.1.0
Summary: Pyalerts is a lightweight, extensible Python alerting library
Author-email: Vivek <vivek16903@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/yourusername/pyalerts
Project-URL: Bug Tracker, https://github.com/yourusername/pyalerts/issues
Keywords: alerts,notifications,email,sms,push,logging,monitoring
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Intended Audience :: Developers
Classifier: Topic :: Communications :: Email
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: sendgrid
Requires-Dist: sendgrid>=6.0; extra == "sendgrid"
Provides-Extra: sms
Requires-Dist: twilio>=8.0; extra == "sms"
Provides-Extra: push
Requires-Dist: requests>=2.28; extra == "push"
Provides-Extra: all
Requires-Dist: sendgrid>=6.0; extra == "all"
Requires-Dist: twilio>=8.0; extra == "all"
Requires-Dist: requests>=2.28; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Dynamic: license-file

# pyalerts

A lightweight, extensible alerting and logging integration library for Python. Configure your channels (Email, SMS, Push notifications) and plug it directly into Python's standard `logging` library or dispatch alerts standalone.

---

## 📦 Installation

```bash
# Base install (Email via SMTP — zero external dependencies)
pip install pyalerts

# With SendGrid email support
pip install pyalerts[sendgrid]

# With SMS support (Twilio)
pip install pyalerts[sms]

# With push notifications support (Pushover)
pip install pyalerts[push]

# Install all channels & dependencies
pip install pyalerts[all]
```

---

## 🚀 Recommended: Standard Python Logger Integration

Use `AlertHandler` to plug `pyalerts` directly into Python's standard `logging` library. Any `logger.error()` or `logger.critical()` call across your entire application will automatically dispatch alerts!

```python
import logging
from pyalerts import AlertManager, AlertConfig, SmtpAlertService, AlertHandler

# 1. Configure alert credentials
config = AlertConfig(
    smtp_host="smtp.gmail.com",
    smtp_port=587,
    sender_email="alerts@mycompany.com",
    sender_password="your-gmail-app-password",
    recipients=["devops@mycompany.com", "oncall@mycompany.com"],
    max_retries=3,               # retry failed sends up to 3 times
    rate_limit_per_minute=10,    # avoid alert storms
)

# 2. Setup AlertManager and add channels
manager = AlertManager(config)
manager.add_service(SmtpAlertService())

# 3. Attach handler to Python's root logger (captures all loggers in your app)
logging.getLogger().addHandler(
    AlertHandler(
        manager,
        level=logging.ERROR,            # only ERROR & CRITICAL trigger alerts
        subject_prefix="[Production]",  # optional prefix in alert subject
        include_traceback=True,         # attach stack trace automatically
    )
)

# 4. Use standard Python logging anywhere in your codebase
logger = logging.getLogger(__name__)

logger.info("Server started on port 8080")       # Normal log, no alert
logger.warning("Cache miss spike detected")     # Normal log, no alert

try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Fatal calculation error") # 🚨 Fires alert with full stack trace!
```

---

## 📢 Multi-Channel Setup (Email + SMS + Push)

You can register multiple channels in the `AlertManager`. When an alert is triggered, it fans out to all channels simultaneously:

```python
from pyalerts import AlertManager, AlertConfig, SmtpAlertService
from pyalerts.services import SmsAlertService, PushAlertService

config = AlertConfig(
    # Email
    sender_email="me@gmail.com",
    sender_password="app-password",
    recipients=["admin@company.com"],
    # Twilio SMS
    twilio_account_sid="ACxxxxxxxxxxxxxxxx",
    twilio_auth_token="your-auth-token",
    sms_from="+14155552671",
    sms_to=["+919876543210"],
    # Pushover Push Notification
    pushover_api_token="your-app-token",
    pushover_user_key="your-user-key",
)

manager = (
    AlertManager(config)
    .add_service(SmtpAlertService())
    .add_service(SmsAlertService())    # pip install pyalerts[sms]
    .add_service(PushAlertService())   # pip install pyalerts[push]
)
```

---

## ⚡ Standalone / Direct Alerts

If you don't want to use Python's `logging` module, you can send alerts directly:

```python
# Synchronous
result = manager.alert("🚨 Database Down", "Failed to connect to postgres-01")
print(result)  # {'SmtpAlertService': True, 'SmsAlertService': True}

# Asynchronous (e.g. FastAPI / asyncio)
result = await manager.alert_async("🚨 Database Down", "Failed to connect to postgres-01")
```

### Dynamic Message Templating

```python
result = manager.alert(
    subject="🚨 Incident in {service}",
    message="Service {service} failed in {environment}. Details: {error}",
    template_vars={
        "service": "billing-service",
        "environment": "production",
        "error": "Payment gateway 504 Gateway Timeout",
    },
)
```

---

## 🔌 Creating Custom Alert Channels

Implementing a new channel (Slack, Discord, Microsoft Teams, Webhook, etc.) takes just a few lines by subclassing `IAlertService`:

```python
import requests
from pyalerts import IAlertService, AlertConfig

class SlackAlertService(IAlertService):
    def send(self, subject: str, message: str, config: AlertConfig) -> bool:
        # Add your custom sending logic here
        webhook_url = "https://hooks.slack.com/services/xxx/yyy/zzz"
        payload = {"text": f"*{subject}*\n```{message}```"}
        response = requests.post(webhook_url, json=payload, timeout=10)
        return response.status_code == 200

# Register your custom service:
manager.add_service(SlackAlertService())
```

---

## 🧪 Testing

Run the test suite with pytest:

```bash
pytest tests/ -v
```

---

## 📄 License

MIT
