1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219from __future__ import annotations
import time
from collections.abc import Mapping
from typing import Any
import requests
from werkzeug import Request, Response
from dify_plugin.entities.provider_config import CredentialType
from dify_plugin.entities.trigger import EventDispatch, Subscription, UnsubscribeResult
from dify_plugin.errors.trigger import (
SubscriptionError,
TriggerDispatchError,
TriggerProviderCredentialValidationError,
TriggerValidationError,
UnsubscribeError,
)
from dify_plugin.interfaces.trigger import Trigger, TriggerSubscriptionConstructor
class TelegramTrigger(Trigger):
"""Handle Telegram webhook event dispatch."""
def _dispatch_event(self, subscription: Subscription, request: Request) -> EventDispatch:
secret_token = subscription.properties.get("secret_token")
if secret_token:
self._validate_secret_token(request=request, secret_token=secret_token)
payload: Mapping[str, Any] = self._validate_payload(request)
response = Response(response='{"ok": true}', status=200, mimetype="application/json")
events = self._determine_events(payload)
return EventDispatch(events=events, response=response)
def _determine_events(self, payload: Mapping[str, Any]) -> list[str]:
"""Determine which events should be triggered based on the update payload."""
events = []
# Check for text message
if "message" in payload:
message = payload["message"]
if "text" in message:
text = message["text"]
# Check if it's a command
if text.startswith("/"):
events.append("command")
else:
events.append("text_message")
# Check for callback query
if "callback_query" in payload:
events.append("callback_query")
return events
def _validate_payload(self, request: Request) -> Mapping[str, Any]:
try:
payload = request.get_json(force=True)
if not payload:
raise TriggerDispatchError("Empty request body")
return payload
except TriggerDispatchError:
raise
except Exception as exc:
raise TriggerDispatchError(f"Failed to parse payload: {exc}") from exc
def _validate_secret_token(self, request: Request, secret_token: str) -> None:
"""Validate Telegram webhook secret token."""
header_token = request.headers.get("X-Telegram-Bot-Api-Secret-Token")
if not header_token:
raise TriggerValidationError("Missing secret token header")
if header_token != secret_token:
raise TriggerValidationError("Invalid secret token")
class TelegramSubscriptionConstructor(TriggerSubscriptionConstructor):
"""Manage Telegram trigger subscriptions."""
_API_BASE_URL = "https://api.telegram.org/bot{token}"
_WEBHOOK_TTL = 365 * 24 * 60 * 60 # 1 year (Telegram webhooks don't expire)
def _validate_api_key(self, credentials: Mapping[str, Any]) -> None:
bot_token = credentials.get("bot_token")
if not bot_token:
raise TriggerProviderCredentialValidationError("Telegram Bot Token is required.")
url = self._API_BASE_URL.format(token=bot_token) + "/getMe"
try:
response = requests.get(url, timeout=10)
if response.status_code != 200:
error_data = response.json()
raise TriggerProviderCredentialValidationError(
error_data.get("description", "Invalid Bot Token")
)
except TriggerProviderCredentialValidationError:
raise
except Exception as exc:
raise TriggerProviderCredentialValidationError(str(exc)) from exc
def _create_subscription(
self,
endpoint: str,
parameters: Mapping[str, Any],
credentials: Mapping[str, Any],
credential_type: CredentialType,
) -> Subscription:
bot_token = credentials.get("bot_token")
if not bot_token:
raise ValueError("bot_token is required")
allowed_updates: list[str] = parameters.get("allowed_updates", ["message", "callback_query"])
secret_token = parameters.get("secret_token", "")
url = self._API_BASE_URL.format(token=bot_token) + "/setWebhook"
webhook_data = {
"url": endpoint,
"allowed_updates": allowed_updates,
"drop_pending_updates": False,
"max_connections": 40,
}
# Add secret token if provided
if secret_token:
webhook_data["secret_token"] = secret_token
try:
response = requests.post(url, json=webhook_data, timeout=10)
except requests.RequestException as exc:
raise SubscriptionError(
f"Network error while creating webhook: {exc}",
error_code="NETWORK_ERROR"
) from exc
if response.status_code == 200:
result = response.json()
if result.get("ok"):
return Subscription(
expires_at=int(time.time()) + self._WEBHOOK_TTL,
endpoint=endpoint,
parameters=parameters,
properties={
"bot_token": bot_token,
"allowed_updates": allowed_updates,
"secret_token": secret_token,
"webhook_url": endpoint,
},
)
else:
raise SubscriptionError(
f"Failed to set webhook: {result.get('description', 'Unknown error')}",
error_code="WEBHOOK_CREATION_FAILED",
external_response=result,
)
response_data: dict[str, Any] = response.json() if response.content else {}
error_msg = response_data.get("description", "Unknown error")
raise SubscriptionError(
f"Failed to create Telegram webhook: {error_msg}",
error_code="WEBHOOK_CREATION_FAILED",
external_response=response_data,
)
def _delete_subscription(
self, subscription: Subscription, credentials: Mapping[str, Any], credential_type: CredentialType
) -> UnsubscribeResult:
bot_token = credentials.get("bot_token")
if not bot_token:
raise UnsubscribeError(
message="Missing bot token",
error_code="MISSING_CREDENTIALS",
external_response=None,
)
url = self._API_BASE_URL.format(token=bot_token) + "/deleteWebhook"
try:
response = requests.post(url, json={"drop_pending_updates": False}, timeout=10)
except requests.RequestException as exc:
raise UnsubscribeError(
message=f"Network error while deleting webhook: {exc}",
error_code="NETWORK_ERROR",
external_response=None,
) from exc
if response.status_code == 200:
result = response.json()
if result.get("ok"):
return UnsubscribeResult(
success=True,
message="Successfully removed Telegram webhook"
)
else:
raise UnsubscribeError(
message=f"Failed to delete webhook: {result.get('description', 'Unknown error')}",
error_code="WEBHOOK_DELETION_FAILED",
external_response=result,
)
raise UnsubscribeError(
message=f"Failed to delete webhook: HTTP {response.status_code}",
error_code="WEBHOOK_DELETION_FAILED",
external_response=response.json() if response.content else None,
)
def _refresh_subscription(
self, subscription: Subscription, credentials: Mapping[str, Any], credential_type: CredentialType
) -> Subscription:
"""Telegram webhooks don't expire, so just extend the TTL."""
return Subscription(
expires_at=int(time.time()) + self._WEBHOOK_TTL,
endpoint=subscription.endpoint,
parameters=subscription.parameters,
properties=subscription.properties,
)