Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(integrations): add project telegram integration

Tin63ff1a925cfc
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index cbaa8cd2e..6510dd333 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -37,6 +37,7 @@ import slackIntegration from "./slack-integration";
import { getPrivateObject } from "./storage/s3";
import task from "./task";
import taskRelation from "./task-relation";
+import telegramIntegration from "./telegram-integration";
import timeEntry from "./time-entry";
import { getInvitationDetails } from "./utils/check-registration-allowed";
import { migrateApiKeyReferenceId } from "./utils/migrate-apikey-reference-id";
@@ -407,6 +408,10 @@ const discordIntegrationApi = api.route(
discordIntegration,
);
const slackIntegrationApi = api.route("/slack-integration", slackIntegration);
+const telegramIntegrationApi = api.route(
+ "/telegram-integration",
+ telegramIntegration,
+);
const taskRelationApi = api.route("/task-relation", taskRelation);
const externalLinkApi = api.route("/external-link", externalLink);
const workflowRuleApi = api.route("/workflow-rule", workflowRule);
@@ -464,6 +469,7 @@ export type AppType =
| typeof genericWebhookIntegrationApi
| typeof discordIntegrationApi
| typeof slackIntegrationApi
+ | typeof telegramIntegrationApi
| typeof taskRelationApi
| typeof externalLinkApi
| typeof workflowRuleApi
diff --git a/apps/api/src/plugins/index.ts b/apps/api/src/plugins/index.ts
index 195b94ddf..16f5f34ce 100644
--- a/apps/api/src/plugins/index.ts
+++ b/apps/api/src/plugins/index.ts
@@ -3,6 +3,7 @@ import { genericWebhookPlugin } from "./generic-webhook";
import { githubPlugin, initializeGitHubPlugin } from "./github";
import { initializeEventSubscriptions, registerPlugin } from "./registry";
import { slackPlugin } from "./slack";
+import { telegramPlugin } from "./telegram";
export function initializePlugins() {
console.log("Initializing plugins...");
@@ -11,6 +12,7 @@ export function initializePlugins() {
registerPlugin(slackPlugin);
registerPlugin(discordPlugin);
registerPlugin(genericWebhookPlugin);
+ registerPlugin(telegramPlugin);
initializeGitHubPlugin();
initializeEventSubscriptions();
diff --git a/apps/api/src/plugins/telegram/client.ts b/apps/api/src/plugins/telegram/client.ts
new file mode 100644
index 000000000..3824f5660
--- /dev/null
+++ b/apps/api/src/plugins/telegram/client.ts
@@ -0,0 +1,57 @@
+type TelegramMessage = {
+ chat_id: string;
+ text: string;
+ parse_mode?: "HTML";
+ disable_web_page_preview?: boolean;
+ message_thread_id?: number;
+};
+
+const TELEGRAM_TIMEOUT_MS = 10_000;
+
+export async function postToTelegram(
+ botToken: string,
+ message: TelegramMessage,
+): Promise<void> {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), TELEGRAM_TIMEOUT_MS);
+
+ try {
+ const response = await fetch(
+ `https://api.telegram.org/bot${botToken}/sendMessage`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(message),
+ signal: controller.signal,
+ },
+ );
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(
+ `Telegram request failed (${response.status}): ${errorText}`,
+ );
+ }
+
+ const result = (await response.json()) as {
+ ok?: boolean;
+ description?: string;
+ };
+
+ if (!result.ok) {
+ throw new Error(result.description || "Telegram API request failed");
+ }
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ throw new Error(
+ `Telegram request timed out after ${TELEGRAM_TIMEOUT_MS}ms`,
+ );
+ }
+
+ throw error;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+}
diff --git a/apps/api/src/plugins/telegram/config.ts b/apps/api/src/plugins/telegram/config.ts
new file mode 100644
index 000000000..2734f8892
--- /dev/null
+++ b/apps/api/src/plugins/telegram/config.ts
@@ -0,0 +1,90 @@
+import * as v from "valibot";
+
+export const telegramEventKeys = [
+ "taskCreated",
+ "taskStatusChanged",
+ "taskPriorityChanged",
+ "taskTitleChanged",
+ "taskDescriptionChanged",
+ "taskCommentCreated",
+] as const;
+
+export type TelegramEventKey = (typeof telegramEventKeys)[number];
+
+const telegramBotTokenSchema = v.pipe(
+ v.string(),
+ v.regex(/^\d+:[A-Za-z0-9_-]{20,}$/, "Enter a valid Telegram bot token"),
+);
+
+const telegramChatIdSchema = v.pipe(
+ v.string(),
+ v.minLength(1, "Chat ID is required"),
+);
+
+export const telegramConfigSchema = v.object({
+ botToken: telegramBotTokenSchema,
+ chatId: telegramChatIdSchema,
+ threadId: v.optional(v.number()),
+ chatLabel: v.optional(v.string()),
+ events: v.optional(
+ v.object({
+ taskCreated: v.optional(v.boolean()),
+ taskStatusChanged: v.optional(v.boolean()),
+ taskPriorityChanged: v.optional(v.boolean()),
+ taskTitleChanged: v.optional(v.boolean()),
+ taskDescriptionChanged: v.optional(v.boolean()),
+ taskCommentCreated: v.optional(v.boolean()),
+ }),
+ ),
+});
+
+export type TelegramConfig = v.InferOutput<typeof telegramConfigSchema>;
+
+export const defaultTelegramEvents: Record<TelegramEventKey, boolean> = {
+ taskCreated: true,
+ taskStatusChanged: true,
+ taskPriorityChanged: false,
+ taskTitleChanged: false,
+ taskDescriptionChanged: false,
+ taskCommentCreated: true,
+};
+
+export function normalizeTelegramConfig(
+ config: TelegramConfig,
+): TelegramConfig {
+ return {
+ ...config,
+ chatId: config.chatId.trim(),
+ threadId:
+ typeof config.threadId === "number" && Number.isFinite(config.threadId)
+ ? config.threadId
+ : undefined,
+ chatLabel: config.chatLabel?.trim() || undefined,
+ events: {
+ ...defaultTelegramEvents,
+ ...(config.events ?? {}),
+ },
+ };
+}
+
+export async function validateTelegramConfig(
+ config: unknown,
+): Promise<{ valid: boolean; errors?: string[] }> {
+ try {
+ const parsed = v.parse(telegramConfigSchema, config);
+ normalizeTelegramConfig(parsed);
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof v.ValiError) {
+ return {
+ valid: false,
+ errors: error.issues.map((issue) => issue.message),
+ };
+ }
+
+ return {
+ valid: false,
+ errors: [error instanceof Error ? error.message : "Invalid config"],
+ };
+ }
+}
diff --git a/apps/api/src/plugins/telegram/events.ts b/apps/api/src/plugins/telegram/events.ts
new file mode 100644
index 000000000..266242060
--- /dev/null
+++ b/apps/api/src/plugins/telegram/events.ts
@@ -0,0 +1,249 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../database";
+import {
+ projectTable,
+ taskTable,
+ userTable,
+ workspaceTable,
+} from "../../database/schema";
+import type {
+ PluginContext,
+ TaskCommentCreatedEvent,
+ TaskCreatedEvent,
+ TaskDescriptionChangedEvent,
+ TaskPriorityChangedEvent,
+ TaskStatusChangedEvent,
+ TaskTitleChangedEvent,
+} from "../types";
+import { postToTelegram } from "./client";
+import type { TelegramConfig, TelegramEventKey } from "./config";
+import { normalizeTelegramConfig } from "./config";
+
+type TelegramEventData = {
+ taskTitle: string;
+ taskNumber: number | null;
+ projectName: string;
+ taskUrl: string | null;
+ actorName: string | null;
+ status: string | null;
+ priority: string | null;
+};
+
+function isEnabled(config: TelegramConfig, key: TelegramEventKey): boolean {
+ return config.events?.[key] ?? false;
+}
+
+function toSentenceCase(value: string | null): string {
+ if (!value) return "Unknown";
+ return value
+ .replace(/[-_]+/g, " ")
+ .replace(/\b\w/g, (char) => char.toUpperCase());
+}
+
+function truncate(value: string, maxLength: number): string {
+ if (value.length <= maxLength) {
+ return value;
+ }
+
+ return `${value.slice(0, maxLength - 1)}…`;
+}
+
+function escapeHtml(value: string): string {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;");
+}
+
+function redactBotToken(botToken: string): string {
+ const [prefix, suffix = ""] = botToken.split(":", 2);
+ if (!suffix) {
+ return "redacted";
+ }
+
+ return `${prefix}:${
+ suffix.length > 8 ? `${suffix.slice(0, 4)}…${suffix.slice(-4)}` : "••••"
+ }`;
+}
+
+async function getTelegramEventData(
+ taskId: string,
+ projectId: string,
+ userId: string | null,
+): Promise<TelegramEventData | null> {
+ const taskPromise = db
+ .select({
+ title: taskTable.title,
+ number: taskTable.number,
+ status: taskTable.status,
+ priority: taskTable.priority,
+ projectName: projectTable.name,
+ projectId: projectTable.id,
+ workspaceId: workspaceTable.id,
+ })
+ .from(taskTable)
+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
+ .innerJoin(workspaceTable, eq(projectTable.workspaceId, workspaceTable.id))
+ .where(and(eq(taskTable.id, taskId), eq(projectTable.id, projectId)))
+ .limit(1);
+
+ const userPromise = userId
+ ? db
+ .select({ name: userTable.name })
+ .from(userTable)
+ .where(eq(userTable.id, userId))
+ .limit(1)
+ : Promise.resolve([]);
+
+ const [[taskRow], [user]] = await Promise.all([taskPromise, userPromise]);
+
+ if (!taskRow) {
+ return null;
+ }
+
+ const clientUrl = process.env.KANEO_CLIENT_URL || "http://localhost:5173";
+ const taskUrl = `${clientUrl}/dashboard/workspace/${taskRow.workspaceId}/project/${taskRow.projectId}/task/${taskId}`;
+
+ return {
+ taskTitle: taskRow.title,
+ taskNumber: taskRow.number,
+ projectName: taskRow.projectName,
+ taskUrl,
+ actorName: user?.name ?? null,
+ status: taskRow.status,
+ priority: taskRow.priority,
+ };
+}
+
+async function sendTelegramMessage(
+ config: TelegramConfig,
+ title: string,
+ body: string,
+ data: TelegramEventData,
+): Promise<void> {
+ const issueKey =
+ data.taskNumber !== null ? `#${data.taskNumber}` : "Task update";
+ const taskLabel = `${issueKey} ${data.taskTitle}`;
+ const escapedTaskLabel = escapeHtml(taskLabel);
+ const taskLine = data.taskUrl
+ ? `<a href="${escapeHtml(data.taskUrl)}">${escapedTaskLabel}</a>`
+ : escapedTaskLabel;
+
+ const lines = [
+ `<b>${escapeHtml(title)}</b>`,
+ escapeHtml(body),
+ "",
+ `<b>Task:</b> ${taskLine}`,
+ `<b>Project:</b> ${escapeHtml(data.projectName)}`,
+ `<b>Status:</b> ${escapeHtml(toSentenceCase(data.status))}`,
+ `<b>Priority:</b> ${escapeHtml(toSentenceCase(data.priority))}`,
+ `<b>Triggered by:</b> ${escapeHtml(data.actorName ?? "Kaneo")}`,
+ ];
+
+ try {
+ await postToTelegram(config.botToken, {
+ chat_id: config.chatId,
+ text: lines.join("\n"),
+ parse_mode: "HTML",
+ disable_web_page_preview: false,
+ message_thread_id: config.threadId,
+ });
+ } catch (error) {
+ console.error("sendTelegramMessage postToTelegram failed", {
+ error,
+ botToken: redactBotToken(config.botToken),
+ chatId: config.chatId,
+ threadId: config.threadId ?? null,
+ taskUrl: data.taskUrl,
+ });
+ }
+}
+
+type TelegramMessageContent = {
+ title: string;
+ body: string;
+};
+
+async function runTelegramHandler(
+ context: PluginContext,
+ event: {
+ taskId: string;
+ projectId: string;
+ userId: string | null;
+ },
+ featureKey: TelegramEventKey,
+ buildMessage: () => TelegramMessageContent,
+): Promise<void> {
+ const config = normalizeTelegramConfig(context.config as TelegramConfig);
+ if (!isEnabled(config, featureKey)) return;
+
+ const data = await getTelegramEventData(
+ event.taskId,
+ event.projectId,
+ event.userId,
+ );
+ if (!data) return;
+
+ const { title, body } = buildMessage();
+ await sendTelegramMessage(config, title, body, data);
+}
+
+export async function handleTaskCreated(
+ event: TaskCreatedEvent,
+ context: PluginContext,
+): Promise<void> {
+ await runTelegramHandler(context, event, "taskCreated", () => ({
+ title: "New task created",
+ body: `A new task was added: ${event.title}`,
+ }));
+}
+
+export async function handleTaskStatusChanged(
+ event: TaskStatusChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ await runTelegramHandler(context, event, "taskStatusChanged", () => ({
+ title: "Task status changed",
+ body: `${event.title} moved from ${toSentenceCase(event.oldStatus)} to ${toSentenceCase(event.newStatus)}.`,
+ }));
+}
+
+export async function handleTaskPriorityChanged(
+ event: TaskPriorityChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ await runTelegramHandler(context, event, "taskPriorityChanged", () => ({
+ title: "Task priority changed",
+ body: `${event.title} changed from ${toSentenceCase(event.oldPriority)} to ${toSentenceCase(event.newPriority)}.`,
+ }));
+}
+
+export async function handleTaskTitleChanged(
+ event: TaskTitleChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ await runTelegramHandler(context, event, "taskTitleChanged", () => ({
+ title: "Task title changed",
+ body: `Task renamed from ${truncate(event.oldTitle, 120)} to ${truncate(event.newTitle, 120)}.`,
+ }));
+}
+
+export async function handleTaskDescriptionChanged(
+ event: TaskDescriptionChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ await runTelegramHandler(context, event, "taskDescriptionChanged", () => ({
+ title: "Task description changed",
+ body: `The task description was updated${event.newDescription ? `: ${truncate(event.newDescription.replace(/\s+/g, " "), 160)}` : "."}`,
+ }));
+}
+
+export async function handleTaskCommentCreated(
+ event: TaskCommentCreatedEvent,
+ context: PluginContext,
+): Promise<void> {
+ await runTelegramHandler(context, event, "taskCommentCreated", () => ({
+ title: "New task comment",
+ body: truncate(event.comment.replace(/\s+/g, " "), 200),
+ }));
+}
diff --git a/apps/api/src/plugins/telegram/index.ts b/apps/api/src/plugins/telegram/index.ts
new file mode 100644
index 000000000..29b39332b
--- /dev/null
+++ b/apps/api/src/plugins/telegram/index.ts
@@ -0,0 +1,22 @@
+import type { IntegrationPlugin } from "../types";
+import { validateTelegramConfig } from "./config";
+import {
+ handleTaskCommentCreated,
+ handleTaskCreated,
+ handleTaskDescriptionChanged,
+ handleTaskPriorityChanged,
+ handleTaskStatusChanged,
+ handleTaskTitleChanged,
+} from "./events";
+
+export const telegramPlugin: IntegrationPlugin = {
+ type: "telegram",
+ name: "Telegram",
+ onTaskCreated: handleTaskCreated,
+ onTaskStatusChanged: handleTaskStatusChanged,
+ onTaskPriorityChanged: handleTaskPriorityChanged,
+ onTaskTitleChanged: handleTaskTitleChanged,
+ onTaskDescriptionChanged: handleTaskDescriptionChanged,
+ onTaskCommentCreated: handleTaskCommentCreated,
+ validateConfig: validateTelegramConfig,
+};
diff --git a/apps/api/src/schemas.ts b/apps/api/src/schemas.ts
index 486404736..de7f52b5a 100644
--- a/apps/api/src/schemas.ts
+++ b/apps/api/src/schemas.ts
@@ -157,6 +157,20 @@ export const genericWebhookIntegrationSchema = v.object({
updatedAt: v.date(),
});
+export const telegramIntegrationSchema = v.object({
+ id: v.string(),
+ projectId: v.string(),
+ chatId: v.string(),
+ threadId: v.nullable(v.number()),
+ chatLabel: v.nullable(v.string()),
+ botTokenConfigured: v.boolean(),
+ maskedBotToken: v.string(),
+ events: integrationEventsSchema,
+ isActive: v.nullable(v.boolean()),
+ createdAt: v.date(),
+ updatedAt: v.date(),
+});
+
export const commentSchema = v.object({
id: v.string(),
taskId: v.string(),
diff --git a/apps/api/src/telegram-integration/index.ts b/apps/api/src/telegram-integration/index.ts
new file mode 100644
index 000000000..d5d493b15
--- /dev/null
+++ b/apps/api/src/telegram-integration/index.ts
@@ -0,0 +1,315 @@
+import { and, eq } from "drizzle-orm";
+import { Hono } from "hono";
+import { HTTPException } from "hono/http-exception";
+import { describeRoute, resolver, validator } from "hono-openapi";
+import * as v from "valibot";
+import db from "../database";
+import { integrationTable } from "../database/schema";
+import {
+ defaultTelegramEvents,
+ normalizeTelegramConfig,
+ type TelegramConfig,
+ validateTelegramConfig,
+} from "../plugins/telegram/config";
+import { telegramIntegrationSchema } from "../schemas";
+import { workspaceAccess } from "../utils/workspace-access-middleware";
+
+const telegramIntegration = new Hono<{
+ Variables: {
+ userId: string;
+ workspaceId: string;
+ apiKey?: {
+ id: string;
+ userId: string;
+ enabled: boolean;
+ };
+ };
+}>();
+
+function maskBotToken(value: string): string {
+ const [prefix, suffix = ""] = value.split(":", 2);
+ if (!suffix) {
+ return "Configured";
+ }
+
+ const maskedSuffix =
+ suffix.length > 8 ? `${suffix.slice(0, 4)}…${suffix.slice(-4)}` : "••••";
+ return `${prefix}:${maskedSuffix}`;
+}
+
+function toResponse(integration: {
+ id: string;
+ projectId: string;
+ config: string;
+ isActive: boolean | null;
+ createdAt: Date;
+ updatedAt: Date;
+}) {
+ const config = normalizeTelegramConfig(
+ JSON.parse(integration.config) as TelegramConfig,
+ );
+
+ return {
+ id: integration.id,
+ projectId: integration.projectId,
+ chatId: config.chatId,
+ threadId: config.threadId ?? null,
+ chatLabel: config.chatLabel ?? null,
+ botTokenConfigured: Boolean(config.botToken),
+ maskedBotToken: config.botToken ? maskBotToken(config.botToken) : "",
+ events: {
+ ...defaultTelegramEvents,
+ ...(config.events ?? {}),
+ },
+ isActive: integration.isActive,
+ createdAt: integration.createdAt,
+ updatedAt: integration.updatedAt,
+ };
+}
+
+async function getTelegramIntegration(projectId: string) {
+ const integration = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "telegram"),
+ ),
+ });
+
+ if (!integration) {
+ return null;
+ }
+
+ return toResponse(integration);
+}
+
+const telegramEventsSchema = v.object({
+ taskCreated: v.optional(v.boolean()),
+ taskStatusChanged: v.optional(v.boolean()),
+ taskPriorityChanged: v.optional(v.boolean()),
+ taskTitleChanged: v.optional(v.boolean()),
+ taskDescriptionChanged: v.optional(v.boolean()),
+ taskCommentCreated: v.optional(v.boolean()),
+});
+
+telegramIntegration
+ .get(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "getTelegramIntegration",
+ tags: ["Telegram"],
+ description: "Get Telegram integration for a project",
+ responses: {
+ 200: {
+ description: "Telegram integration details",
+ content: {
+ "application/json": { schema: resolver(telegramIntegrationSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const integration = await getTelegramIntegration(projectId);
+ return c.json(integration);
+ },
+ )
+ .post(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "createTelegramIntegration",
+ tags: ["Telegram"],
+ description: "Create or replace a Telegram integration for a project",
+ responses: {
+ 200: {
+ description: "Telegram integration created successfully",
+ content: {
+ "application/json": { schema: resolver(telegramIntegrationSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ validator(
+ "json",
+ v.object({
+ botToken: v.pipe(v.string(), v.minLength(1)),
+ chatId: v.pipe(v.string(), v.minLength(1)),
+ threadId: v.optional(v.number()),
+ chatLabel: v.optional(v.string()),
+ events: v.optional(telegramEventsSchema),
+ }),
+ ),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const body = c.req.valid("json");
+
+ const config = normalizeTelegramConfig({
+ botToken: body.botToken,
+ chatId: body.chatId,
+ threadId: body.threadId,
+ chatLabel: body.chatLabel,
+ events: body.events,
+ });
+
+ const validation = await validateTelegramConfig(config);
+ if (!validation.valid) {
+ throw new HTTPException(400, {
+ message: validation.errors?.join(", ") ?? "Invalid config",
+ });
+ }
+
+ await db
+ .insert(integrationTable)
+ .values({
+ projectId,
+ type: "telegram",
+ config: JSON.stringify(config),
+ isActive: true,
+ })
+ .onConflictDoUpdate({
+ target: [integrationTable.projectId, integrationTable.type],
+ set: {
+ config: JSON.stringify(config),
+ isActive: true,
+ updatedAt: new Date(),
+ },
+ });
+
+ const integration = await getTelegramIntegration(projectId);
+ return c.json(integration);
+ },
+ )
+ .patch(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "updateTelegramIntegration",
+ tags: ["Telegram"],
+ description: "Update Telegram integration settings",
+ responses: {
+ 200: {
+ description: "Telegram integration updated successfully",
+ content: {
+ "application/json": { schema: resolver(telegramIntegrationSchema) },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ validator(
+ "json",
+ v.object({
+ botToken: v.optional(v.string()),
+ chatId: v.optional(v.string()),
+ threadId: v.optional(v.nullable(v.number())),
+ chatLabel: v.optional(v.nullable(v.string())),
+ isActive: v.optional(v.boolean()),
+ events: v.optional(telegramEventsSchema),
+ }),
+ ),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+ const body = c.req.valid("json");
+
+ const existing = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "telegram"),
+ ),
+ });
+
+ if (!existing) {
+ throw new HTTPException(404, {
+ message: "Telegram integration not found",
+ });
+ }
+
+ const currentConfig = normalizeTelegramConfig(
+ JSON.parse(existing.config) as TelegramConfig,
+ );
+ const nextConfig = normalizeTelegramConfig({
+ botToken: body.botToken?.trim() || currentConfig.botToken,
+ chatId: body.chatId?.trim() || currentConfig.chatId,
+ threadId:
+ body.threadId === undefined
+ ? currentConfig.threadId
+ : (body.threadId ?? undefined),
+ chatLabel:
+ body.chatLabel === undefined
+ ? currentConfig.chatLabel
+ : (body.chatLabel ?? undefined),
+ events: {
+ ...(currentConfig.events ?? {}),
+ ...(body.events ?? {}),
+ },
+ });
+
+ const validation = await validateTelegramConfig(nextConfig);
+ if (!validation.valid) {
+ throw new HTTPException(400, {
+ message: validation.errors?.join(", ") ?? "Invalid config",
+ });
+ }
+
+ await db
+ .update(integrationTable)
+ .set({
+ config: JSON.stringify(nextConfig),
+ isActive:
+ body.isActive !== undefined
+ ? body.isActive
+ : (existing.isActive ?? true),
+ updatedAt: new Date(),
+ })
+ .where(eq(integrationTable.id, existing.id));
+
+ const integration = await getTelegramIntegration(projectId);
+ return c.json(integration);
+ },
+ )
+ .delete(
+ "/project/:projectId",
+ describeRoute({
+ operationId: "deleteTelegramIntegration",
+ tags: ["Telegram"],
+ description: "Delete Telegram integration for a project",
+ responses: {
+ 200: {
+ description: "Telegram integration deleted successfully",
+ content: {
+ "application/json": {
+ schema: resolver(v.object({ success: v.boolean() })),
+ },
+ },
+ },
+ },
+ }),
+ validator("param", v.object({ projectId: v.string() })),
+ workspaceAccess.fromProject("projectId"),
+ async (c) => {
+ const { projectId } = c.req.valid("param");
+
+ const existing = await db.query.integrationTable.findFirst({
+ where: and(
+ eq(integrationTable.projectId, projectId),
+ eq(integrationTable.type, "telegram"),
+ ),
+ });
+
+ if (!existing) {
+ throw new HTTPException(404, {
+ message: "Telegram integration not found",
+ });
+ }
+
+ await db
+ .delete(integrationTable)
+ .where(eq(integrationTable.id, existing.id));
+ return c.json({ success: true });
+ },
+ );
+
+export default telegramIntegration;
diff --git a/apps/web/src/components/project/telegram-integration-settings.tsx b/apps/web/src/components/project/telegram-integration-settings.tsx
new file mode 100644
index 000000000..4c2730d61
--- /dev/null
+++ b/apps/web/src/components/project/telegram-integration-settings.tsx
@@ -0,0 +1,523 @@
+import { standardSchemaResolver } from "@hookform/resolvers/standard-schema";
+import { CheckCircle, Trash2 } from "lucide-react";
+import React from "react";
+import { useForm } from "react-hook-form";
+import { useTranslation } from "react-i18next";
+import { z } from "zod/v4";
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import {
+ useCreateTelegramIntegration,
+ useDeleteTelegramIntegration,
+ useUpdateTelegramIntegration,
+} from "@/hooks/mutations/telegram-integration/use-telegram-integration";
+import useGetTelegramIntegration from "@/hooks/queries/telegram-integration/use-get-telegram-integration";
+import { toast } from "@/lib/toast";
+
+type TelegramIntegrationFormValues = {
+ botToken: string;
+ chatId: string;
+ threadId: string;
+ chatLabel: string;
+ taskCreated: boolean;
+ taskStatusChanged: boolean;
+ taskPriorityChanged: boolean;
+ taskTitleChanged: boolean;
+ taskDescriptionChanged: boolean;
+ taskCommentCreated: boolean;
+};
+
+function EventToggle({
+ control,
+ name,
+ label,
+}: {
+ control: ReturnType<typeof useForm<TelegramIntegrationFormValues>>["control"];
+ name: keyof Pick<
+ TelegramIntegrationFormValues,
+ | "taskCreated"
+ | "taskStatusChanged"
+ | "taskPriorityChanged"
+ | "taskTitleChanged"
+ | "taskDescriptionChanged"
+ | "taskCommentCreated"
+ >;
+ label: string;
+}) {
+ return (
+ <FormField
+ control={control}
+ name={name}
+ render={({ field }) => (
+ <FormItem className="flex items-center justify-between rounded-md border px-3 py-2">
+ <FormLabel className="text-sm font-medium">{label}</FormLabel>
+ <FormControl>
+ <Switch
+ checked={Boolean(field.value)}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ );
+}
+
+function isValidTelegramBotToken(value: string): boolean {
+ return /^\d+:[A-Za-z0-9_-]{20,}$/.test(value);
+}
+
+function isValidTelegramThreadId(value: string): boolean {
+ return /^\d+$/.test(value) && Number(value) > 0;
+}
+
+export function TelegramIntegrationSettings({
+ projectId,
+}: {
+ projectId: string;
+}) {
+ const { t } = useTranslation();
+ const schema = React.useMemo(
+ () =>
+ z.object({
+ botToken: z.string(),
+ chatId: z.string(),
+ threadId: z.string(),
+ chatLabel: z.string(),
+ taskCreated: z.boolean(),
+ taskStatusChanged: z.boolean(),
+ taskPriorityChanged: z.boolean(),
+ taskTitleChanged: z.boolean(),
+ taskDescriptionChanged: z.boolean(),
+ taskCommentCreated: z.boolean(),
+ }),
+ [],
+ );
+
+ const { data: integration, isLoading } = useGetTelegramIntegration(projectId);
+ const { mutateAsync: createIntegration, isPending: isCreating } =
+ useCreateTelegramIntegration();
+ const { mutateAsync: updateIntegration, isPending: isUpdating } =
+ useUpdateTelegramIntegration();
+ const { mutateAsync: deleteIntegration, isPending: isDeleting } =
+ useDeleteTelegramIntegration();
+ const normalizedValues = React.useMemo<TelegramIntegrationFormValues>(
+ () => ({
+ botToken: "",
+ chatId: integration?.chatId ?? "",
+ threadId: integration?.threadId ? String(integration.threadId) : "",
+ chatLabel: integration?.chatLabel ?? "",
+ taskCreated: integration?.events?.taskCreated ?? true,
+ taskStatusChanged: integration?.events?.taskStatusChanged ?? true,
+ taskPriorityChanged: integration?.events?.taskPriorityChanged ?? false,
+ taskTitleChanged: integration?.events?.taskTitleChanged ?? false,
+ taskDescriptionChanged:
+ integration?.events?.taskDescriptionChanged ?? false,
+ taskCommentCreated: integration?.events?.taskCommentCreated ?? true,
+ }),
+ [integration],
+ );
+
+ const form = useForm<TelegramIntegrationFormValues>({
+ resolver: standardSchemaResolver(schema),
+ defaultValues: {
+ botToken: "",
+ chatId: "",
+ threadId: "",
+ chatLabel: "",
+ taskCreated: true,
+ taskStatusChanged: true,
+ taskPriorityChanged: false,
+ taskTitleChanged: false,
+ taskDescriptionChanged: false,
+ taskCommentCreated: true,
+ },
+ });
+ const { reset } = form;
+ const lastResetKeyRef = React.useRef<string | null>(null);
+ const resetKey = `${projectId}:${integration?.id ?? "none"}`;
+
+ React.useEffect(() => {
+ if (form.formState.isDirty && lastResetKeyRef.current === resetKey) {
+ return;
+ }
+
+ reset(normalizedValues);
+ lastResetKeyRef.current = resetKey;
+ }, [form.formState.isDirty, normalizedValues, reset, resetKey]);
+
+ const isConnected = Boolean(integration?.botTokenConfigured);
+ const isBusy = isCreating || isUpdating || isDeleting;
+
+ const onSubmit = async (values: TelegramIntegrationFormValues) => {
+ try {
+ const trimmedBotToken = values.botToken.trim();
+ const trimmedChatId = values.chatId.trim();
+ const trimmedThreadId = values.threadId.trim();
+ const parsedThreadId = trimmedThreadId
+ ? Number(trimmedThreadId)
+ : undefined;
+ const events = {
+ taskCreated: values.taskCreated,
+ taskStatusChanged: values.taskStatusChanged,
+ taskPriorityChanged: values.taskPriorityChanged,
+ taskTitleChanged: values.taskTitleChanged,
+ taskDescriptionChanged: values.taskDescriptionChanged,
+ taskCommentCreated: values.taskCommentCreated,
+ };
+
+ if (!trimmedChatId) {
+ form.setError("chatId", {
+ message: t("settings:telegramIntegration.validation.chatIdRequired"),
+ });
+ return;
+ }
+
+ if (trimmedThreadId && !isValidTelegramThreadId(trimmedThreadId)) {
+ form.setError("threadId", {
+ message: t("settings:telegramIntegration.validation.threadIdInvalid"),
+ });
+ return;
+ }
+
+ if (!isConnected) {
+ if (!trimmedBotToken || !isValidTelegramBotToken(trimmedBotToken)) {
+ form.setError("botToken", {
+ message: t(
+ "settings:telegramIntegration.validation.botTokenInvalid",
+ ),
+ });
+ return;
+ }
+
+ await createIntegration({
+ projectId,
+ data: {
+ botToken: trimmedBotToken,
+ chatId: trimmedChatId,
+ threadId: parsedThreadId,
+ chatLabel: values.chatLabel || undefined,
+ events,
+ },
+ });
+ } else {
+ if (trimmedBotToken && !isValidTelegramBotToken(trimmedBotToken)) {
+ form.setError("botToken", {
+ message: t(
+ "settings:telegramIntegration.validation.botTokenInvalid",
+ ),
+ });
+ return;
+ }
+
+ await updateIntegration({
+ projectId,
+ json: {
+ botToken: trimmedBotToken || undefined,
+ chatId: trimmedChatId,
+ threadId: parsedThreadId ?? null,
+ chatLabel: values.chatLabel || null,
+ events,
+ },
+ });
+ }
+
+ form.reset({
+ ...values,
+ botToken: "",
+ chatId: trimmedChatId,
+ threadId: trimmedThreadId,
+ });
+ toast.success(t("settings:telegramIntegration.toast.saved"));
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("settings:telegramIntegration.toast.saveError"),
+ );
+ }
+ };
+
+ const handleToggleActive = async (checked: boolean) => {
+ try {
+ await updateIntegration({
+ projectId,
+ json: { isActive: checked },
+ });
+ toast.success(
+ checked
+ ? t("settings:telegramIntegration.toast.enabled")
+ : t("settings:telegramIntegration.toast.disabled"),
+ );
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("settings:telegramIntegration.toast.updateError"),
+ );
+ }
+ };
+
+ const handleDelete = async () => {
+ try {
+ await deleteIntegration(projectId);
+ form.reset({
+ botToken: "",
+ chatId: "",
+ threadId: "",
+ chatLabel: "",
+ taskCreated: true,
+ taskStatusChanged: true,
+ taskPriorityChanged: false,
+ taskTitleChanged: false,
+ taskDescriptionChanged: false,
+ taskCommentCreated: true,
+ });
+ toast.success(t("settings:telegramIntegration.toast.removed"));
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("settings:telegramIntegration.toast.removeError"),
+ );
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="space-y-4">
+ <div className="space-y-4 rounded-md border border-border bg-sidebar p-4">
+ <div className="h-4 w-40 animate-pulse rounded bg-muted" />
+ <div className="h-10 w-full animate-pulse rounded bg-muted" />
+ <div className="h-10 w-full animate-pulse rounded bg-muted" />
+ </div>
+ <div className="space-y-4 rounded-md border border-border bg-sidebar p-4">
+ <div className="h-4 w-40 animate-pulse rounded bg-muted" />
+ <div className="h-10 w-full animate-pulse rounded bg-muted" />
+ <div className="h-10 w-full animate-pulse rounded bg-muted" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <Form {...form}>
+ <form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}>
+ <div className="space-y-4 rounded-md border border-border bg-sidebar p-4">
+ <div className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <h3 className="font-medium">
+ {t("settings:telegramIntegration.connectionTitle")}
+ </h3>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ {t("settings:telegramIntegration.connectionHint")}
+ </p>
+ </div>
+
+ <div className="flex items-center gap-3">
+ {isConnected && (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <CheckCircle className="size-4 text-green-600" />
+ <span>
+ {integration?.isActive
+ ? t("settings:telegramIntegration.connected")
+ : t("settings:telegramIntegration.paused")}
+ </span>
+ </div>
+ )}
+ <Switch
+ checked={integration?.isActive ?? false}
+ disabled={!isConnected || isBusy}
+ onCheckedChange={handleToggleActive}
+ />
+ </div>
+ </div>
+
+ <FormField
+ control={form.control}
+ name="botToken"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {t("settings:telegramIntegration.botTokenLabel")}
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ autoComplete="off"
+ placeholder={t(
+ "settings:telegramIntegration.botTokenPlaceholder",
+ )}
+ type="password"
+ />
+ </FormControl>
+ <p className="text-xs text-muted-foreground">
+ {integration?.botTokenConfigured
+ ? t(
+ "settings:telegramIntegration.botTokenHintConfigured",
+ { token: integration.maskedBotToken },
+ )
+ : t("settings:telegramIntegration.botTokenHint")}
+ </p>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="chatId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {t("settings:telegramIntegration.chatIdLabel")}
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder={t(
+ "settings:telegramIntegration.chatIdPlaceholder",
+ )}
+ />
+ </FormControl>
+ <p className="text-xs text-muted-foreground">
+ {t("settings:telegramIntegration.chatIdHint")}
+ </p>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="threadId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {t("settings:telegramIntegration.threadIdLabel")}
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ inputMode="numeric"
+ placeholder={t(
+ "settings:telegramIntegration.threadIdPlaceholder",
+ )}
+ />
+ </FormControl>
+ <p className="text-xs text-muted-foreground">
+ {t("settings:telegramIntegration.threadIdHint")}
+ </p>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="chatLabel"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {t("settings:telegramIntegration.chatLabelLabel")}
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder={t(
+ "settings:telegramIntegration.chatLabelPlaceholder",
+ )}
+ />
+ </FormControl>
+ <p className="text-xs text-muted-foreground">
+ {t("settings:telegramIntegration.chatLabelHint")}
+ </p>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <div className="space-y-3 rounded-md border border-border bg-sidebar p-4">
+ <div>
+ <h3 className="font-medium">
+ {t("settings:telegramIntegration.eventsTitle")}
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ {t("settings:telegramIntegration.eventsHint")}
+ </p>
+ </div>
+
+ <EventToggle
+ control={form.control}
+ label={t("settings:telegramIntegration.events.taskCreated")}
+ name="taskCreated"
+ />
+ <EventToggle
+ control={form.control}
+ label={t("settings:telegramIntegration.events.taskStatusChanged")}
+ name="taskStatusChanged"
+ />
+ <EventToggle
+ control={form.control}
+ label={t(
+ "settings:telegramIntegration.events.taskPriorityChanged",
+ )}
+ name="taskPriorityChanged"
+ />
+ <EventToggle
+ control={form.control}
+ label={t("settings:telegramIntegration.events.taskTitleChanged")}
+ name="taskTitleChanged"
+ />
+ <EventToggle
+ control={form.control}
+ label={t(
+ "settings:telegramIntegration.events.taskDescriptionChanged",
+ )}
+ name="taskDescriptionChanged"
+ />
+ <EventToggle
+ control={form.control}
+ label={t(
+ "settings:telegramIntegration.events.taskCommentCreated",
+ )}
+ name="taskCommentCreated"
+ />
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <Button disabled={isBusy} type="submit">
+ {isConnected
+ ? t("settings:telegramIntegration.saveChanges")
+ : t("settings:telegramIntegration.connect")}
+ </Button>
+ {isConnected && (
+ <Button
+ disabled={isBusy}
+ onClick={handleDelete}
+ type="button"
+ variant="outline"
+ >
+ <Trash2 className="size-4" />
+ {t("settings:telegramIntegration.disconnect")}
+ </Button>
+ )}
+ </div>
+ </form>
+ </Form>
+ </div>
+ );
+}
diff --git a/apps/web/src/fetchers/telegram-integration/create-telegram-integration.ts b/apps/web/src/fetchers/telegram-integration/create-telegram-integration.ts
new file mode 100644
index 000000000..41099812b
--- /dev/null
+++ b/apps/web/src/fetchers/telegram-integration/create-telegram-integration.ts
@@ -0,0 +1,43 @@
+import { getApiUrl } from "@/fetchers/get-api-url";
+import type { TelegramIntegration } from "./get-telegram-integration";
+
+export type CreateTelegramIntegrationRequest = {
+ botToken: string;
+ chatId: string;
+ threadId?: number;
+ chatLabel?: string;
+ events?: {
+ taskCreated?: boolean;
+ taskStatusChanged?: boolean;
+ taskPriorityChanged?: boolean;
+ taskTitleChanged?: boolean;
+ taskDescriptionChanged?: boolean;
+ taskCommentCreated?: boolean;
+ };
+};
+
+async function createTelegramIntegration(
+ projectId: string,
+ json: CreateTelegramIntegrationRequest,
+) {
+ const response = await fetch(
+ getApiUrl(`/telegram-integration/project/${projectId}`),
+ {
+ method: "POST",
+ credentials: "include",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(json),
+ },
+ );
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return (await response.json()) as TelegramIntegration;
+}
+
+export default createTelegramIntegration;
diff --git a/apps/web/src/fetchers/telegram-integration/delete-telegram-integration.ts b/apps/web/src/fetchers/telegram-integration/delete-telegram-integration.ts
new file mode 100644
index 000000000..eb3a950fd
--- /dev/null
+++ b/apps/web/src/fetchers/telegram-integration/delete-telegram-integration.ts
@@ -0,0 +1,20 @@
+import { getApiUrl } from "@/fetchers/get-api-url";
+
+async function deleteTelegramIntegration(projectId: string) {
+ const response = await fetch(
+ getApiUrl(`/telegram-integration/project/${projectId}`),
+ {
+ method: "DELETE",
+ credentials: "include",
+ },
+ );
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return (await response.json()) as { success: boolean };
+}
+
+export default deleteTelegramIntegration;
diff --git a/apps/web/src/fetchers/telegram-integration/get-telegram-integration.ts b/apps/web/src/fetchers/telegram-integration/get-telegram-integration.ts
new file mode 100644
index 000000000..ea1bd19ff
--- /dev/null
+++ b/apps/web/src/fetchers/telegram-integration/get-telegram-integration.ts
@@ -0,0 +1,40 @@
+import { getApiUrl } from "@/fetchers/get-api-url";
+
+export type TelegramIntegration = {
+ id: string;
+ projectId: string;
+ chatId: string;
+ threadId: number | null;
+ chatLabel: string | null;
+ botTokenConfigured: boolean;
+ maskedBotToken: string;
+ events: {
+ taskCreated: boolean;
+ taskStatusChanged: boolean;
+ taskPriorityChanged: boolean;
+ taskTitleChanged: boolean;
+ taskDescriptionChanged: boolean;
+ taskCommentCreated: boolean;
+ };
+ isActive: boolean | null;
+ createdAt: string;
+ updatedAt: string;
+} | null;
+
+async function getTelegramIntegration(projectId: string) {
+ const response = await fetch(
+ getApiUrl(`/telegram-integration/project/${projectId}`),
+ {
+ credentials: "include",
+ },
+ );
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return (await response.json()) as TelegramIntegration;
+}
+
+export default getTelegramIntegration;
diff --git a/apps/web/src/fetchers/telegram-integration/update-telegram-integration.ts b/apps/web/src/fetchers/telegram-integration/update-telegram-integration.ts
new file mode 100644
index 000000000..2a50682f9
--- /dev/null
+++ b/apps/web/src/fetchers/telegram-integration/update-telegram-integration.ts
@@ -0,0 +1,44 @@
+import { getApiUrl } from "@/fetchers/get-api-url";
+import type { TelegramIntegration } from "./get-telegram-integration";
+
+export type UpdateTelegramIntegrationRequest = {
+ botToken?: string;
+ chatId?: string;
+ threadId?: number | null;
+ chatLabel?: string | null;
+ isActive?: boolean;
+ events?: {
+ taskCreated?: boolean;
+ taskStatusChanged?: boolean;
+ taskPriorityChanged?: boolean;
+ taskTitleChanged?: boolean;
+ taskDescriptionChanged?: boolean;
+ taskCommentCreated?: boolean;
+ };
+};
+
+async function updateTelegramIntegration(
+ projectId: string,
+ json: UpdateTelegramIntegrationRequest,
+) {
+ const response = await fetch(
+ getApiUrl(`/telegram-integration/project/${projectId}`),
+ {
+ method: "PATCH",
+ credentials: "include",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(json),
+ },
+ );
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+
+ return (await response.json()) as TelegramIntegration;
+}
+
+export default updateTelegramIntegration;
diff --git a/apps/web/src/hooks/mutations/telegram-integration/use-telegram-integration.ts b/apps/web/src/hooks/mutations/telegram-integration/use-telegram-integration.ts
new file mode 100644
index 000000000..28be03239
--- /dev/null
+++ b/apps/web/src/hooks/mutations/telegram-integration/use-telegram-integration.ts
@@ -0,0 +1,59 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import createTelegramIntegration, {
+ type CreateTelegramIntegrationRequest,
+} from "@/fetchers/telegram-integration/create-telegram-integration";
+import deleteTelegramIntegration from "@/fetchers/telegram-integration/delete-telegram-integration";
+import updateTelegramIntegration, {
+ type UpdateTelegramIntegrationRequest,
+} from "@/fetchers/telegram-integration/update-telegram-integration";
+
+export function useCreateTelegramIntegration() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({
+ projectId,
+ data,
+ }: {
+ projectId: string;
+ data: CreateTelegramIntegrationRequest;
+ }) => createTelegramIntegration(projectId, data),
+ onSuccess: (_, { projectId }) => {
+ void queryClient.invalidateQueries({
+ queryKey: ["telegram-integration", projectId],
+ });
+ },
+ });
+}
+
+export function useUpdateTelegramIntegration() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({
+ projectId,
+ json,
+ }: {
+ projectId: string;
+ json: UpdateTelegramIntegrationRequest;
+ }) => updateTelegramIntegration(projectId, json),
+ onSuccess: (_, { projectId }) => {
+ void queryClient.invalidateQueries({
+ queryKey: ["telegram-integration", projectId],
+ });
+ },
+ });
+}
+
+export function useDeleteTelegramIntegration() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: (projectId: string) => deleteTelegramIntegration(projectId),
+ onSuccess: (_, projectId) => {
+ void queryClient.invalidateQueries({
+ queryKey: ["telegram-integration", projectId],
+ });
+ },
+ });
+}
diff --git a/apps/web/src/hooks/queries/telegram-integration/use-get-telegram-integration.ts b/apps/web/src/hooks/queries/telegram-integration/use-get-telegram-integration.ts
new file mode 100644
index 000000000..ff9616646
--- /dev/null
+++ b/apps/web/src/hooks/queries/telegram-integration/use-get-telegram-integration.ts
@@ -0,0 +1,12 @@
+import { useQuery } from "@tanstack/react-query";
+import getTelegramIntegration from "@/fetchers/telegram-integration/get-telegram-integration";
+
+function useGetTelegramIntegration(projectId: string) {
+ return useQuery({
+ queryKey: ["telegram-integration", projectId],
+ queryFn: () => getTelegramIntegration(projectId),
+ enabled: Boolean(projectId),
+ });
+}
+
+export default useGetTelegramIntegration;
diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsx
index 71758d49c..8d0de525e 100644
--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsx
+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/integrations.tsx
@@ -4,6 +4,7 @@ import {
Github,
MessageCircle,
Radio,
+ Send,
Webhook,
} from "lucide-react";
import type { ReactNode } from "react";
@@ -13,6 +14,7 @@ import { DiscordIntegrationSettings } from "@/components/project/discord-integra
import { GenericWebhookIntegrationSettings } from "@/components/project/generic-webhook-integration-settings";
import { GitHubIntegrationSettings } from "@/components/project/github-integration-settings";
import { SlackIntegrationSettings } from "@/components/project/slack-integration-settings";
+import { TelegramIntegrationSettings } from "@/components/project/telegram-integration-settings";
import {
Collapsible,
CollapsibleContent,
@@ -44,7 +46,6 @@ function RouteComponent() {
<div className="space-y-6">
<IntegrationSection
- defaultOpen
icon={<Github className="size-4" />}
subtitle={t("settings:projectIntegrations.githubSectionSubtitle")}
title={t("settings:projectIntegrations.githubSectionTitle")}
@@ -77,6 +78,14 @@ function RouteComponent() {
>
<SlackIntegrationSettings projectId={projectId} />
</IntegrationSection>
+
+ <IntegrationSection
+ icon={<Send className="size-4" />}
+ subtitle={t("settings:projectIntegrations.telegramSectionSubtitle")}
+ title={t("settings:projectIntegrations.telegramSectionTitle")}
+ >
+ <TelegramIntegrationSettings projectId={projectId} />
+ </IntegrationSection>
</div>
</div>
</>
diff --git a/i18n/de-DE.json b/i18n/de-DE.json
index a4ae060dc..f7ba3bdb6 100644
--- a/i18n/de-DE.json
+++ b/i18n/de-DE.json
@@ -498,7 +498,9 @@
"genericWebhookSectionTitle": "Generische Webhooks",
"genericWebhookSectionSubtitle": "Sende Projektaufgabenereignisse als JSON an einen beliebigen HTTP-Endpunkt.",
"slackSectionTitle": "Slack-Integration",
- "slackSectionSubtitle": "Sende Projektaktualisierungen per Incoming Webhook in einen Slack-Kanal."
+ "slackSectionSubtitle": "Sende Projektaktualisierungen per Incoming Webhook in einen Slack-Kanal.",
+ "telegramSectionTitle": "Telegram-Integration",
+ "telegramSectionSubtitle": "Sende Projektaktualisierungen mit einem Bot in einen Telegram-Chat oder ein Thema."
},
"projectVisibility": {
"pageTitle": "Projektsichtbarkeit",
@@ -722,6 +724,52 @@
"saveChanges": "Änderungen speichern",
"disconnect": "Trennen"
},
+ "telegramIntegration": {
+ "validation": {
+ "botTokenInvalid": "Gib einen gültigen Telegram-Bot-Token ein",
+ "chatIdRequired": "Chat-ID ist erforderlich",
+ "threadIdInvalid": "Gib eine gültige Telegram-Themen-ID ein"
+ },
+ "toast": {
+ "saved": "Telegram-Integration erfolgreich gespeichert",
+ "saveError": "Telegram-Integration konnte nicht gespeichert werden",
+ "enabled": "Telegram-Benachrichtigungen aktiviert",
+ "disabled": "Telegram-Benachrichtigungen pausiert",
+ "updateError": "Telegram-Integration konnte nicht aktualisiert werden",
+ "removed": "Telegram-Integration erfolgreich entfernt",
+ "removeError": "Telegram-Integration konnte nicht entfernt werden"
+ },
+ "connectionTitle": "Telegram-Bot-Verbindung",
+ "connectionHint": "Verwende einen Telegram-Bot-Token und eine Chat-ID, um Projektaktualisierungen in einen Chat oder ein Thema zu senden.",
+ "connected": "Verbunden",
+ "paused": "Pausiert",
+ "botTokenLabel": "Bot-Token",
+ "botTokenPlaceholder": "123456789:AAExampleBotToken",
+ "botTokenHint": "Erstelle mit BotFather einen Bot und füge seinen Token hier ein.",
+ "botTokenHintConfigured": "Ein Bot-Token ist bereits konfiguriert ({{token}}). Gib einen neuen ein, um ihn zu ersetzen.",
+ "chatIdLabel": "Chat-ID",
+ "chatIdPlaceholder": "-1001234567890 oder @team_updates",
+ "chatIdHint": "Gib die Telegram-Chat-ID oder den Kanalnamen ein, in dem Updates gepostet werden sollen.",
+ "threadIdLabel": "Themen-ID",
+ "threadIdPlaceholder": "Optionale Themen-ID",
+ "threadIdHint": "Optional. Verwende dies für Forenthemen in Telegram-Gruppen.",
+ "chatLabelLabel": "Chat-Label",
+ "chatLabelPlaceholder": "Engineering Updates",
+ "chatLabelHint": "Optionales Label für deine Referenz in Kaneo.",
+ "eventsTitle": "Ereignisbenachrichtigungen",
+ "eventsHint": "Wähle aus, welche Projektänderungen an Telegram gesendet werden sollen.",
+ "events": {
+ "taskCreated": "Neue Aufgaben",
+ "taskStatusChanged": "Statusänderungen",
+ "taskPriorityChanged": "Prioritätsänderungen",
+ "taskTitleChanged": "Titeländerungen",
+ "taskDescriptionChanged": "Beschreibungsänderungen",
+ "taskCommentCreated": "Neue Kommentare"
+ },
+ "connect": "Telegram verbinden",
+ "saveChanges": "Änderungen speichern",
+ "disconnect": "Trennen"
+ },
"repositoryBrowser": {
"title": "Repository auswählen",
"description": "Wähle ein Repository aus, in dem deine GitHub-App installiert ist, um die Issue-Synchronisierung zu aktivieren.",
diff --git a/i18n/el-GR.json b/i18n/el-GR.json
index c5dd05052..13e5fc380 100644
--- a/i18n/el-GR.json
+++ b/i18n/el-GR.json
@@ -492,7 +492,9 @@
"title": "Ενσωματώσεις έργου",
"subtitle": "Συνδέστε το έργο σας με εξωτερικά εργαλεία και υπηρεσίες για πιο ομαλή ροή εργασίας.",
"githubSectionTitle": "Ενσωμάτωση GitHub",
- "githubSectionSubtitle": "Συγχρονίστε εργασίες με GitHub issues και ενεργοποιήστε αμφίδρομο συγχρονισμό."
+ "githubSectionSubtitle": "Συγχρονίστε εργασίες με GitHub issues και ενεργοποιήστε αμφίδρομο συγχρονισμό.",
+ "telegramSectionTitle": "Ενσωμάτωση Telegram",
+ "telegramSectionSubtitle": "Στείλτε ενημερώσεις εργασιών έργου σε συνομιλία ή θέμα Telegram με bot."
},
"projectVisibility": {
"pageTitle": "Ορατότητα έργου",
@@ -602,6 +604,52 @@
"importIssues": "Εισαγωγή issues",
"importDisabledHint": "Ολοκληρώστε τη ρύθμιση του αποθετηρίου παραπάνω για να ενεργοποιήσετε την εισαγωγή"
},
+ "telegramIntegration": {
+ "validation": {
+ "botTokenInvalid": "Εισαγάγετε έγκυρο token bot Telegram",
+ "chatIdRequired": "Το αναγνωριστικό συνομιλίας είναι υποχρεωτικό",
+ "threadIdInvalid": "Εισαγάγετε έγκυρο αναγνωριστικό θέματος Telegram"
+ },
+ "toast": {
+ "saved": "Η ενσωμάτωση Telegram αποθηκεύτηκε με επιτυχία",
+ "saveError": "Αποτυχία αποθήκευσης της ενσωμάτωσης Telegram",
+ "enabled": "Οι ειδοποιήσεις Telegram ενεργοποιήθηκαν",
+ "disabled": "Οι ειδοποιήσεις Telegram μπήκαν σε παύση",
+ "updateError": "Αποτυχία ενημέρωσης της ενσωμάτωσης Telegram",
+ "removed": "Η ενσωμάτωση Telegram αφαιρέθηκε με επιτυχία",
+ "removeError": "Αποτυχία αφαίρεσης της ενσωμάτωσης Telegram"
+ },
+ "connectionTitle": "Σύνδεση bot Telegram",
+ "connectionHint": "Χρησιμοποιήστε token bot Telegram και αναγνωριστικό συνομιλίας για να στέλνετε ενημερώσεις έργου σε συνομιλία ή θέμα.",
+ "connected": "Συνδεδεμένο",
+ "paused": "Σε παύση",
+ "botTokenLabel": "Token bot",
+ "botTokenPlaceholder": "123456789:AAExampleBotToken",
+ "botTokenHint": "Δημιουργήστε bot με το BotFather και επικολλήστε εδώ το token του.",
+ "botTokenHintConfigured": "Ένα token bot έχει ήδη ρυθμιστεί ({{token}}). Εισαγάγετε νέο για να το αντικαταστήσετε.",
+ "chatIdLabel": "Αναγνωριστικό συνομιλίας",
+ "chatIdPlaceholder": "-1001234567890 ή @team_updates",
+ "chatIdHint": "Εισαγάγετε το αναγνωριστικό συνομιλίας Telegram ή το όνομα καναλιού όπου θα δημοσιεύονται οι ενημερώσεις.",
+ "threadIdLabel": "Αναγνωριστικό θέματος",
+ "threadIdPlaceholder": "Προαιρετικό αναγνωριστικό θέματος",
+ "threadIdHint": "Προαιρετικό. Χρησιμοποιήστε το για θέματα forum μέσα σε ομάδες Telegram.",
+ "chatLabelLabel": "Ετικέτα συνομιλίας",
+ "chatLabelPlaceholder": "Engineering Updates",
+ "chatLabelHint": "Προαιρετική ετικέτα για δική σας αναφορά μέσα στο Kaneo.",
+ "eventsTitle": "Ειδοποιήσεις συμβάντων",
+ "eventsHint": "Επιλέξτε ποιες αλλαγές έργου θα δημοσιεύονται στο Telegram.",
+ "events": {
+ "taskCreated": "Νέες εργασίες",
+ "taskStatusChanged": "Αλλαγές κατάστασης",
+ "taskPriorityChanged": "Αλλαγές προτεραιότητας",
+ "taskTitleChanged": "Αλλαγές τίτλου",
+ "taskDescriptionChanged": "Αλλαγές περιγραφής",
+ "taskCommentCreated": "Νέα σχόλια"
+ },
+ "connect": "Σύνδεση Telegram",
+ "saveChanges": "Αποθήκευση αλλαγών",
+ "disconnect": "Αποσύνδεση"
+ },
"repositoryBrowser": {
"title": "Επιλογή αποθετηρίου",
"description": "Επιλέξτε ένα αποθετήριο στο οποίο είναι εγκατεστημένη η εφαρμογή GitHub για να ενεργοποιήσετε τον συγχρονισμό issues.",
diff --git a/i18n/en-US.json b/i18n/en-US.json
index ccb9a385a..e5faa88a6 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -498,7 +498,9 @@
"genericWebhookSectionTitle": "Generic Webhooks",
"genericWebhookSectionSubtitle": "Send project task events to any HTTP endpoint as JSON.",
"slackSectionTitle": "Slack Integration",
- "slackSectionSubtitle": "Send project task updates into a Slack channel with an incoming webhook."
+ "slackSectionSubtitle": "Send project task updates into a Slack channel with an incoming webhook.",
+ "telegramSectionTitle": "Telegram Integration",
+ "telegramSectionSubtitle": "Send project task updates into a Telegram chat or topic with a bot."
},
"projectVisibility": {
"pageTitle": "Project Visibility",
@@ -722,6 +724,52 @@
"saveChanges": "Save changes",
"disconnect": "Disconnect"
},
+ "telegramIntegration": {
+ "validation": {
+ "botTokenInvalid": "Enter a valid Telegram bot token",
+ "chatIdRequired": "Chat ID is required",
+ "threadIdInvalid": "Enter a valid Telegram topic thread ID"
+ },
+ "toast": {
+ "saved": "Telegram integration saved successfully",
+ "saveError": "Failed to save Telegram integration",
+ "enabled": "Telegram notifications enabled",
+ "disabled": "Telegram notifications paused",
+ "updateError": "Failed to update Telegram integration",
+ "removed": "Telegram integration removed successfully",
+ "removeError": "Failed to remove Telegram integration"
+ },
+ "connectionTitle": "Telegram bot connection",
+ "connectionHint": "Use a Telegram bot token and chat ID to send project task updates into a chat or topic.",
+ "connected": "Connected",
+ "paused": "Paused",
+ "botTokenLabel": "Bot token",
+ "botTokenPlaceholder": "123456789:AAExampleBotToken",
+ "botTokenHint": "Create a bot with BotFather and paste its token here.",
+ "botTokenHintConfigured": "A bot token is already configured ({{token}}). Enter a new one to replace it.",
+ "chatIdLabel": "Chat ID",
+ "chatIdPlaceholder": "-1001234567890 or @team_updates",
+ "chatIdHint": "Enter the Telegram chat ID or channel username where updates should be posted.",
+ "threadIdLabel": "Topic thread ID",
+ "threadIdPlaceholder": "Optional topic ID",
+ "threadIdHint": "Optional. Use this for forum topics inside Telegram groups.",
+ "chatLabelLabel": "Chat label",
+ "chatLabelPlaceholder": "Engineering Updates",
+ "chatLabelHint": "Optional label for your reference inside Kaneo.",
+ "eventsTitle": "Event notifications",
+ "eventsHint": "Choose which project changes should post to Telegram.",
+ "events": {
+ "taskCreated": "New tasks",
+ "taskStatusChanged": "Status changes",
+ "taskPriorityChanged": "Priority changes",
+ "taskTitleChanged": "Title changes",
+ "taskDescriptionChanged": "Description changes",
+ "taskCommentCreated": "New comments"
+ },
+ "connect": "Connect Telegram",
+ "saveChanges": "Save changes",
+ "disconnect": "Disconnect"
+ },
"repositoryBrowser": {
"title": "Select Repository",
"description": "Choose a repository where your GitHub App is installed to enable issue synchronization.",
diff --git a/i18n/fr-FR.json b/i18n/fr-FR.json
index b8adf688a..e1843e2d1 100644
--- a/i18n/fr-FR.json
+++ b/i18n/fr-FR.json
@@ -492,7 +492,9 @@
"title": "Intégrations du projet",
"subtitle": "Connectez votre projet avec des outils et services externes pour rationaliser votre flux de travail.",
"githubSectionTitle": "Intégration GitHub",
- "githubSectionSubtitle": "Synchronisez les tâches avec les problèmes GitHub et activez la synchronisation bidirectionnelle."
+ "githubSectionSubtitle": "Synchronisez les tâches avec les problèmes GitHub et activez la synchronisation bidirectionnelle.",
+ "telegramSectionTitle": "Intégration Telegram",
+ "telegramSectionSubtitle": "Envoyez les mises à jour des tâches du projet dans un chat ou un sujet Telegram avec un bot."
},
"projectVisibility": {
"pageTitle": "Visibilité du projet",
@@ -602,6 +604,52 @@
"importIssues": "Importer les problèmes",
"importDisabledHint": "Complétez la configuration du dépôt ci-dessus pour activer l'importation"
},
+ "telegramIntegration": {
+ "validation": {
+ "botTokenInvalid": "Entrez un jeton de bot Telegram valide",
+ "chatIdRequired": "L'identifiant du chat est requis",
+ "threadIdInvalid": "Entrez un identifiant de sujet Telegram valide"
+ },
+ "toast": {
+ "saved": "Intégration Telegram enregistrée avec succès",
+ "saveError": "Échec de l'enregistrement de l'intégration Telegram",
+ "enabled": "Notifications Telegram activées",
+ "disabled": "Notifications Telegram mises en pause",
+ "updateError": "Échec de la mise à jour de l'intégration Telegram",
+ "removed": "Intégration Telegram supprimée avec succès",
+ "removeError": "Échec de la suppression de l'intégration Telegram"
+ },
+ "connectionTitle": "Connexion du bot Telegram",
+ "connectionHint": "Utilisez un jeton de bot Telegram et un identifiant de chat pour envoyer les mises à jour du projet dans un chat ou un sujet.",
+ "connected": "Connecté",
+ "paused": "En pause",
+ "botTokenLabel": "Jeton du bot",
+ "botTokenPlaceholder": "123456789:AAExampleBotToken",
+ "botTokenHint": "Créez un bot avec BotFather et collez son jeton ici.",
+ "botTokenHintConfigured": "Un jeton de bot est déjà configuré ({{token}}). Entrez-en un nouveau pour le remplacer.",
+ "chatIdLabel": "Identifiant du chat",
+ "chatIdPlaceholder": "-1001234567890 ou @team_updates",
+ "chatIdHint": "Entrez l'identifiant du chat Telegram ou le nom d'utilisateur du canal où publier les mises à jour.",
+ "threadIdLabel": "Identifiant du sujet",
+ "threadIdPlaceholder": "Identifiant de sujet facultatif",
+ "threadIdHint": "Facultatif. Utilisez-le pour les sujets de forum dans les groupes Telegram.",
+ "chatLabelLabel": "Libellé du chat",
+ "chatLabelPlaceholder": "Mises à jour engineering",
+ "chatLabelHint": "Libellé facultatif pour votre référence dans Kaneo.",
+ "eventsTitle": "Notifications d'événements",
+ "eventsHint": "Choisissez les changements du projet à publier dans Telegram.",
+ "events": {
+ "taskCreated": "Nouvelles tâches",
+ "taskStatusChanged": "Changements de statut",
+ "taskPriorityChanged": "Changements de priorité",
+ "taskTitleChanged": "Changements de titre",
+ "taskDescriptionChanged": "Changements de description",
+ "taskCommentCreated": "Nouveaux commentaires"
+ },
+ "connect": "Connecter Telegram",
+ "saveChanges": "Enregistrer les modifications",
+ "disconnect": "Déconnecter"
+ },
"repositoryBrowser": {
"title": "Sélectionner un dépôt",
"description": "Choisissez un dépôt où votre application GitHub est installée pour activer la synchronisation des problèmes.",
diff --git a/i18n/mk-MK.json b/i18n/mk-MK.json
index df689050d..86a58f2a9 100644
--- a/i18n/mk-MK.json
+++ b/i18n/mk-MK.json
@@ -492,7 +492,9 @@
"title": "Интеграции на проект",
"subtitle": "Поврзи го твојот проект со надворешни алатки и сервиси за да го подобриш работниот тек.",
"githubSectionTitle": "GitHub интеграција",
- "githubSectionSubtitle": "Синхронизирај задачи со GitHub issues и овозможи двонасочна синхронизација."
+ "githubSectionSubtitle": "Синхронизирај задачи со GitHub issues и овозможи двонасочна синхронизација.",
+ "telegramSectionTitle": "Telegram интеграција",
+ "telegramSectionSubtitle": "Испраќај ажурирања за задачи од проектот во Telegram разговор или тема со бот."
},
"projectVisibility": {
"pageTitle": "Видливост на проект",
@@ -602,6 +604,52 @@
"importIssues": "Увези Issues",
"importDisabledHint": "Заврши ја конфигурацијата на репозиториумот погоре за да овозможиш увоз"
},
+ "telegramIntegration": {
+ "validation": {
+ "botTokenInvalid": "Внеси валиден Telegram bot token",
+ "chatIdRequired": "Chat ID е задолжително",
+ "threadIdInvalid": "Внеси валиден Telegram ID за тема"
+ },
+ "toast": {
+ "saved": "Telegram интеграцијата е успешно зачувана",
+ "saveError": "Неуспешно зачувување на Telegram интеграцијата",
+ "enabled": "Telegram известувањата се вклучени",
+ "disabled": "Telegram известувањата се паузирани",
+ "updateError": "Неуспешно ажурирање на Telegram интеграцијата",
+ "removed": "Telegram интеграцијата е успешно отстранета",
+ "removeError": "Неуспешно отстранување на Telegram интеграцијата"
+ },
+ "connectionTitle": "Конекција со Telegram бот",
+ "connectionHint": "Користи Telegram bot token и chat ID за да испраќаш ажурирања за проектот во разговор или тема.",
+ "connected": "Поврзан",
+ "paused": "Паузирано",
+ "botTokenLabel": "Bot token",
+ "botTokenPlaceholder": "123456789:AAExampleBotToken",
+ "botTokenHint": "Креирај бот со BotFather и залепи го неговиот token тука.",
+ "botTokenHintConfigured": "Bot token веќе е конфигуриран ({{token}}). Внеси нов за да го замениш.",
+ "chatIdLabel": "Chat ID",
+ "chatIdPlaceholder": "-1001234567890 или @team_updates",
+ "chatIdHint": "Внеси Telegram chat ID или корисничко име на канал каде што треба да се објавуваат ажурирањата.",
+ "threadIdLabel": "ID на тема",
+ "threadIdPlaceholder": "Опционален ID на тема",
+ "threadIdHint": "Опционално. Користи го ова за forum теми во Telegram групи.",
+ "chatLabelLabel": "Ознака за разговор",
+ "chatLabelPlaceholder": "Engineering Updates",
+ "chatLabelHint": "Опционална ознака за твоја референца во Kaneo.",
+ "eventsTitle": "Известувања за настани",
+ "eventsHint": "Избери кои промени во проектот треба да се објавуваат во Telegram.",
+ "events": {
+ "taskCreated": "Нови задачи",
+ "taskStatusChanged": "Промени на статус",
+ "taskPriorityChanged": "Промени на приоритет",
+ "taskTitleChanged": "Промени на наслов",
+ "taskDescriptionChanged": "Промени на опис",
+ "taskCommentCreated": "Нови коментари"
+ },
+ "connect": "Поврзи Telegram",
+ "saveChanges": "Зачувај промени",
+ "disconnect": "Откачи"
+ },
"repositoryBrowser": {
"title": "Избери репозиториум",
"description": "Избери репозиториум каде е инсталирана твојата GitHub апликација за да овозможиш синхронизација на issues.",