Skip to content
Blog

Integrating Slack, Discord, and Telegram Webhooks as Agent Notification Tools

Equip your Google ADK agents with multi-channel outbound notification capabilities using Slack incoming webhooks, Discord embeds, and Telegram bot APIs.

Published on • November 29, 2026

AI Assistant

Autonomous AI agents frequently perform long-running background tasks, encounter critical human-in-the-loop approval thresholds, or detect anomalies that require immediate attention. Rather than requiring users to sit and watch an interactive chat terminal, modern agents notify their human teammates across team collaboration platforms: Slack, Discord, or Telegram.

In this tutorial, we will construct unified webhook notification tools in Google Agent Development Kit (ADK) that format and dispatch rich messages across all three platforms asynchronously.


1. Multi-Platform Webhook Anatomy

Each platform expects a distinct JSON structure:

  • Slack: Incoming Webhooks expect an object containing either plain text or structured blocks (Section, Header, Context, Actions).
  • Discord: Webhooks accept content and rich embeds with color accents, fields, and timestamps.
  • Telegram: Bot API (sendMessage) accepts chat_id, formatted text (MarkdownV2 or HTML), and inline keyboards.
+--------------------------------------------------------------+
|                         Google ADK Agent                     |
|  - Reasoning: "Analysis finished with 3 high-severity bugs"   |
|  - Tool Call: notify_team_channel(platform="slack", ...)     |
+--------------------------------------------------------------+
                                |
                                v
+--------------------------------------------------------------+
|                    Unified Webhook Tool                      |
|  - Payload Normalizer (Markdown -> Slack Block / Embed)       |
|  - Secret Management (Environment Variables / Vault)         |
|  - Asynchronous HTTP Dispatcher (httpx)                      |
+--------------------------------------------------------------+
         /                      |                      \
        v                       v                       v
+---------------+       +---------------+       +---------------+
|     Slack     |       |    Discord    |       |   Telegram    |
| Incoming Hook |       | Webhook URL   |       | Bot API Hook  |
+---------------+       +---------------+       +---------------+

2. Implementing the Unified Notification Tool

Let’s build a modular dispatcher using httpx and pydantic:

import os
from typing import Dict, Any, Optional, Literal
import httpx
from pydantic import BaseModel, Field
from google.adk.agents import Agent

class NotificationInput(BaseModel):
    platform: Literal["slack", "discord", "telegram"] = Field(
        description="Target platform to dispatch notification to."
    )
    title: str = Field(
        description="Short, impactful headline for the notification."
    )
    message: str = Field(
        description="Detailed body of the notification message. Supports markdown."
    )
    severity: Literal["info", "warning", "critical"] = Field(
        default="info",
        description="Urgency level of the message. Sets colors and priority badges."
    )
    action_url: Optional[str] = Field(
        default=None,
        description="Optional hyperlink for human reviewers to take immediate action."
    )

