Skip to content

Self-improving AI Employees for everyone

feat: Add Telegram integration (WIP)

trohitg8f2afaced28b
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index ce2d5662..9564201a 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -69,7 +69,7 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
const types: Record<string, React.ComponentType<any>> = {};
// Trigger nodes (no input handles) - check by group or specific types
- const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'gmailReceive', 'chatTrigger', 'taskTrigger'];
+ const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'telegramReceive', 'twitterReceive', 'gmailReceive', 'chatTrigger', 'taskTrigger'];
// Pre-register specialized agent nodes explicitly to ensure they're always available
// This handles cases where nodeDefinitions iteration order might miss them
@@ -94,6 +94,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
} else if (type === 'whatsappSend' || type === 'whatsappDb') {
// WhatsApp action nodes use SquareNode (whatsappReceive is a trigger)
types[type] = SquareNode;
+ } else if (type === 'telegramSend') {
+ // Telegram action node uses SquareNode (telegramReceive is a trigger)
+ types[type] = SquareNode;
} else if (type === 'twitterSend' || type === 'twitterSearch' || type === 'twitterUser') {
// Twitter action nodes use SquareNode (twitterReceive is a trigger)
types[type] = SquareNode;
@@ -670,8 +673,8 @@ const DashboardContent: React.FC = () => {
if (!currentWorkflow) return;
// Check if there's at least one trigger node (workflow entry points)
- // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, twitterReceive, gmailReceive, workflowTrigger, chatTrigger, taskTrigger
- const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'gmailReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];
+ // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, telegramReceive, twitterReceive, gmailReceive, workflowTrigger, chatTrigger, taskTrigger
+ const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'telegramReceive', 'twitterReceive', 'gmailReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];
const hasTriggerNode = nodes.some(node => triggerTypes.includes(node.type || ''));
if (!hasTriggerNode) {
alert('No trigger node found in workflow.\n\nAdd a trigger node (Cron Scheduler, WhatsApp Receive, Webhook, Chat Trigger, etc.) to begin deployment.');
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsx
index daac9c95..95aebabd 100644
--- a/client/src/components/CredentialsModal.tsx
+++ b/client/src/components/CredentialsModal.tsx
@@ -19,7 +19,7 @@ import QRCodeDisplay from './ui/QRCodeDisplay';
import ApiKeyInput from './ui/ApiKeyInput';
import { useApiKeys, ProviderDefaults, ProviderUsageSummary, APIUsageSummary } from '../hooks/useApiKeys';
import { useAppTheme } from '../hooks/useAppTheme';
-import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGoogleStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
+import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGoogleStatus, useTelegramStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
import { useWhatsApp } from '../hooks/useWhatsApp';
import {
OpenAIIcon, ClaudeIcon, GeminiIcon, GroqIcon, OpenRouterIcon, CerebrasIcon,
@@ -100,7 +100,7 @@ interface CredentialItem {
Icon?: React.FC<{ size?: number }>;
CustomIcon?: React.FC;
isSpecial?: boolean;
- panelType?: 'whatsapp' | 'android' | 'twitter' | 'gmail' | 'google_maps' | 'search';
+ panelType?: 'whatsapp' | 'android' | 'twitter' | 'telegram' | 'gmail' | 'google_maps' | 'search';
}
interface Category {
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 78d331a3..dbb13949 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -31,7 +31,7 @@ interface PendingRequest {
const REQUEST_TIMEOUT = 30000;
// Trigger node types that wait indefinitely for events
-const TRIGGER_NODE_TYPES = ['whatsappReceive', 'webhookTrigger', 'cronScheduler', 'chatTrigger'];
+const TRIGGER_NODE_TYPES = ['whatsappReceive', 'webhookTrigger', 'cronScheduler', 'chatTrigger', 'telegramReceive'];
// Status types
export interface AndroidStatus {
@@ -107,6 +107,13 @@ export interface GoogleStatus {
profile_image_url?: string;
}
+export interface TelegramStatus {
+ connected: boolean;
+ bot_username: string | null;
+ bot_name: string | null;
+ bot_id: string | null;
+}
+
// WhatsApp Rate Limit types (from Go RPC schema)
export interface RateLimitConfig {
enabled: boolean;
@@ -222,6 +229,7 @@ interface WebSocketContextValue {
whatsappStatus: WhatsAppStatus;
twitterStatus: TwitterStatus;
googleStatus: GoogleStatus;
+ telegramStatus: TelegramStatus;
whatsappMessages: WhatsAppMessage[]; // History of received messages
lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message
apiKeyStatuses: Record<string, ApiKeyStatus>;
@@ -355,6 +363,13 @@ const defaultGoogleStatus: GoogleStatus = {
email: null,
};
+const defaultTelegramStatus: TelegramStatus = {
+ connected: false,
+ bot_username: null,
+ bot_name: null,
+ bot_id: null,
+};
+
const WebSocketContext = createContext<WebSocketContextValue | null>(null);
// WebSocket URL (convert http to ws)
@@ -390,6 +405,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const [whatsappStatus, setWhatsappStatus] = useState<WhatsAppStatus>(defaultWhatsAppStatus);
const [twitterStatus, setTwitterStatus] = useState<TwitterStatus>(defaultTwitterStatus);
const [googleStatus, setGoogleStatus] = useState<GoogleStatus>(defaultGoogleStatus);
+ const [telegramStatus, setTelegramStatus] = useState<TelegramStatus>(defaultTelegramStatus);
const [whatsappMessages, setWhatsappMessages] = useState<WhatsAppMessage[]>([]);
const [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);
const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});
@@ -506,6 +522,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
if (data.whatsapp) setWhatsappStatus(data.whatsapp);
if (data.twitter) setTwitterStatus(data.twitter);
if (data.google) setGoogleStatus(data.google);
+ if (data.telegram) setTelegramStatus(data.telegram);
if (data.api_keys) setApiKeyStatuses(data.api_keys);
// Node statuses from initial_status - group by workflow_id (n8n pattern)
if (data.nodes) {
@@ -596,6 +613,18 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
break;
+ case 'telegram_status':
+ // Handle Telegram bot status updates
+ if (data) {
+ setTelegramStatus({
+ connected: data.connected || false,
+ bot_username: data.bot_username || null,
+ bot_name: data.bot_name || null,
+ bot_id: data.bot_id || null,
+ });
+ }
+ break;
+
case 'whatsapp_message_received':
// Handle incoming WhatsApp message from Go service
if (data) {
@@ -2054,6 +2083,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
whatsappStatus,
twitterStatus,
googleStatus,
+ telegramStatus,
whatsappMessages,
lastWhatsAppMessage,
apiKeyStatuses,
@@ -2199,6 +2229,12 @@ export const useGoogleStatus = (): GoogleStatus => {
return googleStatus;
};
+// Hook specifically for Telegram status
+export const useTelegramStatus = (): TelegramStatus => {
+ const { telegramStatus } = useWebSocket();
+ return telegramStatus;
+};
+
// Hook specifically for deployment status
export const useDeploymentStatus = (): DeploymentStatus => {
const { deploymentStatus } = useWebSocket();
diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.ts
index 109a601a..b0630675 100644
--- a/client/src/nodeDefinitions.ts
+++ b/client/src/nodeDefinitions.ts
@@ -8,6 +8,7 @@ import { toolNodes, TOOL_NODE_TYPES } from './nodeDefinitions/toolNodes';
import { specializedAgentNodes, SPECIALIZED_AGENT_TYPES } from './nodeDefinitions/specializedAgentNodes';
import { locationNodes, LOCATION_NODE_TYPES } from './nodeDefinitions/locationNodes';
import { whatsappNodes, WHATSAPP_NODE_TYPES } from './nodeDefinitions/whatsappNodes';
+import { telegramNodes, TELEGRAM_NODE_TYPES } from './nodeDefinitions/telegramNodes';
import { workflowNodes } from './nodeDefinitions/workflowNodes';
import { schedulerNodes, SCHEDULER_NODE_TYPES } from './nodeDefinitions/schedulerNodes';
import { androidServiceNodes, ANDROID_SERVICE_NODE_TYPES } from './nodeDefinitions/androidServiceNodes';
@@ -37,6 +38,7 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {
...specializedAgentNodes,
...locationNodes,
...whatsappNodes,
+ ...telegramNodes,
...androidServiceNodes,
...chatNodes,
...codeNodes,
@@ -79,6 +81,10 @@ export const WHATSAPP_NODES = [
...WHATSAPP_NODE_TYPES
];
+export const TELEGRAM_NODES = [
+ ...TELEGRAM_NODE_TYPES
+];
+
export const ANDROID_SERVICE_NODES = [
...ANDROID_SERVICE_NODE_TYPES
];
diff --git a/client/src/nodeDefinitions/telegramNodes.ts b/client/src/nodeDefinitions/telegramNodes.ts
new file mode 100644
index 00000000..d6439175
--- /dev/null
+++ b/client/src/nodeDefinitions/telegramNodes.ts
@@ -0,0 +1,316 @@
+// Telegram Node Definitions - Messaging integration via python-telegram-bot
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+
+// ============================================================================
+// TELEGRAM ICONS (SVG Data URIs)
+// ============================================================================
+
+// Telegram Send - Paper plane (send message)
+const TELEGRAM_SEND_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%230088CC'%3E%3Cpath d='M2.01 21L23 12 2.01 3 2 10l15 2-15 2z'/%3E%3C/svg%3E";
+
+// Telegram Logo - Official Telegram logo (exported for use in credentials/skill nodes)
+export const TELEGRAM_LOGO_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%230088CC'%3E%3Cpath d='M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z'/%3E%3C/svg%3E";
+
+// Telegram Receive - Notification bell with dot (trigger node)
+const TELEGRAM_RECEIVE_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%230088CC'%3E%3Cpath d='M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z'/%3E%3Ccircle cx='18' cy='6' r='4'/%3E%3C/svg%3E";
+
+// ============================================================================
+// TELEGRAM NODES
+// ============================================================================
+
+export const telegramNodes: Record<string, INodeTypeDescription> = {
+ // Telegram Send Message Node - Send text, media, location, contact
+ telegramSend: {
+ displayName: 'Telegram Send',
+ name: 'telegramSend',
+ icon: TELEGRAM_SEND_ICON,
+ group: ['social', 'tool'],
+ version: 1,
+ subtitle: 'Send Telegram Message',
+ description: 'Send text, photo, document, location, or contact messages via Telegram bot',
+ defaults: { name: 'Telegram Send', color: '#0088CC' },
+ inputs: [{
+ name: 'main',
+ displayName: 'Input',
+ type: 'main' as NodeConnectionType,
+ description: 'Message input'
+ }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Message output'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }
+ ],
+ properties: [
+ // ===== RECIPIENT =====
+ {
+ displayName: 'Chat ID',
+ name: 'chat_id',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '123456789 or @username',
+ description: 'Telegram chat ID (numeric) or @username'
+ },
+
+ // ===== MESSAGE TYPE =====
+ {
+ displayName: 'Message Type',
+ name: 'message_type',
+ type: 'options',
+ options: [
+ { name: 'Text', value: 'text' },
+ { name: 'Photo', value: 'photo' },
+ { name: 'Document', value: 'document' },
+ { name: 'Location', value: 'location' },
+ { name: 'Contact', value: 'contact' }
+ ],
+ default: 'text',
+ description: 'Type of message to send'
+ },
+
+ // ===== TEXT MESSAGE =====
+ {
+ displayName: 'Message Text',
+ name: 'text',
+ type: 'string',
+ default: '',
+ required: true,
+ typeOptions: { rows: 4 },
+ description: 'Text message content',
+ placeholder: 'Enter your message...',
+ displayOptions: {
+ show: { message_type: ['text'] }
+ }
+ },
+
+ // ===== MEDIA MESSAGES (photo, document) =====
+ {
+ displayName: 'Media URL',
+ name: 'media_url',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'https://example.com/image.jpg',
+ description: 'URL of the media file or file_id from previous message',
+ displayOptions: {
+ show: { message_type: ['photo', 'document'] }
+ }
+ },
+ {
+ displayName: 'Caption',
+ name: 'caption',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 2 },
+ description: 'Optional caption for media',
+ displayOptions: {
+ show: { message_type: ['photo', 'document'] }
+ }
+ },
+
+ // ===== LOCATION MESSAGE =====
+ {
+ displayName: 'Latitude',
+ name: 'latitude',
+ type: 'number',
+ default: 0,
+ required: true,
+ description: 'Location latitude (-90 to 90)',
+ displayOptions: {
+ show: { message_type: ['location'] }
+ }
+ },
+ {
+ displayName: 'Longitude',
+ name: 'longitude',
+ type: 'number',
+ default: 0,
+ required: true,
+ description: 'Location longitude (-180 to 180)',
+ displayOptions: {
+ show: { message_type: ['location'] }
+ }
+ },
+
+ // ===== CONTACT MESSAGE =====
+ {
+ displayName: 'Phone Number',
+ name: 'phone_number',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: '+1234567890',
+ description: 'Contact phone number (with country code)',
+ displayOptions: {
+ show: { message_type: ['contact'] }
+ }
+ },
+ {
+ displayName: 'First Name',
+ name: 'first_name',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'John',
+ description: 'Contact first name',
+ displayOptions: {
+ show: { message_type: ['contact'] }
+ }
+ },
+ {
+ displayName: 'Last Name',
+ name: 'last_name',
+ type: 'string',
+ default: '',
+ placeholder: 'Doe',
+ description: 'Contact last name (optional)',
+ displayOptions: {
+ show: { message_type: ['contact'] }
+ }
+ },
+
+ // ===== OPTIONS =====
+ {
+ displayName: 'Parse Mode',
+ name: 'parse_mode',
+ type: 'options',
+ options: [
+ { name: 'None', value: '' },
+ { name: 'HTML', value: 'HTML' },
+ { name: 'Markdown', value: 'Markdown' },
+ { name: 'MarkdownV2', value: 'MarkdownV2' }
+ ],
+ default: '',
+ description: 'Text formatting mode',
+ displayOptions: {
+ show: { message_type: ['text', 'photo', 'document'] }
+ }
+ },
+ {
+ displayName: 'Silent',
+ name: 'silent',
+ type: 'boolean',
+ default: false,
+ description: 'Send message without notification sound'
+ },
+ {
+ displayName: 'Reply To Message ID',
+ name: 'reply_to_message_id',
+ type: 'number',
+ default: 0,
+ description: 'If set, sends the message as a reply to this message ID'
+ }
+ ]
+ },
+
+ // Telegram Receive Message - triggers workflow on incoming messages
+ telegramReceive: {
+ displayName: 'Telegram Receive',
+ name: 'telegramReceive',
+ icon: TELEGRAM_RECEIVE_ICON,
+ group: ['social', 'trigger'],
+ version: 1,
+ subtitle: 'On Message Received',
+ description: 'Trigger workflow when Telegram message is received. Outputs message data including sender, content, and metadata.',
+ defaults: { name: 'Telegram Receive', color: '#0077B5' },
+ inputs: [],
+ outputs: [{
+ name: 'main',
+ displayName: 'Message',
+ type: 'main' as NodeConnectionType,
+ description: 'Received message data (message_id, chat_id, chat_type, from_id, from_username, text, content_type, date)'
+ }],
+ properties: [
+ // ===== CHAT TYPE FILTER =====
+ {
+ displayName: 'Chat Type',
+ name: 'chatTypeFilter',
+ type: 'options',
+ options: [
+ { name: 'All Types', value: 'all' },
+ { name: 'Private Only', value: 'private' },
+ { name: 'Group Only', value: 'group' },
+ { name: 'Supergroup Only', value: 'supergroup' },
+ { name: 'Channel Only', value: 'channel' }
+ ],
+ default: 'all',
+ description: 'Filter by chat type'
+ },
+
+ // ===== CONTENT TYPE FILTER =====
+ {
+ displayName: 'Content Type',
+ name: 'contentTypeFilter',
+ type: 'options',
+ options: [
+ { name: 'All Types', value: 'all' },
+ { name: 'Text Only', value: 'text' },
+ { name: 'Photo Only', value: 'photo' },
+ { name: 'Video Only', value: 'video' },
+ { name: 'Audio Only', value: 'audio' },
+ { name: 'Voice Only', value: 'voice' },
+ { name: 'Document Only', value: 'document' },
+ { name: 'Sticker Only', value: 'sticker' },
+ { name: 'Location Only', value: 'location' },
+ { name: 'Contact Only', value: 'contact' },
+ { name: 'Poll Only', value: 'poll' }
+ ],
+ default: 'all',
+ description: 'Filter by message content type'
+ },
+
+ // ===== SPECIFIC FILTERS =====
+ {
+ displayName: 'Chat ID Filter',
+ name: 'chat_id',
+ type: 'string',
+ default: '',
+ placeholder: '123456789',
+ description: 'Only trigger for messages from this specific chat (leave empty for all chats)'
+ },
+ {
+ displayName: 'From User ID Filter',
+ name: 'from_user',
+ type: 'string',
+ default: '',
+ placeholder: '987654321',
+ description: 'Only trigger for messages from this specific user ID (leave empty for all users)'
+ },
+ {
+ displayName: 'Keywords',
+ name: 'keywords',
+ type: 'string',
+ default: '',
+ placeholder: 'help, support, info',
+ description: 'Comma-separated keywords to trigger on (case-insensitive, leave empty to trigger on all)'
+ },
+
+ // ===== OPTIONS =====
+ {
+ displayName: 'Ignore Bot Messages',
+ name: 'ignoreBots',
+ type: 'boolean',
+ default: true,
+ description: 'Do not trigger on messages from other bots'
+ }
+ ]
+ }
+};
+
+// ============================================================================
+// EXPORTS
+// ============================================================================
+
+export const TELEGRAM_NODE_TYPES = ['telegramSend', 'telegramReceive'];
diff --git a/server/requirements.txt b/server/requirements.txt
index cff5e931..117f802b 100644
--- a/server/requirements.txt
+++ b/server/requirements.txt
@@ -82,6 +82,9 @@ xdk>=0.1.0
# Apify Web Scraping
apify-client>=1.8.0
+# Telegram Bot API
+python-telegram-bot==22.6
+
# Gmail API
google-api-python-client>=2.100.0
google-auth>=2.27.0
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 332d2caa..21806592 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1762,6 +1762,190 @@ async def handle_whatsapp_rate_limit_unpause(data: Dict[str, Any], websocket: We
return result
+# ============================================================================
+# Telegram Handlers - Connect/disconnect/status for Telegram bot
+# ============================================================================
+
+from services.telegram_service import get_telegram_service
+
+
+async def handle_telegram_connect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Connect to Telegram with bot token. Stores token in encrypted credentials."""
+ token = data.get("token")
+ if not token:
+ return {"success": False, "error": "Bot token required"}
+
+ service = get_telegram_service()
+ result = await service.connect(token)
+
+ # Store token in encrypted credentials on success
+ if result.get("success"):
+ try:
+ auth_service = get_auth_service()
+ await auth_service.store_api_key(
+ provider="telegram_bot_token",
+ api_key=token,
+ models=[],
+ session_id="default",
+ )
+ except Exception as e:
+ logger.warning(f"[Telegram] Failed to store token in credentials: {e}")
+
+ return result
+
+
+async def handle_telegram_disconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Disconnect Telegram bot and remove stored token."""
+ service = get_telegram_service()
+ result = await service.disconnect()
+
+ # Remove stored token
+ try:
+ auth_service = get_auth_service()
+ await auth_service.remove_api_key("telegram_bot_token")
+ except Exception as e:
+ logger.warning(f"[Telegram] Failed to remove stored token: {e}")
+
+ return result
+
+
+async def handle_telegram_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get Telegram bot connection status. Also checks for stored token."""
+ service = get_telegram_service()
+ status = service.get_status()
+
+ # Check if token is stored (for reconnect UI)
+ has_stored_token = False
+ try:
+ auth_service = get_auth_service()
+ stored = await auth_service.get_api_key("telegram_bot_token")
+ has_stored_token = stored is not None
+ except Exception:
+ pass
+
+ status["has_stored_token"] = has_stored_token
+ return {"success": True, "status": status}
+
+
+async def handle_telegram_send(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Send message via Telegram bot (direct WebSocket call, not via workflow node)."""
+ service = get_telegram_service()
+
+ if not service.connected:
+ return {"success": False, "error": "Telegram bot not connected"}
+
+ chat_id = data.get("chat_id")
+ message_type = data.get("message_type", "text")
+ text = data.get("text")
+ parse_mode = data.get("parse_mode")
+
+ if not chat_id:
+ return {"success": False, "error": "chat_id required"}
+
+ try:
+ if message_type == "text":
+ if not text:
+ return {"success": False, "error": "text required for text message"}
+ result = await service.send_message(
+ chat_id=chat_id,
+ text=text,
+ parse_mode=parse_mode,
+ )
+ elif message_type == "photo":
+ photo_url = data.get("media_url")
+ if not photo_url:
+ return {"success": False, "error": "media_url required for photo"}
+ result = await service.send_photo(
+ chat_id=chat_id,
+ photo=photo_url,
+ caption=data.get("caption"),
+ parse_mode=parse_mode,
+ )
+ elif message_type == "document":
+ doc_url = data.get("media_url")
+ if not doc_url:
+ return {"success": False, "error": "media_url required for document"}
+ result = await service.send_document(
+ chat_id=chat_id,
+ document=doc_url,
+ caption=data.get("caption"),
+ parse_mode=parse_mode,
+ )
+ elif message_type == "location":
+ lat = data.get("latitude")
+ lon = data.get("longitude")
+ if lat is None or lon is None:
+ return {"success": False, "error": "latitude and longitude required"}
+ result = await service.send_location(
+ chat_id=chat_id,
+ latitude=float(lat),
+ longitude=float(lon),
+ )
+ elif message_type == "contact":
+ phone = data.get("phone_number")
+ first_name = data.get("first_name")
+ if not phone or not first_name:
+ return {"success": False, "error": "phone_number and first_name required"}
+ result = await service.send_contact(
+ chat_id=chat_id,
+ phone_number=phone,
+ first_name=first_name,
+ last_name=data.get("last_name"),
+ )
+ else:
+ return {"success": False, "error": f"Unsupported message type: {message_type}"}
+
+ return {"success": True, "result": result}
+ except Exception as e:
+ logger.error(f"[Telegram] Send error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def handle_telegram_reconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Reconnect Telegram using stored bot token from encrypted credentials."""
+ try:
+ auth_service = get_auth_service()
+ token = await auth_service.get_api_key("telegram_bot_token")
+ if not token:
+ return {"success": False, "error": "No stored bot token found. Enter token to connect."}
+
+ service = get_telegram_service()
+ result = await service.connect(token)
+ return result
+ except Exception as e:
+ logger.error(f"[Telegram] Reconnect failed: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def handle_telegram_get_me(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get bot info."""
+ service = get_telegram_service()
+ if not service.connected:
+ return {"success": False, "error": "Telegram bot not connected"}
+ try:
+ result = await service.get_me()
+ return {"success": True, "result": result}
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+
+async def handle_telegram_get_chat(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get chat info."""
+ service = get_telegram_service()
+ if not service.connected:
+ return {"success": False, "error": "Telegram bot not connected"}
+
+ chat_id = data.get("chat_id")
+ if not chat_id:
+ return {"success": False, "error": "chat_id required"}
+
+ try:
+ result = await service.get_chat(chat_id)
+ return {"success": True, "result": result}
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+
# ============================================================================
# Workflow Storage Operations
# ============================================================================
@@ -2703,6 +2887,15 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"whatsapp_rate_limit_stats": handle_whatsapp_rate_limit_stats,
"whatsapp_rate_limit_unpause": handle_whatsapp_rate_limit_unpause,
+ # Telegram operations
+ "telegram_connect": handle_telegram_connect,
+ "telegram_disconnect": handle_telegram_disconnect,
+ "telegram_reconnect": handle_telegram_reconnect,
+ "telegram_status": handle_telegram_status,
+ "telegram_send": handle_telegram_send,
+ "telegram_get_me": handle_telegram_get_me,
+ "telegram_get_chat": handle_telegram_get_chat,
+
# Workflow storage operations
"save_workflow": handle_save_workflow,
"get_workflow": handle_get_workflow,
diff --git a/server/services/event_waiter.py b/server/services/event_waiter.py
index c1e4fc1f..63940daf 100644
--- a/server/services/event_waiter.py
+++ b/server/services/event_waiter.py
@@ -120,9 +120,13 @@ TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {
event_type='gmail_email_received',
display_name='Gmail Email'
),
+ 'telegramReceive': TriggerConfig(
+ node_type='telegramReceive',
+ event_type='telegram_message_received',
+ display_name='Telegram Message'
+ ),
# Future triggers - just add to registry:
# 'mqttTrigger': TriggerConfig('mqttTrigger', 'mqtt_message', 'MQTT Message'),
- # 'telegramTrigger': TriggerConfig('telegramTrigger', 'telegram_message', 'Telegram'),
}
@@ -416,6 +420,89 @@ def build_gmail_filter(params: Dict) -> Callable[[Dict], bool]:
return matches
+def build_telegram_filter(params: Dict) -> Callable[[Dict], bool]:
+ """Build filter function for Telegram messages.
+
+ Filters by:
+ - chatTypeFilter: 'all', 'private', 'group', 'supergroup', 'channel'
+ - contentTypeFilter: 'all', 'text', 'photo', 'video', 'audio', 'voice', 'document', 'sticker', 'location', 'contact', 'poll'
+ - chat_id: Filter to specific chat (optional)
+ - from_user: Filter to specific user ID (optional)
+ - keywords: Comma-separated keywords to match in text (optional)
+ - ignoreBots: Ignore messages from bots (default: True)
+
+ Event data fields (from TelegramService._format_message):
+ - message_id: int
+ - chat_id: int
+ - chat_type: str ('private', 'group', 'supergroup', 'channel')
+ - chat_title: str (for groups/channels)
+ - from_id: int (sender user ID)
+ - from_username: str (sender username)
+ - from_first_name: str
+ - from_last_name: str
+ - is_bot: bool
+ - text: str (message text or caption)
+ - content_type: str
+ - date: str (ISO format)
+ - reply_to_message_id: int (optional)
+ - photo/document/location/contact: dict (media info if present)
+
+ Args:
+ params: Node parameters
+
+ Returns:
+ Filter function that checks if event matches criteria
+ """
+ chat_type_filter = params.get('chatTypeFilter', 'all')
+ content_type_filter = params.get('contentTypeFilter', 'all')
+ chat_id_filter = params.get('chat_id', '')
+ from_user_filter = params.get('from_user', '')
+ keywords = [k.strip().lower() for k in params.get('keywords', '').split(',') if k.strip()]
+ ignore_bots = params.get('ignoreBots', True)
+
+ logger.debug(f"[TelegramFilter] Built: chat_type={chat_type_filter}, content_type={content_type_filter}, chat_id='{chat_id_filter}', ignore_bots={ignore_bots}")
+
+ def matches(m: Dict) -> bool:
+ # Chat type filter
+ if chat_type_filter != 'all':
+ msg_chat_type = m.get('chat_type', '')
+ if msg_chat_type != chat_type_filter:
+ return False
+
+ # Content type filter
+ if content_type_filter != 'all':
+ msg_content_type = m.get('content_type', '')
+ if msg_content_type != content_type_filter:
+ return False
+
+ # Chat ID filter (exact match)
+ if chat_id_filter:
+ msg_chat_id = str(m.get('chat_id', ''))
+ if msg_chat_id != str(chat_id_filter):
+ return False
+
+ # From user filter (user ID)
+ if from_user_filter:
+ msg_from_id = str(m.get('from_id', ''))
+ if msg_from_id != str(from_user_filter):
+ return False
+
+ # Keywords filter (any keyword in text)
+ if keywords:
+ text = (m.get('text') or '').lower()
+ if not any(kw in text for kw in keywords):
+ return False
+
+ # Ignore bot messages
+ if ignore_bots and m.get('is_bot', False):
+ return False
+
+ logger.debug(f"[TelegramFilter] Matched message from {m.get('from_username', m.get('from_id'))}")
+ return True
+
+ return matches
+
+
# Registry of filter builders per trigger type
FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {
'whatsappReceive': build_whatsapp_filter,
@@ -424,6 +511,7 @@ FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {
'taskTrigger': build_task_completed_filter,
'twitterReceive': build_twitter_filter,
'gmailReceive': build_gmail_filter,
+ 'telegramReceive': build_telegram_filter,
}
diff --git a/server/services/handlers/telegram.py b/server/services/handlers/telegram.py
new file mode 100644
index 00000000..a669ee83
--- /dev/null
+++ b/server/services/handlers/telegram.py
@@ -0,0 +1,302 @@
+"""
+Telegram Node Handlers
+
+Handles execution of Telegram workflow nodes:
+- telegramSend: Send messages via Telegram bot
+- telegramReceive: Trigger node that waits for incoming messages
+"""
+
+import time
+from datetime import datetime
+from typing import Any, Dict
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+async def handle_telegram_send(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Telegram send message node execution.
+
+ Parameters (snake_case):
+ - chat_id: Chat ID or @username (required)
+ - message_type: text, photo, document, location, contact (default: text)
+ - text: Message text (for text type)
+ - caption: Caption for media (for photo/document types)
+ - media_url: URL for photo/document
+ - parse_mode: HTML, Markdown, MarkdownV2 (optional)
+ - latitude, longitude: For location type
+ - phone_number, first_name, last_name: For contact type
+ - silent: Send without notification (default: False)
+ - reply_to_message_id: Reply to this message (optional)
+
+ Returns:
+ Execution result with sent message info
+ """
+ from services.telegram_service import get_telegram_service
+
+ start_time = time.time()
+ service = get_telegram_service()
+
+ try:
+ if not service.connected:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "Telegram bot not connected. Add bot token in Credentials.",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ # Extract parameters
+ chat_id = parameters.get("chat_id")
+ if not chat_id:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "chat_id is required",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ message_type = parameters.get("message_type", "text")
+ parse_mode = parameters.get("parse_mode") or None
+ silent = parameters.get("silent", False)
+ reply_to = parameters.get("reply_to_message_id")
+ if reply_to:
+ reply_to = int(reply_to)
+
+ # Route based on message type
+ result = {}
+ match message_type:
+ case "text":
+ text = parameters.get("text")
+ if not text:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "text is required for text message",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+ result = await service.send_message(
+ chat_id=chat_id,
+ text=text,
+ parse_mode=parse_mode,
+ disable_notification=silent,
+ reply_to_message_id=reply_to,
+ )
+
+ case "photo":
+ photo_url = parameters.get("media_url")
+ if not photo_url:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "media_url is required for photo message",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+ result = await service.send_photo(
+ chat_id=chat_id,
+ photo=photo_url,
+ caption=parameters.get("caption"),
+ parse_mode=parse_mode,
+ disable_notification=silent,
+ reply_to_message_id=reply_to,
+ )
+
+ case "document":
+ document_url = parameters.get("media_url")
+ if not document_url:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "media_url is required for document message",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+ result = await service.send_document(
+ chat_id=chat_id,
+ document=document_url,
+ caption=parameters.get("caption"),
+ parse_mode=parse_mode,
+ disable_notification=silent,
+ reply_to_message_id=reply_to,
+ )
+
+ case "location":
+ latitude = parameters.get("latitude")
+ longitude = parameters.get("longitude")
+ if latitude is None or longitude is None:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "latitude and longitude are required for location message",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+ result = await service.send_location(
+ chat_id=chat_id,
+ latitude=float(latitude),
+ longitude=float(longitude),
+ disable_notification=silent,
+ reply_to_message_id=reply_to,
+ )
+
+ case "contact":
+ phone_number = parameters.get("phone_number")
+ first_name = parameters.get("first_name")
+ if not phone_number or not first_name:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "phone_number and first_name are required for contact message",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+ result = await service.send_contact(
+ chat_id=chat_id,
+ phone_number=phone_number,
+ first_name=first_name,
+ last_name=parameters.get("last_name"),
+ disable_notification=silent,
+ reply_to_message_id=reply_to,
+ )
+
+ case _:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": f"Unsupported message type: {message_type}",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ logger.info(f"[Telegram] Message sent: type={message_type}, chat={chat_id}, msg_id={result.get('message_id')}")
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": node_type,
+ "result": {
+ "message_id": result.get("message_id"),
+ "chat_id": result.get("chat_id"),
+ "message_type": message_type,
+ "date": result.get("date"),
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ except Exception as e:
+ logger.error(f"[Telegram] Send failed: {e}")
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+async def handle_telegram_receive(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Telegram receive trigger node.
+
+ This is an event-driven trigger that waits for incoming Telegram messages.
+ Uses the event_waiter system to register a waiter and wait for matching events.
+
+ Filter Parameters:
+ - chatTypeFilter: all, private, group, supergroup, channel
+ - contentTypeFilter: all, text, photo, video, document, location, contact
+ - chat_id: Filter to specific chat (optional)
+ - from_user: Filter to specific user ID (optional)
+ - keywords: Comma-separated keywords to match in text (optional)
+ - ignoreBots: Ignore messages from bots (default: True)
+
+ Returns:
+ The matched Telegram message data
+ """
+ from services import event_waiter
+ from services.status_broadcaster import get_status_broadcaster
+ from services.telegram_service import get_telegram_service
+
+ start_time = time.time()
+ broadcaster = get_status_broadcaster()
+ service = get_telegram_service()
+
+ try:
+ # Check if bot is connected
+ if not service.connected:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "Telegram bot not connected. Add bot token in Credentials.",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ # Register waiter with filter
+ waiter = event_waiter.register(node_type, node_id, parameters)
+
+ logger.info(f"[Telegram] Trigger {node_id} waiting for message (waiter_id={waiter.id})")
+
+ # Broadcast waiting status
+ await broadcaster.update_node_status(
+ node_id,
+ "waiting",
+ {
+ "message": "Waiting for Telegram message...",
+ "waiter_id": waiter.id,
+ "filters": {
+ "chat_type": parameters.get("chatTypeFilter", "all"),
+ "content_type": parameters.get("contentTypeFilter", "all"),
+ "keywords": parameters.get("keywords", ""),
+ }
+ }
+ )
+
+ # Wait for matching event (no timeout - user cancels via cancel_event_wait)
+ event_data = await waiter.future
+
+ logger.info(f"[Telegram] Trigger {node_id} received message: {event_data.get('content_type')} from {event_data.get('from_username', event_data.get('from_id'))}")
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": node_type,
+ "result": event_data,
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ except Exception as e:
+ logger.error(f"[Telegram] Receive failed: {e}")
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index 5b322a2d..ec201715 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -39,6 +39,7 @@ from services.handlers import (
handle_twitter_send, handle_twitter_search, handle_twitter_user,
handle_brave_search, handle_serper_search, handle_perplexity_search,
)
+from services.handlers.telegram import handle_telegram_send, handle_telegram_receive
from services.handlers.apify import handle_apify_actor
# Consolidated Google Workspace handlers (6 services with operation dispatchers)
from services.handlers.gmail import handle_google_gmail, handle_gmail_receive
@@ -144,6 +145,9 @@ class NodeExecutor:
# WhatsApp
'whatsappSend': handle_whatsapp_send,
'whatsappDb': handle_whatsapp_db,
+ # Telegram
+ 'telegramSend': handle_telegram_send,
+ 'telegramReceive': handle_telegram_receive,
# Twitter/X
'twitterSend': handle_twitter_send,
'twitterSearch': handle_twitter_search,
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index 0baecf0c..6bfeaede 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -53,6 +53,12 @@ class StatusBroadcaster:
"email": None,
"name": None,
},
+ "telegram": {
+ "connected": False,
+ "bot_id": None,
+ "bot_username": None,
+ "bot_name": None
+ },
"api_keys": {}, # provider -> validation status
"nodes": {}, # node_id -> node status
"variables": {}, # variable_name -> value
@@ -426,6 +432,36 @@ class StatusBroadcaster:
"""Get WhatsApp connection status."""
return self._status["whatsapp"].copy()
+ # =========================================================================
+ # Telegram Status Updates
+ # =========================================================================
+
+ async def update_telegram_status(
+ self,
+ connected: bool,
+ bot_id: Optional[int] = None,
+ bot_username: Optional[str] = None,
+ bot_name: Optional[str] = None
+ ):
+ """Update Telegram bot connection status and broadcast."""
+ import time
+ self._status["telegram"] = {
+ "connected": connected,
+ "bot_id": bot_id,
+ "bot_username": bot_username,
+ "bot_name": bot_name,
+ "timestamp": time.time()
+ }
+
+ await self.broadcast({
+ "type": "telegram_status",
+ "data": self._status["telegram"]
+ })
+
+ def get_telegram_status(self) -> Dict[str, Any]:
+ """Get Telegram bot connection status."""
+ return self._status["telegram"].copy()
+
# =========================================================================
# Node Status Updates
# =========================================================================
diff --git a/server/services/telegram_service.py b/server/services/telegram_service.py
new file mode 100644
index 00000000..11d12de0
--- /dev/null
+++ b/server/services/telegram_service.py
@@ -0,0 +1,537 @@
+"""
+Telegram Bot Integration Service
+
+Uses python-telegram-bot v22.6 for Bot API communication.
+Singleton service with background polling for receiving updates.
+"""
+
+import asyncio
+import logging
+from datetime import datetime
+from typing import Any, Dict, Optional
+
+from telegram import Bot, Update
+from telegram.ext import Application, ContextTypes, MessageHandler, filters
+
+logger = logging.getLogger(__name__)
+
+
+class TelegramService:
+ """Singleton service for Telegram bot operations."""
+
+ _instance: Optional["TelegramService"] = None
+ _lock = asyncio.Lock()
+
+ def __init__(self):
+ self._application: Optional[Application] = None
+ self._bot: Optional[Bot] = None
+ self._token: Optional[str] = None
+ self._connected: bool = False
+ self._polling_task: Optional[asyncio.Task] = None
+ self._bot_info: Dict[str, Any] = {}
+
+ @classmethod
+ def get_instance(cls) -> "TelegramService":
+ """Get singleton instance."""
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ @classmethod
+ async def reset_instance(cls):
+ """Reset singleton (for testing)."""
+ if cls._instance:
+ await cls._instance.disconnect()
+ cls._instance = None
+
+ @property
+ def connected(self) -> bool:
+ """Check if bot is connected and polling."""
+ return self._connected and self._application is not None
+
+ def get_status(self) -> Dict[str, Any]:
+ """Get current connection status."""
+ return {
+ "connected": self._connected,
+ "bot_id": self._bot_info.get("id"),
+ "bot_username": self._bot_info.get("username"),
+ "bot_name": self._bot_info.get("first_name"),
+ "polling_active": self._polling_task is not None and not self._polling_task.done(),
+ }
+
+ async def connect(self, token: str) -> Dict[str, Any]:
+ """Connect to Telegram with bot token and start polling.
+
+ Args:
+ token: Bot token from @BotFather
+
+ Returns:
+ Connection result with bot info
+ """
+ async with self._lock:
+ if self._connected:
+ await self._disconnect_internal()
+
+ try:
+ logger.info("[Telegram] Connecting with bot token...")
+
+ # Create bot and validate token
+ bot = Bot(token=token)
+ me = await bot.get_me()
+
+ self._bot_info = {
+ "id": me.id,
+ "username": me.username,
+ "first_name": me.first_name,
+ "can_join_groups": me.can_join_groups,
+ "can_read_all_group_messages": me.can_read_all_group_messages,
+ }
+
+ logger.info(f"[Telegram] Bot validated: @{me.username} (ID: {me.id})")
+
+ # Build application
+ self._application = Application.builder().token(token).build()
+ self._bot = self._application.bot
+ self._token = token
+
+ # Register message handler for all messages
+ self._application.add_handler(
+ MessageHandler(filters.ALL, self._on_message_received)
+ )
+
+ # Initialize application
+ await self._application.initialize()
+
+ # Start polling in background task
+ self._polling_task = asyncio.create_task(self._run_polling())
+ self._connected = True
+
+ # Broadcast status update
+ await self._broadcast_status()
+
+ logger.info(f"[Telegram] Connected and polling started for @{me.username}")
+
+ return {
+ "success": True,
+ "bot": self._bot_info,
+ "message": f"Connected to @{me.username}",
+ }
+
+ except Exception as e:
+ logger.error(f"[Telegram] Connection failed: {e}")
+ self._connected = False
+ self._application = None
+ self._bot = None
+ return {
+ "success": False,
+ "error": str(e),
+ }
+
+ async def disconnect(self) -> Dict[str, Any]:
+ """Disconnect bot and stop polling."""
+ async with self._lock:
+ return await self._disconnect_internal()
+
+ async def _disconnect_internal(self) -> Dict[str, Any]:
+ """Internal disconnect (must be called with lock held)."""
+ try:
+ logger.info("[Telegram] Disconnecting...")
+
+ # Cancel polling task
+ if self._polling_task and not self._polling_task.done():
+ self._polling_task.cancel()
+ try:
+ await self._polling_task
+ except asyncio.CancelledError:
+ pass
+
+ # Stop and shutdown application
+ if self._application:
+ try:
+ await self._application.stop()
+ await self._application.shutdown()
+ except Exception as e:
+ logger.warning(f"[Telegram] Shutdown warning: {e}")
+
+ self._application = None
+ self._bot = None
+ self._token = None
+ self._connected = False
+ self._polling_task = None
+
+ # Broadcast disconnected status
+ await self._broadcast_status()
+
+ logger.info("[Telegram] Disconnected")
+ return {"success": True, "message": "Disconnected"}
+
+ except Exception as e:
+ logger.error(f"[Telegram] Disconnect error: {e}")
+ return {"success": False, "error": str(e)}
+
+ async def _run_polling(self):
+ """Run polling loop in background."""
+ try:
+ logger.info("[Telegram] Starting polling loop...")
+ await self._application.start()
+ await self._application.updater.start_polling(
+ drop_pending_updates=True,
+ allowed_updates=Update.ALL_TYPES,
+ )
+
+ # Keep running until cancelled
+ while True:
+ await asyncio.sleep(1)
+
+ except asyncio.CancelledError:
+ logger.info("[Telegram] Polling cancelled")
+ raise
+ except Exception as e:
+ logger.error(f"[Telegram] Polling error: {e}")
+ self._connected = False
+ await self._broadcast_status()
+
+ async def _on_message_received(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
+ """Handle incoming messages and dispatch to event_waiter."""
+ try:
+ if not update.message:
+ return
+
+ msg = update.message
+ event_data = self._format_message(msg)
+
+ logger.debug(f"[Telegram] Message received: {event_data.get('content_type')} from {event_data.get('from_username', event_data.get('from_id'))}")
+
+ # Dispatch to event_waiter for trigger nodes
+ from services import event_waiter
+ event_waiter.dispatch("telegram_message_received", event_data)
+
+ except Exception as e:
+ logger.error(f"[Telegram] Message handler error: {e}")
+
+ def _format_message(self, msg) -> Dict[str, Any]:
+ """Format Telegram message to unified event data."""
+ # Determine content type
+ content_type = "text"
+ if msg.photo:
+ content_type = "photo"
+ elif msg.video:
+ content_type = "video"
+ elif msg.audio:
+ content_type = "audio"
+ elif msg.voice:
+ content_type = "voice"
+ elif msg.document:
+ content_type = "document"
+ elif msg.sticker:
+ content_type = "sticker"
+ elif msg.location:
+ content_type = "location"
+ elif msg.contact:
+ content_type = "contact"
+ elif msg.poll:
+ content_type = "poll"
+
+ # Build event data
+ data = {
+ "message_id": msg.message_id,
+ "chat_id": msg.chat.id,
+ "chat_type": msg.chat.type, # private, group, supergroup, channel
+ "chat_title": msg.chat.title,
+ "from_id": msg.from_user.id if msg.from_user else None,
+ "from_username": msg.from_user.username if msg.from_user else None,
+ "from_first_name": msg.from_user.first_name if msg.from_user else None,
+ "from_last_name": msg.from_user.last_name if msg.from_user else None,
+ "is_bot": msg.from_user.is_bot if msg.from_user else False,
+ "text": msg.text or msg.caption or "",
+ "content_type": content_type,
+ "date": msg.date.isoformat() if msg.date else datetime.now().isoformat(),
+ "reply_to_message_id": msg.reply_to_message.message_id if msg.reply_to_message else None,
+ }
+
+ # Add media info if present
+ if msg.photo:
+ # Get largest photo
+ photo = msg.photo[-1]
+ data["photo"] = {
+ "file_id": photo.file_id,
+ "file_unique_id": photo.file_unique_id,
+ "width": photo.width,
+ "height": photo.height,
+ "file_size": photo.file_size,
+ }
+ elif msg.document:
+ data["document"] = {
+ "file_id": msg.document.file_id,
+ "file_name": msg.document.file_name,
+ "mime_type": msg.document.mime_type,
+ "file_size": msg.document.file_size,
+ }
+ elif msg.location:
+ data["location"] = {
+ "latitude": msg.location.latitude,
+ "longitude": msg.location.longitude,
+ }
+ elif msg.contact:
+ data["contact"] = {
+ "phone_number": msg.contact.phone_number,
+ "first_name": msg.contact.first_name,
+ "last_name": msg.contact.last_name,
+ "user_id": msg.contact.user_id,
+ }
+
+ return data
+
+ async def _broadcast_status(self):
+ """Broadcast connection status to all WebSocket clients."""
+ try:
+ from services.status_broadcaster import get_status_broadcaster
+ broadcaster = get_status_broadcaster()
+ await broadcaster.update_telegram_status(
+ connected=self._connected,
+ bot_id=self._bot_info.get("id"),
+ bot_username=self._bot_info.get("username"),
+ bot_name=self._bot_info.get("first_name"),
+ )
+ except Exception as e:
+ logger.warning(f"[Telegram] Status broadcast failed: {e}")
+
+ # =========================================================================
+ # Send Methods
+ # =========================================================================
+
+ async def send_message(
+ self,
+ chat_id: str | int,
+ text: str,
+ parse_mode: Optional[str] = None,
+ disable_notification: bool = False,
+ reply_to_message_id: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ """Send a text message.
+
+ Args:
+ chat_id: Chat ID or @username
+ text: Message text
+ parse_mode: 'HTML', 'Markdown', or 'MarkdownV2'
+ disable_notification: Send silently
+ reply_to_message_id: Reply to this message
+
+ Returns:
+ Sent message info
+ """
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+
+ msg = await self._bot.send_message(
+ chat_id=chat_id,
+ text=text,
+ parse_mode=parse_mode if parse_mode else None,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
+
+ return {
+ "message_id": msg.message_id,
+ "chat_id": msg.chat.id,
+ "date": msg.date.isoformat(),
+ "text": msg.text,
+ }
+
+ async def send_photo(
+ self,
+ chat_id: str | int,
+ photo: str,
+ caption: Optional[str] = None,
+ parse_mode: Optional[str] = None,
+ disable_notification: bool = False,
+ reply_to_message_id: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ """Send a photo.
+
+ Args:
+ chat_id: Chat ID or @username
+ photo: URL or file_id
+ caption: Photo caption
+ parse_mode: Caption parse mode
+ disable_notification: Send silently
+ reply_to_message_id: Reply to this message
+
+ Returns:
+ Sent message info
+ """
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+
+ msg = await self._bot.send_photo(
+ chat_id=chat_id,
+ photo=photo,
+ caption=caption,
+ parse_mode=parse_mode if parse_mode else None,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
+
+ return {
+ "message_id": msg.message_id,
+ "chat_id": msg.chat.id,
+ "date": msg.date.isoformat(),
+ }
+
+ async def send_document(
+ self,
+ chat_id: str | int,
+ document: str,
+ caption: Optional[str] = None,
+ parse_mode: Optional[str] = None,
+ disable_notification: bool = False,
+ reply_to_message_id: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ """Send a document.
+
+ Args:
+ chat_id: Chat ID or @username
+ document: URL or file_id
+ caption: Document caption
+ parse_mode: Caption parse mode
+ disable_notification: Send silently
+ reply_to_message_id: Reply to this message
+
+ Returns:
+ Sent message info
+ """
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+
+ msg = await self._bot.send_document(
+ chat_id=chat_id,
+ document=document,
+ caption=caption,
+ parse_mode=parse_mode if parse_mode else None,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
+
+ return {
+ "message_id": msg.message_id,
+ "chat_id": msg.chat.id,
+ "date": msg.date.isoformat(),
+ }
+
+ async def send_location(
+ self,
+ chat_id: str | int,
+ latitude: float,
+ longitude: float,
+ disable_notification: bool = False,
+ reply_to_message_id: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ """Send a location.
+
+ Args:
+ chat_id: Chat ID or @username
+ latitude: Latitude
+ longitude: Longitude
+ disable_notification: Send silently
+ reply_to_message_id: Reply to this message
+
+ Returns:
+ Sent message info
+ """
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+
+ msg = await self._bot.send_location(
+ chat_id=chat_id,
+ latitude=latitude,
+ longitude=longitude,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
+
+ return {
+ "message_id": msg.message_id,
+ "chat_id": msg.chat.id,
+ "date": msg.date.isoformat(),
+ }
+
+ async def send_contact(
+ self,
+ chat_id: str | int,
+ phone_number: str,
+ first_name: str,
+ last_name: Optional[str] = None,
+ disable_notification: bool = False,
+ reply_to_message_id: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ """Send a contact.
+
+ Args:
+ chat_id: Chat ID or @username
+ phone_number: Contact phone number
+ first_name: Contact first name
+ last_name: Contact last name
+ disable_notification: Send silently
+ reply_to_message_id: Reply to this message
+
+ Returns:
+ Sent message info
+ """
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+
+ msg = await self._bot.send_contact(
+ chat_id=chat_id,
+ phone_number=phone_number,
+ first_name=first_name,
+ last_name=last_name,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
+
+ return {
+ "message_id": msg.message_id,
+ "chat_id": msg.chat.id,
+ "date": msg.date.isoformat(),
+ }
+
+ async def get_me(self) -> Dict[str, Any]:
+ """Get bot info."""
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+
+ me = await self._bot.get_me()
+ return {
+ "id": me.id,
+ "username": me.username,
+ "first_name": me.first_name,
+ "can_join_groups": me.can_join_groups,
+ }
+
+ async def get_chat(self, chat_id: str | int) -> Dict[str, Any]:
+ """Get chat info.
+
+ Args:
+ chat_id: Chat ID or @username
+
+ Returns:
+ Chat info
+ """
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+
+ chat = await self._bot.get_chat(chat_id)
+ return {
+ "id": chat.id,
+ "type": chat.type,
+ "title": chat.title,
+ "username": chat.username,
+ "first_name": chat.first_name,
+ "last_name": chat.last_name,
+ "description": chat.description,
+ }
+
+
+def get_telegram_service() -> TelegramService:
+ """Get TelegramService singleton instance."""
+ return TelegramService.get_instance()