Skip to content

Commit 47d3cbe

Browse files
aadamgoughAdam Gough
andauthored
feat(telegram): added telegram webhook, block, tools, & docs (#314)
* jira and confluence token refresh * telegram message tool * webhook configured * telegram requires permanent url * webhook working * telegram done * test * telegram webhook working * package-lock.json * style curl command * added setWebhook logic * added some documentation for chat ID * styling changes * added delete webhook logic * adding docs * updated docs for jira and telegram * added links * moved function to other route.ts * logger * mrge.io changes --------- Co-authored-by: Adam Gough <adamgough@Adams-MacBook-Pro.local>
1 parent ca34c72 commit 47d3cbe

18 files changed

Lines changed: 795 additions & 14 deletions

File tree

docs/content/docs/tools/jira.mdx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,19 @@ import { BlockInfoCard } from "@/components/ui/block-info-card"
2525
</svg>`}
2626
/>
2727

28+
[Jira](https://www.atlassian.com/jira) is a leading project management and issue tracking platform that helps teams plan, track, and manage agile software development projects effectively. As part of the Atlassian suite, Jira has become the industry standard for software development teams and project management professionals worldwide.
29+
30+
Jira provides a comprehensive set of tools for managing complex projects through its flexible and customizable workflow system. With its robust API and integration capabilities, Jira enables teams to streamline their development processes and maintain clear visibility of project progress.
31+
32+
Key features of Jira include:
33+
34+
- Agile Project Management: Support for Scrum and Kanban methodologies with customizable boards and workflows
35+
- Issue Tracking: Sophisticated tracking system for bugs, stories, epics, and tasks with detailed reporting
36+
- Workflow Automation: Powerful automation rules to streamline repetitive tasks and processes
37+
- Advanced Search: JQL (Jira Query Language) for complex issue filtering and reporting
38+
39+
In Sim Studio, the Jira integration allows your agents to seamlessly interact with your project management workflow. This creates opportunities for automated issue creation, updates, and tracking as part of your AI workflows. The integration enables agents to create, retrieve, and update Jira issues programmatically, facilitating automated project management tasks and ensuring that important information is properly tracked and documented. By connecting Sim Studio with Jira, you can build intelligent agents that maintain project visibility while automating routine project management tasks, enhancing team productivity and ensuring consistent project tracking.
40+
2841
## Usage Instructions
2942

3043
Connect to Jira workspaces to read, write, and update issues. Access content, metadata, and integrate Jira documentation into your workflows.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
---
2+
title: Telegram
3+
description: Send a message through Telegram
4+
---
5+
6+
import { BlockInfoCard } from "@/components/ui/block-info-card"
7+
8+
<BlockInfoCard
9+
type="telegram"
10+
color="#E0E0E0"
11+
icon={true}
12+
iconSvg={`<svg className="block-icon"
13+
14+
15+
16+
viewBox="-5 0 41 33"
17+
fill="none"
18+
xmlns="http://www.w3.org/2000/svg"
19+
>
20+
<circle cx="16" cy="16" r="14" fill="url(#paint0_linear_87_7225)"/>
21+
<path
22+
d="M22.9866 10.2088C23.1112 9.40332 22.3454 8.76755 21.6292 9.082L7.36482 15.3448C6.85123 15.5703 6.8888 16.3483 7.42147 16.5179L10.3631 17.4547C10.9246 17.6335 11.5325 17.541 12.0228 17.2023L18.655 12.6203C18.855 12.4821 19.073 12.7665 18.9021 12.9426L14.1281 17.8646C13.665 18.3421 13.7569 19.1512 14.314 19.5005L19.659 22.8523C20.2585 23.2282 21.0297 22.8506 21.1418 22.1261L22.9866 10.2088Z"
23+
fill="white"/>
24+
<defs>
25+
<linearGradient id="paint0_linear_87_7225" x1="16" y1="2" x2="16" y2="30"
26+
gradientUnits="userSpaceOnUse">
27+
<stop stopColor="#37BBFE"/>
28+
<stop offset="1" stopColor="#007DBB"/>
29+
</linearGradient>
30+
</defs>
31+
</svg>`}
32+
/>
33+
34+
[Telegram](https://telegram.org) is a secure, cloud-based messaging platform that enables fast and reliable communication across devices and platforms. With over 700 million monthly active users, Telegram has established itself as one of the world's leading messaging services, known for its security, speed, and powerful API capabilities.
35+
36+
<iframe width="100%" height="400" src="https://www.youtube.com/embed/nhq2Q8fndFg?start=62" title="Use Telegram with Sim Studio" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen ></iframe>
37+
38+
Telegram's Bot API provides a robust framework for creating automated messaging solutions and integrating communication features into applications. With support for rich media, inline keyboards, and custom commands, Telegram bots can facilitate sophisticated interaction patterns and automated workflows.
39+
40+
Key features of Telegram include:
41+
42+
- Secure Communication: End-to-end encryption and secure cloud storage for messages and media
43+
- Bot Platform: Powerful bot API for creating automated messaging solutions and interactive experiences
44+
- Rich Media Support: Send and receive messages with text formatting, images, files, and interactive elements
45+
- Global Reach: Connect with users worldwide with support for multiple languages and platforms
46+
47+
In Sim Studio, the Telegram integration enables your agents to leverage these powerful messaging capabilities as part of their workflows. This creates opportunities for automated notifications, alerts, and interactive conversations through Telegram's secure messaging platform. The integration allows agents to send messages programmatically to individuals or channels, enabling timely communication and updates. By connecting Sim Studio with Telegram, you can build intelligent agents that engage users through a secure and widely-adopted messaging platform, perfect for delivering notifications, updates, and interactive communications.
48+
49+
## Usage Instructions
50+
51+
Send messages to any Telegram channel using your Bot API key. Integrate automated notifications and alerts into your workflow to keep your team informed.
52+
53+
54+
55+
## Tools
56+
57+
### `telegram_message`
58+
59+
Send messages to Telegram channels or users through the Telegram Bot API. Enables direct communication and notifications with message tracking and chat confirmation.
60+
61+
#### Input
62+
63+
| Parameter | Type | Required | Description |
64+
| --------- | ---- | -------- | ----------- |
65+
| `botToken` | string | Yes | Your Telegram Bot API Token |
66+
| `chatId` | string | Yes | Target Telegram chat ID |
67+
| `text` | string | Yes | Message text to send |
68+
69+
#### Output
70+
71+
| Parameter | Type |
72+
| --------- | ---- |
73+
| `ok` | string |
74+
| `date` | string |
75+
76+
77+
78+
## Block Configuration
79+
80+
### Input
81+
82+
| Parameter | Type | Required | Description |
83+
| --------- | ---- | -------- | ----------- |
84+
| `botToken` | string | Yes | Bot Token - Enter your Telegram Bot Token |
85+
86+
87+
88+
### Outputs
89+
90+
| Output | Type | Description |
91+
| ------ | ---- | ----------- |
92+
| `response` | object | Output from response |
93+
|`ok` | boolean | ok of the response |
94+
|`result` | json | result of the response |
95+
96+
97+
## Notes
98+
99+
- Category: `tools`
100+
- Type: `telegram`

sim/app/api/webhooks/[id]/route.ts

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,13 +160,70 @@ export async function DELETE(
160160
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
161161
}
162162

163-
// Delete the webhook
163+
const foundWebhook = webhooks[0].webhook
164+
165+
// If it's a Telegram webhook, delete it from Telegram first
166+
if (foundWebhook.provider === 'telegram') {
167+
try {
168+
const { botToken } = foundWebhook.providerConfig as { botToken: string }
169+
170+
if (!botToken) {
171+
logger.warn(`[${requestId}] Missing botToken for Telegram webhook deletion.`, {
172+
webhookId: id,
173+
})
174+
return NextResponse.json(
175+
{ error: 'Missing botToken for Telegram webhook deletion' },
176+
{ status: 400 }
177+
)
178+
}
179+
180+
const telegramApiUrl = `https://api.telegram.org/bot${botToken}/deleteWebhook`
181+
const telegramResponse = await fetch(telegramApiUrl, {
182+
method: 'POST',
183+
headers: {
184+
'Content-Type': 'application/json',
185+
}
186+
})
187+
188+
const responseBody = await telegramResponse.json()
189+
if (!telegramResponse.ok || !responseBody.ok) {
190+
const errorMessage = responseBody.description || `Failed to delete Telegram webhook. Status: ${telegramResponse.status}`
191+
logger.error(`[${requestId}] ${errorMessage}`, {
192+
response: responseBody
193+
})
194+
return NextResponse.json(
195+
{ error: 'Failed to delete webhook from Telegram', details: errorMessage },
196+
{ status: 500 }
197+
)
198+
}
199+
200+
logger.info(`[${requestId}] Successfully deleted Telegram webhook for webhook ${id}`)
201+
} catch (error: any) {
202+
logger.error(`[${requestId}] Error deleting Telegram webhook`, {
203+
webhookId: id,
204+
error: error.message,
205+
stack: error.stack,
206+
})
207+
return NextResponse.json(
208+
{
209+
error: 'Failed to delete webhook from Telegram',
210+
details: error.message
211+
},
212+
{ status: 500 }
213+
)
214+
}
215+
}
216+
217+
// Delete the webhook from the database
164218
await db.delete(webhook).where(eq(webhook.id, id))
165219