class WebhookNotifier:
    """Handles dispatching formatted payloads to external platforms."""

    def __init__(self):
        self.slack_url = os.environ.get("SLACK_WEBHOOK_URL")
        self.discord_url = os.environ.get("DISCORD_WEBHOOK_URL")
        self.telegram_bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")
        self.telegram_chat_id = os.environ.get("TELEGRAM_CHAT_ID")

    async def send_slack(self, inp: NotificationInput) -> Dict[str, Any]:
        if not self.slack_url:
            raise ValueError("SLACK_WEBHOOK_URL is not configured.")

        color_map = {"info": "#2eb886", "warning": "#daa038", "critical": "#a30200"}
        emoji_map = {"info": ":information_source:", "warning": ":warning:", "critical": ":rotating_light:"}

        blocks = [
            {
                "type": "header",
                "text": {"type": "plain_text", "text": f"{emoji_map[inp.severity]} {inp.title}"}
            },
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": inp.message}
            }
        ]

        if inp.action_url:
            blocks.append({
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {"type": "plain_text", "text": "Review Incident"},
                        "url": inp.action_url,
                        "style": "danger" if inp.severity == "critical" else "primary"
                    }
                ]
            })

        payload = {"attachments": [{"color": color_map[inp.severity], "blocks": blocks}]}

        async with httpx.AsyncClient() as client:
            resp = await client.post(self.slack_url, json=payload, timeout=10.0)
            resp.raise_for_status()

        return {"platform": "slack", "status": "delivered"}

    async def send_discord(self, inp: NotificationInput) -> Dict[str, Any]:
        if not self.discord_url:
            raise ValueError("DISCORD_WEBHOOK_URL is not configured.")

        # Decimal color representations
        color_map = {"info": 3066993, "warning": 15105570, "critical": 15158332}

        embed = {
            "title": inp.title,
            "description": inp.message,
            "color": color_map[inp.severity],
            "footer": {"text": f"Agent Notification • Severity: {inp.severity.upper()}"}
        }
        if inp.action_url:
            embed["url"] = inp.action_url

        payload = {"embeds": [embed]}

        async with httpx.AsyncClient() as client:
            resp = await client.post(self.discord_url, json=payload, timeout=10.0)
            resp.raise_for_status()

        return {"platform": "discord", "status": "delivered"}

    async def send_telegram(self, inp: NotificationInput) -> Dict[str, Any]:
        if not self.telegram_bot_token or not self.telegram_chat_id:
            raise ValueError("TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID must be configured.")

        url = f"https://api.telegram.org/bot{self.telegram_bot_token}/sendMessage"
        emoji_map = {"info": "ℹ️", "warning": "⚠️", "critical": "🚨"}

        formatted_text = (
            f"<b>{emoji_map[inp.severity]} {inp.title}</b>\n\n"
            f"{inp.message}\n\n"
            f"<i>Priority: {inp.severity.upper()}</i>"
        )
        if inp.action_url:
            formatted_text += f'\n<a href="{inp.action_url}">[View Details & Action]</a>'

        payload = {
            "chat_id": self.telegram_chat_id,
            "text": formatted_text,
            "parse_mode": "HTML",
            "disable_web_page_preview": False,
        }

        async with httpx.AsyncClient() as client:
            resp = await client.post(url, json=payload, timeout=10.0)
            resp.raise_for_status()

        return {"platform": "telegram", "status": "delivered"}

notifier = WebhookNotifier()

async def dispatch_agent_alert(inp: NotificationInput) -> Dict[str, Any]:
    """Sends a rich formatted notification to Slack, Discord, or Telegram.

    Use this tool whenever human alerting or task completion broadcasts are required.
    """
    try:
        if inp.platform == "slack":
            res = await notifier.send_slack(inp)
        elif inp.platform == "discord":
            res = await notifier.send_discord(inp)
        elif inp.platform == "telegram":
            res = await notifier.send_telegram(inp)
        else:
            return {"status": "error", "message": f"Unsupported platform: {inp.platform}"}

        return {"status": "success", "result": res}
    except Exception as exc:
        return {"status": "error", "message": str(exc)}

3. Configuring the Alerting Agent

Now we register our async tool with an ADK Agent:

monitoring_agent = Agent(
    name="ops_sentinel",
    model="gemini-3.8-flash",
    instruction="""
    You are a DevOps Incident Responder and Security Sentinel.
    When monitoring system logs or pipeline states:
    1. If you encounter critical errors, data outages, or unauthorized attempts,
       immediately dispatch an alert via `dispatch_agent_alert`.
    2. Choose the appropriate platform and severity based on user policy.
    3. Include a concise summary and actionable reproduction steps.
    """,
    tools=[dispatch_agent_alert],
)

4. Best Practices for Agent Notifications

  1. Deduplication and Throttling: If an agent encounters a repeating failure loop, don’t flood team channels with dozens of duplicate messages. Maintain a small recent-hashes cache inside session state to rate-limit notifications.
  2. Channel Scoping: Separate noisy test alerts (#dev-bot-spam) from critical escalations (#prod-incidents). Let the agent accept a channel tag or resolve it dynamically.
  3. Graceful Failure: Ensure that network failures to Slack/Discord don’t abort the entire agent turn. Catch exceptions and log them as non-fatal tool errors.

Takeaway: Equipping ADK agents with Slack, Discord, and Telegram webhook tools bridges the gap between autonomous AI processes and real-time team collaboration.

Sources