166220
logger.info(`[${requestId}] Successfully deleted webhook: ${id}`)
167221
return NextResponse.json({ success: true }, { status: 200 })
168-
} catch (error) {
169-
logger.error(`[${requestId}] Error deleting webhook`, error)
222+
} catch (error: any) {
223+
logger.error(`[${requestId}] Error deleting webhook`, {
224+
error: error.message,
225+
stack: error.stack
226+
})
170227
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
171228
}
172229
}

sim/app/api/webhooks/route.ts

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,26 @@ export async function POST(request: NextRequest) {
162162
}
163163
// --- End Airtable specific logic ---
164164

165+
// --- Attempt to create webhook in Telegram if provider is 'telegram' ---
166+
if (savedWebhook && provider === 'telegram') {
167+
logger.info(
168+
`[${requestId}] Telegram provider detected. Attempting to create webhook in Telegram.`
169+
)
170+
try {
171+
await createTelegramWebhookSubscription(request, userId, savedWebhook, requestId)
172+
} catch (err) {
173+
logger.error(`[${requestId}] Error creating Telegram webhook`, err)
174+
return NextResponse.json(
175+
{
176+
error: 'Failed to create webhook in Telegram',
177+
details: err instanceof Error ? err.message : 'Unknown error',
178+
},
179+
{ status: 500 }
180+
)
181+
}
182+
}
183+
// --- End Telegram specific logic ---
184+
165185
const status = existingWebhooks.length > 0 ? 200 : 201
166186
return NextResponse.json({ webhook: savedWebhook }, { status })
167187
} catch (error: any) {
@@ -289,3 +309,72 @@ async function createAirtableWebhookSubscription(
289309
)
290310
}
291311
}
312+
313+
// Helper function to create the webhook subscription in Telegram
314+
async function createTelegramWebhookSubscription(
315+
request: NextRequest,
316+
userId: string,
317+
webhookData: any,
318+
requestId: string
319+
) {
320+
try {
321+
const { path, providerConfig } = webhookData
322+
const { botToken, triggerPhrase } = providerConfig || {}
323+
324+
if (!botToken || !triggerPhrase) {
325+
logger.warn(`[${requestId}] Missing botToken or triggerPhrase for Telegram webhook creation.`, {
326+
webhookId: webhookData.id,
327+
})
328+
return // Cannot proceed without botToken and triggerPhrase
329+
}
330+
331+
const requestOrigin = new URL(request.url).origin
332+
// Ensure origin does not point to localhost for external API calls
333+
const effectiveOrigin = requestOrigin.includes('localhost')
334+
? process.env.NEXT_PUBLIC_APP_URL || requestOrigin // Use env var if available, fallback to original
335+
: requestOrigin
336+
337+
const notificationUrl = `${effectiveOrigin}/api/webhooks/trigger/${path}`
338+
if (effectiveOrigin !== requestOrigin) {
339+
logger.debug(
340+
`[${requestId}] Remapped localhost origin to ${effectiveOrigin} for notificationUrl`
341+
)
342+
}
343+
344+
const telegramApiUrl = `https://api.telegram.org/bot${botToken}/setWebhook`
345+
346+
const requestBody: any = {
347+
url: notificationUrl,
348+
allowed_updates: ['message'],
349+
}
350+
351+
const telegramResponse = await fetch(telegramApiUrl, {
352+
method: 'POST',
353+
headers: {
354+
'Content-Type': 'application/json',
355+
},
356+
body: JSON.stringify(requestBody),
357+
})
358+
359+
const responseBody = await telegramResponse.json()
360+
if (!telegramResponse.ok || !responseBody.ok) {
361+
const errorMessage = responseBody.description || `Failed to create Telegram webhook. Status: ${telegramResponse.status}`
362+
logger.error(`[${requestId}] ${errorMessage}`, {
363+
response: responseBody
364+
})
365+
throw new Error(errorMessage)
366+
}
367+
368+
logger.info(
369+
`[${requestId}] Successfully created Telegram webhook for webhook ${webhookData.id}.`
370+
)
371+
} catch (error: any) {
372+
logger.error(
373+
`[${requestId}] Exception during Telegram webhook creation for webhook ${webhookData.id}.`,
374+
{
375+
message: error.message,
376+
stack: error.stack,
377+
}
378+
)
379+
}
380+
}

0 commit comments

Comments
 (0)