Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
Telegram Group Notification via QR Code (#1861)
Moulik Aggarwalb6549670f4ba
diff --git a/TELEGRAM.md b/TELEGRAM.mdnew file mode 100644index 000000000..75a9558d8--- /dev/null+++ b/TELEGRAM.md@@ -0,0 +1,76 @@+# Telegram Group Integration Technical Documentation++This document outlines the technical architecture, security measures, and configuration requirements for the Telegram bot integration in OpenStatus.++## Overview++The integration follows a two-step "QR Code" flow to securely link a Telegram group to an OpenStatus workspace:+1. **Phase 1 (Private Connection)**: Link a user's Telegram account to a workspace via a one-time token.+2. **Phase 2 (Group Addition)**: Detect when the bot is added to a group by that specific user.++---++## Environment Variables++The following environment variables must be configured in both the dashboard and the API packages.++| Variable | Scope | Description |+| :--- | :--- | :--- |+| `TELEGRAM_BOT_TOKEN` | Backend | The API token provided by BotFather. Used for `getUpdates`. |+| `NEXT_PUBLIC_TELEGRAM_BOT_USERNAME` | Frontend & Backend | The username of the bot (without `@`). Used for QR links and identity verification. |++---++## Technical Architecture++### 1. Token Management (Redis)+We use a **Unified Single-Key Strategy** to manage integration tokens.++- **Redis Key Pattern**: `telegram:workspace_token:${workspaceId}`+- **Storage**: Stores a plain 12-character random ID (generated using `nanoid(12)`).+- **Override Logic**: Only **one** active token is allowed per workspace at any time. Generating a new token automatically replaces the previous one.+- **Security Lifecycle**:+ - **Expiry**: Tokens have a hard expiry of **30 minutes**.+ - **One-Time Use**: The token is immediately deleted from Redis once the private chat connection (Phase 1) is successful.++### 2. Session Isolation & Stale Data Prevention+Telegram's `getUpdates` API returns updates from the last 24 hours. To prevent old messages from triggering new integrations, we implement **Timestamp Filtering**:++- **Session Start Time**: When the user clicks "Connect with QR", the frontend captures the current unix timestamp (`sessionStartTime`).+- **Query Filter**: The backend `getTelegramUpdates` query accepts a `since` parameter and skips any update with a `date < since`.+- **Reset Handling**: If a user resets the group ID, a new `sessionStartTime` is generated, ensuring only *subsequent* group additions are processed.++### 3. Update Processing Logic++#### Phase 1: Private Connection+- **Trigger**: User scans QR and sends `/start <token>`.+- **Verification**:+ - Extract `token` from message text.+ - Look up `storedRandomId` using the workspace ID from the request context.+ - If `token === storedRandomId`, the connection is valid.+ - The `privateChatId` is returned to the frontend.++#### Phase 2: Group Addition+- **Trigger**: User adds the bot to a group.+- **Verification**:+ - Detects `new_chat_participant` or `new_chat_member` in the message object.+ - **Bot Identity**: Verifies that `participant.username === NEXT_PUBLIC_TELEGRAM_BOT_USERNAME`.+ - **Ownership**: Verifies that `message.from.id` matches the `privateChatId` linked in Phase 1.+ - **Session**: Verifies `message.date >= since`.++---++## UI Components++- **`FormTelegram`**: Orchestrates the flow, manages polling, and handles session state.+- **`TelegramQRConnection`**: Displays the QR code and the "Reset Group ID" button.+- **`TelegramQRCode`**: Generates the `t.me` URL with the appropriate `start` or `startgroup` parameters.++---++## Group Reset Mechanism++Users can clear an accidental group connection using the **"Reset Group ID"** button.+1. Clears the `chatId` in the form.+2. Sets a new `sessionStartTime` (current time).+3. Polling continues, but will ignore the previous group addition because its timestamp is now older than the new session start time.diff --git a/apps/dashboard/src/components/forms/components/telegram-connection-flow.tsx b/apps/dashboard/src/components/forms/components/telegram-connection-flow.tsxnew file mode 100644index 000000000..9b923db3e--- /dev/null+++ b/apps/dashboard/src/components/forms/components/telegram-connection-flow.tsx@@ -0,0 +1,70 @@+"use client";++import { useTelegramConnection } from "@/hooks/use-telegram-connection";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@openstatus/ui/components/ui/tabs";+import type { UseFormReturn } from "react-hook-form";+import type { FormValues } from "../notifications/form-telegram";+import { TelegramManualInput } from "./telegram-manual-input";+import { TelegramQRConnection } from "./telegram-qr-connection";++interface TelegramConnectionFlowProps {+ form: UseFormReturn<FormValues>;+ mode: "qr" | "manual" | null;+ onModeChange: (mode: "qr" | "manual" | null) => void;+}++export function TelegramConnectionFlow({+ form,+ mode,+ onModeChange,+}: TelegramConnectionFlowProps) {+ const {+ tokenData,+ isTokenLoading,+ flowStep,+ privateChatId,+ userName,+ groupTitle,+ isPolling,+ resetConnection,+ confirmPrivateChat,+ } = useTelegramConnection({ form, mode });++ return (+ <Tabs+ value={mode ?? "qr"}+ onValueChange={(v) => onModeChange(v as "qr" | "manual")}+ >+ <TabsList className="w-full">+ <TabsTrigger value="qr" className="flex-1">+ Connect with QR+ </TabsTrigger>+ <TabsTrigger value="manual" className="flex-1">+ Enter ChatID manually+ </TabsTrigger>+ </TabsList>+ <TabsContent value="qr">+ <TelegramQRConnection+ form={form}+ token={tokenData?.token}+ isLoading={isTokenLoading}+ isPolling={isPolling}+ flowStep={flowStep}+ privateChatId={privateChatId}+ userName={userName}+ groupTitle={groupTitle}+ onReset={resetConnection}+ onConfirmPrivateChat={confirmPrivateChat}+ />+ </TabsContent>+ <TabsContent value="manual">+ <TelegramManualInput form={form} />+ </TabsContent>+ </Tabs>+ );+}diff --git a/apps/dashboard/src/components/forms/components/telegram-form-actions.tsx b/apps/dashboard/src/components/forms/components/telegram-form-actions.tsxnew file mode 100644index 000000000..a34b0bab2--- /dev/null+++ b/apps/dashboard/src/components/forms/components/telegram-form-actions.tsx@@ -0,0 +1,73 @@+"use client";++import { useTRPC } from "@/lib/trpc/client";+import { Button } from "@openstatus/ui/components/ui/button";+import { useMutation } from "@tanstack/react-query";+import { isTRPCClientError } from "@trpc/client";+import { useTransition } from "react";+import type { UseFormReturn } from "react-hook-form";+import { toast } from "sonner";+import type { FormValues } from "../notifications/form-telegram";++interface TelegramFormActionsProps {+ form: UseFormReturn<FormValues>;+ isPending: boolean;+}++export function TelegramFormActions({+ form,+ isPending,+}: TelegramFormActionsProps) {+ const [_, startTransition] = useTransition();+ const trpc = useTRPC();+ const sendTestMutation = useMutation(+ trpc.notification.sendTest.mutationOptions(),+ );++ function testAction() {+ if (isPending) return;++ startTransition(async () => {+ try {+ const provider = form.getValues("provider");+ const data = form.getValues("data");+ const promise = sendTestMutation.mutateAsync({+ provider,+ data: {+ telegram: { chatId: data.chatId },+ },+ });+ toast.promise(promise, {+ loading: "Sending test...",+ success: "Test sent",+ error: (error) => {+ if (isTRPCClientError(error)) {+ return error.message;+ }+ if (error instanceof Error) {+ return error.message;+ }+ return "Failed to send test";+ },+ });+ await promise;+ } catch (error) {+ console.error(error);+ }+ });+ }++ return (+ <div>+ <Button+ variant="outline"+ size="sm"+ type="button"+ onClick={testAction}+ disabled={isPending}+ >+ Send Test+ </Button>+ </div>+ );+}diff --git a/apps/dashboard/src/components/forms/components/telegram-manual-input.tsx b/apps/dashboard/src/components/forms/components/telegram-manual-input.tsxnew file mode 100644index 000000000..d7734bbcd--- /dev/null+++ b/apps/dashboard/src/components/forms/components/telegram-manual-input.tsx@@ -0,0 +1,59 @@+"use client";++import { Link } from "@/components/common/link";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@openstatus/ui/components/ui/form";+import { Input } from "@openstatus/ui/components/ui/input";+import type { UseFormReturn } from "react-hook-form";+import type { FormValues } from "../notifications/form-telegram";++interface TelegramManualInputProps {+ form: UseFormReturn<FormValues>;+ successMsg?: string;+ showDescription?: boolean;+}++export function TelegramManualInput({+ form,+ successMsg,+ showDescription = true,+}: TelegramManualInputProps) {+ return (+ <FormField+ control={form.control}+ name="data.chatId"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Telegram Chat ID</FormLabel>+ <FormControl>+ <Input placeholder="1234567890" {...field} />+ </FormControl>+ <FormMessage />+ {successMsg && (+ <div className="font-medium text-green-600 text-sm">+ {successMsg}+ </div>+ )}+ {showDescription && (+ <FormDescription>+ Enter the Telegram chat ID to send notifications to.{" "}+ <Link+ href="https://docs.openstatus.dev/reference/notification/#telegram"+ rel="noreferrer"+ target="_blank"+ >+ Learn more+ </Link>+ </FormDescription>+ )}+ </FormItem>+ )}+ />+ );+}diff --git a/apps/dashboard/src/components/forms/components/telegram-qr-connection.tsx b/apps/dashboard/src/components/forms/components/telegram-qr-connection.tsxnew file mode 100644index 000000000..989a71a0c--- /dev/null+++ b/apps/dashboard/src/components/forms/components/telegram-qr-connection.tsx@@ -0,0 +1,114 @@+import { Button } from "@openstatus/ui/components/ui/button";+import { Input } from "@openstatus/ui/components/ui/input";+import { Label } from "@openstatus/ui/components/ui/label";+import type { UseFormReturn } from "react-hook-form";+import type { FormValues } from "../notifications/form-telegram";+import { TelegramManualInput } from "./telegram-manual-input";+import TelegramQRCode from "./telegram-qrcode";++interface TelegramQRConnectionProps {+ form: UseFormReturn<FormValues>;+ token?: string;+ isLoading: boolean;+ isPolling?: boolean;+ flowStep: "private" | "group";+ privateChatId: string | null;+ userName?: string | null;+ groupTitle?: string | null;+ onReset?: () => void;+ onConfirmPrivateChat?: () => void;+}++export function TelegramQRConnection({+ form,+ token,+ isLoading,+ isPolling,+ flowStep,+ privateChatId,+ userName,+ groupTitle,+ onReset,+ onConfirmPrivateChat,+}: TelegramQRConnectionProps) {+ const chatId = form.watch("data.chatId");+ const isGroup = !!groupTitle;++ // When we have a chat ID (group or private), show the manual input with connection info+ if (chatId) {+ const successMsg = isGroup+ ? `Connected to ${groupTitle}`+ : `Connected to ${userName || "Unknown"}'s private chat`;+ return (+ <div className="flex flex-col gap-2">+ <TelegramManualInput+ form={form}+ successMsg={successMsg}+ showDescription={false}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={onReset}+ className="w-full"+ >+ {isGroup ? "Reset Group ID" : "Add Group"}+ </Button>+ </div>+ );+ }++ // When we have a private chat ID, show read-only info with second QR code+ if (privateChatId && flowStep === "group") {+ return (+ <div className="flex flex-col gap-2">+ {/* Show read-only private chat info */}+ <div className="space-y-2">+ <Label>Private Chat ID</Label>+ <Input value={privateChatId} readOnly className="bg-muted" />+ {userName && (+ <div className="font-medium text-green-600 text-sm">+ {`Connected to: ${userName}`}+ </div>+ )}+ </div>++ {/* Show second QR code for group connection */}+ <div className="text-muted-foreground text-sm">+ Step 2 of 2: Add bot to your group+ </div>+ <TelegramQRCode+ chatType="group"+ token={token}+ isLoading={isLoading}+ isPolling={isPolling}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={onConfirmPrivateChat}+ className="w-full"+ >+ Use private chat only+ </Button>+ </div>+ );+ }++ // Initial state: show first QR code for private chat connection+ return (+ <div className="flex flex-col gap-2">+ <div className="text-muted-foreground text-sm">+ Step 1 of 2: Connect your Telegram account+ </div>+ <TelegramQRCode+ chatType="private"+ token={token}+ isLoading={isLoading}+ isPolling={isPolling}+ />+ </div>+ );+}diff --git a/apps/dashboard/src/components/forms/components/telegram-qrcode.tsx b/apps/dashboard/src/components/forms/components/telegram-qrcode.tsxnew file mode 100644index 000000000..a671cd537--- /dev/null+++ b/apps/dashboard/src/components/forms/components/telegram-qrcode.tsx@@ -0,0 +1,51 @@+import { QRCode } from "@openstatus/ui/components/ui/qr-code";+import { Skeleton } from "@openstatus/ui/components/ui/skeleton";+import { Loader2 } from "lucide-react";++export default function TelegramQRCode({+ chatType,+ token,+ isLoading,+ isPolling,+}: {+ chatType: "group" | "private";+ token?: string | undefined;+ isLoading: boolean;+ isPolling?: boolean;+}) {+ const telegramBotUserName = process.env.NEXT_PUBLIC_TELEGRAM_BOT_USERNAME;++ // Grpoup : t.me/<bot_username>?startgroup=<parameter>&admin=<permissions>+ // Private Chat: t.me/<bot_username>?start=<parameter>++ const qrURL =+ chatType === "group"+ ? `https://t.me/${telegramBotUserName}?startgroup=${token}&admin=post_messages`+ : `https://t.me/${telegramBotUserName}?start=${token}`;++ return (+ <div className="flex flex-col items-center justify-center gap-2">+ {isLoading ? (+ <Skeleton className="h-[200px] w-[200px]" />+ ) : token ? (+ <QRCode data={qrURL} className="overflow-hidden rounded-md" />+ ) : null}+ <div className="flex items-center gap-2 text-muted-foreground text-sm">+ {isLoading ? (+ "Generating QR Code..."+ ) : isPolling ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" />+ {chatType === "private"+ ? "Retrieving your account..."+ : "Waiting for group connection..."}+ </>+ ) : chatType === "private" ? (+ "Scan the QR code to connect your account"+ ) : (+ "Scan to add the bot to your group"+ )}+ </div>+ </div>+ );+}diff --git a/apps/dashboard/src/components/forms/notifications/form-telegram.tsx b/apps/dashboard/src/components/forms/notifications/form-telegram.tsxindex 765c75f4c..d65152019 100644--- a/apps/dashboard/src/components/forms/notifications/form-telegram.tsx+++ b/apps/dashboard/src/components/forms/notifications/form-telegram.tsx@@ -10,25 +10,24 @@ import {FormMessage,} from "@openstatus/ui/components/ui/form";-import { Link } from "@/components/common/link";import {FormCardContent,FormCardSeparator,} from "@/components/forms/form-card";import { useFormSheetDirty } from "@/components/forms/form-sheet";-import { useTRPC } from "@/lib/trpc/client";import { zodResolver } from "@hookform/resolvers/zod";-import { Button } from "@openstatus/ui/components/ui/button";import { Form } from "@openstatus/ui/components/ui/form";import { Input } from "@openstatus/ui/components/ui/input";import { Label } from "@openstatus/ui/components/ui/label";import { cn } from "@openstatus/ui/lib/utils";-import { useMutation } from "@tanstack/react-query";import { isTRPCClientError } from "@trpc/client";import React, { useTransition } from "react";import { useForm } from "react-hook-form";import { toast } from "sonner";import { z } from "zod";+import { TelegramConnectionFlow } from "../components/telegram-connection-flow";+import { TelegramFormActions } from "../components/telegram-form-actions";+import { TelegramManualInput } from "../components/telegram-manual-input";const schema = z.object({name: z.string(),@@ -36,10 +35,11 @@ const schema = z.object({data: z.object({chatId: z.string(),}),+ chatType: z.enum(["group", "private"]),monitors: z.array(z.number()),});-type FormValues = z.infer<typeof schema>;+export type FormValues = z.infer<typeof schema>;export function FormTelegram({monitors,@@ -60,21 +60,25 @@ export function FormTelegram({data: {chatId: "",},+ chatType: "private",monitors: [],},});const [isPending, startTransition] = useTransition();const { setIsDirty } = useFormSheetDirty();- const trpc = useTRPC();- const sendTestMutation = useMutation(- trpc.notification.sendTest.mutationOptions(),- );const formIsDirty = form.formState.isDirty;React.useEffect(() => {setIsDirty(formIsDirty);}, [formIsDirty, setIsDirty]);+ // Check if we're editing an existing notification (has chatID) or creating a new one+ const isEditMode = React.useMemo(() => {+ return Boolean(defaultValues?.data?.chatId);+ }, [defaultValues]);++ const [mode, setMode] = React.useState<"qr" | "manual" | null>(null);+function submitAction(values: FormValues) {if (isPending) return;@@ -92,39 +96,10 @@ export function FormTelegram({},});await promise;- } catch (error) {- console.error(error);- }- });- }-- function testAction() {- if (isPending) return;- startTransition(async () => {- try {- const provider = form.getValues("provider");- const data = form.getValues("data");- const promise = sendTestMutation.mutateAsync({- provider,- data: {- telegram: { chatId: data.chatId },- },- });- toast.promise(promise, {- loading: "Sending test...",- success: "Test sent",- error: (error) => {- if (isTRPCClientError(error)) {- return error.message;- }- if (error instanceof Error) {- return error.message;- }- return "Failed to send test";- },- });- await promise;+ // Reset UI state after successful submission+ setMode(null);+ form.reset();} catch (error) {console.error(error);}@@ -155,39 +130,20 @@ export function FormTelegram({</FormItem>)}/>- <FormField- control={form.control}- name="data.chatId"- render={({ field }) => (- <FormItem>- <FormLabel>Telegram Chat ID</FormLabel>- <FormControl>- <Input placeholder="1234567890" {...field} />- </FormControl>- <FormMessage />- <FormDescription>- Enter the Telegram chat ID to send notifications to.{" "}- <Link- href="https://docs.openstatus.dev/reference/notification/#telegram"- rel="noreferrer"- target="_blank"- >- Learn more- </Link>- </FormDescription>- </FormItem>+ <div className="flex flex-col gap-4">+ {isEditMode ? (+ // Edit mode: Show editable chatID input only+ <TelegramManualInput form={form} />+ ) : (+ // Create mode: Show QR/manual connection flow+ <TelegramConnectionFlow+ form={form}+ mode={mode}+ onModeChange={setMode}+ />)}- />- <div>- <Button- variant="outline"- size="sm"- type="button"- onClick={testAction}- >- Send Test- </Button></div>+ <TelegramFormActions form={form} isPending={isPending} /></FormCardContent><FormCardSeparator /><FormCardContent>diff --git a/apps/dashboard/src/hooks/use-telegram-connection.ts b/apps/dashboard/src/hooks/use-telegram-connection.tsnew file mode 100644index 000000000..1c27e0202--- /dev/null+++ b/apps/dashboard/src/hooks/use-telegram-connection.ts@@ -0,0 +1,200 @@+"use client";++import type { FormValues } from "@/components/forms/notifications/form-telegram";+import { useTRPC } from "@/lib/trpc/client";+import { useQuery } from "@tanstack/react-query";+import React, { useReducer, useTransition } from "react";+import type { UseFormReturn } from "react-hook-form";+import { toast } from "sonner";++interface UseTelegramConnectionProps {+ form: UseFormReturn<FormValues>;+ mode: "qr" | "manual" | null;+}++interface TelegramConnectionState {+ flowStep: "private" | "group";+ privateChatId: string | null;+ userName: string | null;+ groupTitle: string | null;+ sessionStartTime: number | null;+}++type TelegramConnectionAction =+ | { type: "SET_SESSION_START_TIME"; payload: number | null }+ | { type: "RESET_STATE" }+ | { type: "RESET_GROUP_CONNECTION" }+ | {+ type: "SET_PRIVATE_CONNECTION_DATA";+ payload: {+ privateChatId: string;+ userName: string;+ };+ }+ | {+ type: "SET_GROUP_CONNECTION_DATA";+ payload: {+ groupTitle: string;+ chatId: string;+ };+ };++const initialState: TelegramConnectionState = {+ flowStep: "private",+ privateChatId: null,+ userName: null,+ groupTitle: null,+ sessionStartTime: null,+};++function telegramConnectionReducer(+ state: TelegramConnectionState,+ action: TelegramConnectionAction,+): TelegramConnectionState {+ switch (action.type) {+ case "SET_SESSION_START_TIME":+ return { ...state, sessionStartTime: action.payload };+ case "RESET_STATE":+ return initialState;+ case "RESET_GROUP_CONNECTION":+ return {+ ...state,+ groupTitle: null,+ sessionStartTime: Math.floor(Date.now() / 1000),+ flowStep: state.privateChatId ? "group" : "private",+ };+ case "SET_PRIVATE_CONNECTION_DATA":+ return {+ ...state,+ privateChatId: action.payload.privateChatId,+ userName: action.payload.userName,+ flowStep: "group",+ };+ case "SET_GROUP_CONNECTION_DATA":+ return {+ ...state,+ groupTitle: action.payload.groupTitle,+ };+ default:+ return state;+ }+}++export function useTelegramConnection({+ form,+ mode,+}: UseTelegramConnectionProps) {+ const [isPending, startTransition] = useTransition();+ const trpc = useTRPC();+ const [state, dispatch] = useReducer(telegramConnectionReducer, initialState);++ // Create Telegram Token+ const { data: tokenData, isLoading: isTokenLoading } = useQuery({+ ...trpc.notification.createTelegramToken.queryOptions(),+ refetchOnWindowFocus: false,+ });++ // Set session start time when entering QR mode+ React.useEffect(() => {+ if (mode === "qr") {+ dispatch({+ type: "SET_SESSION_START_TIME",+ payload: Math.floor(Date.now() / 1000),+ });+ } else if (mode === null) {+ dispatch({ type: "SET_SESSION_START_TIME", payload: null });+ }+ }, [mode]);++ // Cleanup: Reset UI state when component unmounts (e.g., on discard)+ React.useEffect(() => {+ return () => {+ // This runs when component unmounts+ dispatch({ type: "RESET_STATE" });+ };+ }, []);++ // Start polling for updates+ const { data: updates } = useQuery({+ ...trpc.notification.getTelegramUpdates.queryOptions({+ privateChatId:+ state.flowStep === "group"+ ? state.privateChatId ?? undefined+ : undefined,+ since: state.sessionStartTime ?? undefined,+ }),+ enabled:+ !!tokenData?.token && !form.getValues("data.chatId") && mode === "qr",+ refetchInterval: 5000,+ });++ React.useEffect(() => {+ if (updates && updates.length > 0) {+ const lastUpdate = updates[updates.length - 1];++ // Phase 1: Private chat ID received+ if (lastUpdate.chatType === "private" && state.flowStep === "private") {+ dispatch({+ type: "SET_PRIVATE_CONNECTION_DATA",+ payload: {+ privateChatId: lastUpdate.chatId,+ userName: lastUpdate.user?.first_name || "Unknown",+ },+ });+ toast.success(+ `Connected to ${lastUpdate.user?.first_name || "Unknown"}'s account. Now add the bot to your group.`,+ );+ }+ // Phase 2: Group chat ID received+ else if (lastUpdate.chatType === "group" && state.flowStep === "group") {+ dispatch({+ type: "SET_GROUP_CONNECTION_DATA",+ payload: {+ groupTitle: lastUpdate.chatTitle || "Unknown",+ chatId: lastUpdate.chatId,+ },+ });+ startTransition(() => {+ form.setValue("data.chatId", lastUpdate.chatId, {+ shouldDirty: true,+ });+ toast.success(+ `Connected to group "${lastUpdate.chatTitle || "Unknown"}"`,+ );+ });+ }+ }+ }, [updates, form, state.flowStep]);++ const resetConnection = React.useCallback(() => {+ form.setValue("data.chatId", "", { shouldDirty: true });+ dispatch({ type: "RESET_GROUP_CONNECTION" });+ }, [form]);++ const confirmPrivateChat = React.useCallback(() => {+ if (state.privateChatId) {+ startTransition(() => {+ form.setValue("data.chatId", state.privateChatId ?? "", {+ shouldDirty: true,+ });+ toast.success(+ `Connected to ${state.userName || "Unknown"}'s private chat`,+ );+ });+ }+ }, [form, state.privateChatId, state.userName]);++ return {+ tokenData,+ isTokenLoading,+ flowStep: state.flowStep,+ privateChatId: state.privateChatId,+ userName: state.userName,+ groupTitle: state.groupTitle,+ isPolling:+ !!tokenData?.token && !form.watch("data.chatId") && mode === "qr",+ resetConnection,+ confirmPrivateChat,+ isPending,+ };+}diff --git a/apps/web/public/assets/posts/telegram-group-qr-integration/telegram.png b/apps/web/public/assets/posts/telegram-group-qr-integration/telegram.pngnew file mode 100644index 000000000..239388e6fBinary files /dev/null and b/apps/web/public/assets/posts/telegram-group-qr-integration/telegram.png differdiff --git a/apps/web/src/content/pages/blog/telegram-group-qr-integration.mdx b/apps/web/src/content/pages/blog/telegram-group-qr-integration.mdxnew file mode 100644index 000000000..a8edaf1f6--- /dev/null+++ b/apps/web/src/content/pages/blog/telegram-group-qr-integration.mdx@@ -0,0 +1,232 @@+---+title: "Connecting Telegram Groups Without a Webhook"+description: "How we implemented a two-phase QR code flow to securely link Telegram groups to OpenStatus using Redis, polling, and stale-update filtering — no webhooks needed."+author: "Moulik Aggarwal"+publishedAt: "2026-02-21"+image: "/assets/posts/telegram-group-qr-integration/telegram.png"+category: "engineering"+---++Most Telegram bot integrations follow the same playbook: spin up a webhook endpoint, expose it to the internet, and handle updates as they arrive. It's well-documented, straightforward, and used by just about every platform that offers a "Connect your Telegram" button.++We didn't do that.++This post explains the two-phase QR code flow we built to connect Telegram groups to OpenStatus — and why the approach we took is more reliable, simpler to deploy, and doesn't require us to maintain a live webhook endpoint at all.++---++## The Problem with Webhooks++Webhooks are powerful, but they come with operational overhead that can exceed the complexity of a one-time setup flow:++- **Infrastructure requirements**: You need a publicly accessible HTTPS endpoint that stays online 24/7+- **Request handling**: You must implement retry logic, ensure request ordering, and handle deduplication+- **Security validation**: Every incoming request needs verification against a Telegram secret token+- **State consistency**: Mismatches between the webhook receiver and your database become a real problem at scale++For our use case — a one-time group connection during initial setup — this felt disproportionate. We weren't building a real-time chat pipeline. We were building a configuration UI.++The alternative? Telegram's `getUpdates` long-polling API. It's the simpler sibling of webhooks, designed for bots that pull updates on demand rather than receive them pushed. We already had the infrastructure: a working API, Redis, and a frontend capable of polling. So we leaned in.++---++## The Two-Phase Flow++The core challenge with Telegram group notifications is that **you can't directly obtain a group chat ID from a user**. Unlike a "Log in with Telegram" flow, groups don't have a built-in sign-in mechanism. The user can't just authenticate and grant group access.++The solution is a two-step handshake:++**Phase 1 — Identity Verification (Private Chat)**++The user scans a QR code that opens a direct message with the bot, pre-filled with `/start <token>`. When they send it, the bot receives a private message containing the token. We verify the token matches what we stored in Redis for that workspace, then return the user's private `chatId` to the frontend.++**Phase 2 — Group Detection**++Now that we know *who* initiated the flow (via their private `chatId`), we wait for that same user to add our bot to a group. The bot receives a `new_chat_members` update. We verify:+- The bot was actually added to the group+- The bot was added *by the same user from Phase 1*+- The event happened *after* the session started++Once both phases complete, we have the group's `chatId` — which is what gets stored and used for alert delivery.++---++## Token Management: One Key per Workspace++During Phase 1, we need to issue a short-lived, single-use token that links a QR scan back to a specific OpenStatus workspace.++Our strategy is simple: **one Redis key per workspace**.++```+telegram:workspace_token:${workspaceId} → "a3kXp9bN1qRt" (30 min TTL)+```++The token is a 12-character random ID generated with `nanoid(12)`. This is short enough to fit comfortably in a Telegram deep-link URL parameter (Telegram limits `start` parameters to 64 characters, giving us plenty of headroom), yet random enough to be effectively unguessable.++Key properties of this design:++- **One active token per workspace** — generating a new QR code automatically invalidates the previous one. There's no accumulation of stale tokens floating around.+- **30-minute hard expiry** — set at the Redis level using TTL, so cleanup is free and automatic.+- **Single-use deletion** — once Phase 1 succeeds, we immediately delete the key. Even if a user somehow replays the same QR code, it won't match anymore.++```ts+// Phase 1 server-side verification+const tokenKey = `telegram:workspace_token:${workspaceId}`;+const storedToken = await redis.get<string>(tokenKey);++if (storedToken && receivedToken === storedToken) {+ await redis.del(tokenKey); // one-time use+ return { chatId: String(message.chat.id), user: message.from };+}+```++This approach scales horizontally: adding new workspaces requires no coordination between API instances, since each one can independently manage its own Redis keys.++---++## Stale Update Prevention: Timestamp Filtering++Here's the subtle problem with `getUpdates`: **Telegram's API returns updates from the last 24 hours by default**. If a user previously added the bot to a group (even accidentally), that event would still be in the update feed.++Without filtering, Phase 2 would instantly succeed with stale data — connecting the user to the wrong group.++Our fix: **session start time**.++When the user clicks "Connect with QR", the frontend records a Unix timestamp (`sessionStartTime = Math.floor(Date.now() / 1000)`). This value is passed as `since` with every polling request. The backend skips any update older than this threshold.++```ts+const recentUpdates = since+ ? updates.filter((u) => u.message && u.message.date >= since)+ : updates;+```++This also cleanly handles the **reset flow**. If a user accidentally adds the bot to the wrong group, they can click "Reset Group ID". We clear the stored `chatId`, generate a new `sessionStartTime`, and resume polling. The previous group-add event is now older than the new session start — so it gets filtered out automatically, with no server-side cleanup needed.++The beauty of this approach: **the client drives the filtering logic**, and the server is just a passive validator. No state needs to be stored on the backend beyond the 30-minute token.++---++## Ownership Verification in Phase 2++Detecting that the bot was added to a group is straightforward. But we need to make sure *the right user* did it. Otherwise, any user who scans the QR could add the bot to an arbitrary group that doesn't belong to them.++The verification chain in Phase 2:++1. The update must be a `group` or `supergroup` event (not a private chat)+2. The `new_chat_members` array must include our bot's username+3. The `message.from.id` must match the `privateChatId` returned from Phase 1+4. The `message.date` must be `>= since` (the session start time)+++```ts+function extractGroupBotAddition(update, privateChatId, botUsername) {+ const { message } = update;+ if (!message || !["group", "supergroup"].includes(message.chat.type)) return null;+ if (String(message.from.id) !== privateChatId) return null;++ // Telegram uses all three field names inconsistently across versions+ const isBotAdded =+ message.new_chat_participant?.username === botUsername ||+ message.new_chat_member?.username === botUsername ||+ message.new_chat_members?.some((m) => m.username === botUsername);++ if (!isBotAdded) return null;++ return { chatId: String(message.chat.id), chatTitle: message.chat.title };+}+```++All three Telegram field variants (`new_chat_participant`, `new_chat_member`, `new_chat_members`) are checked because the field name varies across bot API versions and group types. It's defensive, but necessary — we've learned that Telegram's API isn't always consistent across versions and group configurations.++---++## Frontend State: A Reducer-Driven Flow++Managing the two-phase flow on the client required careful state handling. We used `useReducer` to model the flow explicitly, treating the entire QR connection process as a state machine.++The state machine looks like this:++```+flowStep: "private" → (Phase 1 success) → flowStep: "group" → (Phase 2 success)+ ↓+ (Phase 2 success)+ ↓+ chatId written to form+```++The reducer handles five actions:++| Action | Effect |+|--------|--------|+| `SET_SESSION_START_TIME` | Captures Unix timestamp when QR mode is entered |+| `SET_PRIVATE_CONNECTION_DATA` | Stores `privateChatId`, advances flow to `"group"` step |+| `SET_GROUP_CONNECTION_DATA` | Stores `groupTitle`, triggers form update with final `chatId` |+| `RESET_GROUP_CONNECTION` | Clears group data, generates new `sessionStartTime`, keeps `privateChatId` |+| `RESET_STATE` | Full reset on unmount or user discard |++The polling query is driven by this state:++```ts+const { data: updates } = useQuery({+ ...trpc.notification.getTelegramUpdates.queryOptions({+ privateChatId: state.flowStep === "group" ? state.privateChatId : undefined,+ since: state.sessionStartTime ?? undefined,+ }),+ enabled: !!tokenData?.token && !form.watch("data.chatId") && mode === "qr",+ refetchInterval: 5000,+});+```++Polling automatically stops once `chatId` is set in the form — there's no manual cleanup needed. The `enabled` flag handles it reactively. This means the frontend naturally stops polling once the connection succeeds, freeing up resources without explicit teardown logic.++---++## Why This Architecture Scales++The thing that makes this design hold up at scale is that **the server stays stateless between polls**.++- No WebSocket connections to manage or monitor for leaks+- No long-lived processes that could accumulate state+- No event listeners that need memory cleanup+- No webhook endpoint that requires uptime SLAs++Each poll is a short-lived tRPC call that:+1. Fetches updates from Telegram+2. Runs a few comparisons against a single Redis key+3. Returns the result++Redis handles token TTL and single-use deletion atomically. The frontend manages all UX state locally via the reducer. There's no coordination needed between API instances.++Adding a new workspace doesn't change anything server-side. The Redis key pattern `telegram:workspace_token:${workspaceId}` scales horizontally with zero coordination between instances. If you double your API servers, the system just works.++---++## The User Experience++From a user's perspective, the flow is straightforward:++1. Open the "Connect Telegram" panel in OpenStatus+2. Scan the QR code with your phone+3. Telegram opens a DM with the bot — you hit send on the pre-filled `/start` message+4. The dashboard immediately detects the connection and shows your Telegram username+5. You add the bot to your Telegram group+6. The dashboard detects the group and auto-fills the notification channel+7. Alerts now flow directly to that group++No webhooks. No manual token copying. No server-side secrets exposed in URLs. No stale data from leftover `getUpdates` history. The setup takes about 10 seconds.++---++## Key Takeaways++This pattern works well when:++- **Setup is one-time**: You're not streaming real-time events; you're wiring up a configuration+- **Latency tolerance exists**: A 5-second poll interval is acceptable (vs. instant webhook delivery)+- **Operational simplicity matters**: You want to avoid running a public endpoint with its attendant security and availability requirements++If you need true real-time bidirectional communication with Telegram (a chat application, for instance), webhooks are the right choice. But for one-shot integrations like "connect your group for alerts," this polling approach is simpler, more reliable, and far easier to deploy.++---++_Set up Telegram alerting on [Openstatus](/app/login) and get notified the moment a monitor fails._\ No newline at end of filediff --git a/apps/web/src/data/author.ts b/apps/web/src/data/author.tsindex ff49b4bf0..f859a6f90 100644--- a/apps/web/src/data/author.ts+++ b/apps/web/src/data/author.ts@@ -2,12 +2,14 @@ export const author = {"Maximilian Kaske": {name: "Maximilian Kaske",url: "https://x.com/mxkaske",- image: "/assets/authors/max.png",},"Thibault Le Ouay Ducasse": {name: "Thibault Le Ouay Ducasse",url: "https://bsky.app/profile/thibaultleouay.dev",- image: "/assets/authors/thibault.jpeg",+ },+ "Moulik Aggarwal": {+ name: "Moulik Aggarwal",+ url: "https://x.com/aggmoulik",},} as const;diff --git a/packages/api/src/router/notification.ts b/packages/api/src/router/notification.tsindex 84a1c6560..863628a8c 100644--- a/packages/api/src/router/notification.ts+++ b/packages/api/src/router/notification.ts@@ -22,7 +22,13 @@ import { sendTest as sendGoogleChatTest } from "@openstatus/notification-google-import { sendTest as sendGrafanaTest } from "@openstatus/notification-grafana-oncall";import { sendTest as sendTelegramTest } from "@openstatus/notification-telegram";import { sendTest as sendWhatsAppTest } from "@openstatus/notification-twillio-whatsapp";+import { redis } from "@openstatus/upstash";+import { nanoid } from "nanoid";+import {+ type TelegramGetUpdatesResponse,+ processTelegramUpdates,+} from "../service/telegram-updates";import { createTRPCRouter, protectedProcedure } from "../trpc";export const notificationRouter = createTRPCRouter({@@ -310,4 +316,50 @@ export const notificationRouter = createTRPCRouter({message: "Invalid provider",});}),++ createTelegramToken: protectedProcedure.query(async (opts) => {+ const workspaceId = opts.ctx.workspace.id;+ const randomId = nanoid(12);+ const EXPIRY = 1800; // 30 minutes++ await redis.set(`telegram:workspace_token:${workspaceId}`, randomId, {+ ex: EXPIRY,+ });++ return { token: randomId };+ }),++ getTelegramUpdates: protectedProcedure+ .input(+ z+ .object({+ privateChatId: z.string().optional(),+ since: z.number().optional(),+ })+ .optional(),+ )+ .query(async (opts) => {+ const res = await fetch(+ `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/getUpdates`,+ );+ const data = (await res.json()) as TelegramGetUpdatesResponse;+ if (!data.ok || !data.result) return [];++ const botUsername = process.env.NEXT_PUBLIC_TELEGRAM_BOT_USERNAME;+ if (!botUsername) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Telegram bot username not configured",+ });+ }++ return processTelegramUpdates({+ updates: data.result,+ workspaceId: opts.ctx.workspace.id,+ privateChatId: opts.input?.privateChatId,+ since: opts.input?.since,+ botUsername,+ redisClient: redis,+ });+ }),});diff --git a/packages/api/src/service/telegram-updates.ts b/packages/api/src/service/telegram-updates.tsnew file mode 100644index 000000000..d48e402d6--- /dev/null+++ b/packages/api/src/service/telegram-updates.ts@@ -0,0 +1,256 @@+import type { redis } from "@openstatus/upstash";++// ---- Telegram API Types -----------------------------------------------------++interface TelegramUser {+ id: number;+ is_bot: boolean;+ first_name: string;+ username?: string;+ language_code?: string;+}++interface TelegramChat {+ id: number;+ type: "private" | "group" | "supergroup" | "channel";+ title?: string;+ first_name?: string;+ all_members_are_administrators?: boolean;+}++interface TelegramMessage {+ message_id: number;+ from: TelegramUser;+ chat: TelegramChat;+ date: number;+ text?: string;+ entities?: Array<{+ offset: number;+ length: number;+ type: string;+ }>;+ new_chat_members?: TelegramUser[];+ new_chat_member?: TelegramUser;+ new_chat_participant?: TelegramUser;+}++interface TelegramChatMember {+ user: TelegramUser;+ status:+ | "member"+ | "administrator"+ | "left"+ | "creator"+ | "restricted"+ | "kicked";+ can_be_edited?: boolean;+ can_manage_chat?: boolean;+ can_change_info?: boolean;+ can_delete_messages?: boolean;+ can_invite_users?: boolean;+ can_restrict_members?: boolean;+ can_pin_messages?: boolean;+ can_manage_topics?: boolean;+ can_promote_members?: boolean;+ can_manage_video_chats?: boolean;+ can_post_stories?: boolean;+ can_edit_stories?: boolean;+ can_delete_stories?: boolean;+ is_anonymous?: boolean;+}++interface TelegramMyChatMemberUpdate {+ chat: TelegramChat;+ from: TelegramUser;+ date: number;+ old_chat_member: TelegramChatMember;+ new_chat_member: TelegramChatMember;+}++export interface TelegramUpdate {+ update_id: number;+ message?: TelegramMessage;+ my_chat_member?: TelegramMyChatMemberUpdate;+}++export interface TelegramGetUpdatesResponse {+ ok: boolean;+ result: TelegramUpdate[];+}++export type ValidUpdate =+ | {+ chatId: string;+ chatType: "private";+ user: { id: number; first_name: string; username?: string };+ }+ | {+ chatId: string;+ chatType: "group";+ chatTitle?: string;+ user: { id: number; first_name: string; username?: string };+ };++// ---- Helpers ----------------------------------------------------------------++function extractPrivateChatStart(+ update: TelegramUpdate,+ token: string,+): {+ chatId: string;+ user: { id: number; first_name: string; username?: string };+} | null {+ const { message } = update;++ if (+ !message ||+ message.chat.type !== "private" ||+ !message.text?.startsWith("/start ") ||+ !message.from+ ) {+ return null;+ }++ const receivedToken = message.text.split(" ")[1];+ if (!receivedToken || receivedToken !== token) return null;++ return {+ chatId: String(message.chat.id),+ user: {+ id: message.from.id,+ first_name: message.from.first_name,+ username: message.from.username,+ },+ };+}++function extractGroupBotAddition(+ update: TelegramUpdate,+ privateChatId: string,+ botUsername: string,+): {+ chatId: string;+ chatTitle?: string;+ user: { id: number; first_name: string; username?: string };+} | null {+ // Modern Telegram Bot API (v5.0+): bot additions come as my_chat_member updates+ if (update.my_chat_member) {+ const { my_chat_member } = update;++ const isInvalidGroupAddition =+ (my_chat_member.chat.type !== "group" &&+ my_chat_member.chat.type !== "supergroup") ||+ String(my_chat_member.from.id) !== privateChatId ||+ my_chat_member.new_chat_member.user.username !== botUsername ||+ (my_chat_member.new_chat_member.status !== "member" &&+ my_chat_member.new_chat_member.status !== "administrator");++ if (isInvalidGroupAddition) {+ return null;+ }++ return {+ chatId: String(my_chat_member.chat.id),+ chatTitle: my_chat_member.chat.title,+ user: {+ id: my_chat_member.from.id,+ first_name: my_chat_member.from.first_name,+ username: my_chat_member.from.username,+ },+ };+ }++ // Legacy fallback: service message with new_chat_member fields+ const { message } = update;++ const isInvalidGroupAddition =+ !message ||+ (message.chat.type !== "group" && message.chat.type !== "supergroup") ||+ !message.from ||+ String(message.from.id) !== privateChatId;++ if (isInvalidGroupAddition) {+ return null;+ }++ const isBotAdded =+ message.new_chat_participant?.username === botUsername ||+ message.new_chat_member?.username === botUsername ||+ message.new_chat_members?.some((m) => m.username === botUsername);++ if (!isBotAdded) return null;++ return {+ chatId: String(message.chat.id),+ chatTitle: message.chat.title,+ user: {+ id: message.from.id,+ first_name: message.from.first_name,+ username: message.from.username,+ },+ };+}++// ---- Main logic -------------------------------------------------------------++export async function processTelegramUpdates(args: {+ updates: TelegramUpdate[];+ workspaceId: number;+ privateChatId?: string;+ since?: number;+ botUsername: string;+ redisClient: typeof redis;+}): Promise<ValidUpdate[]> {+ const {+ updates,+ workspaceId,+ privateChatId,+ since,+ botUsername,+ redisClient,+ } = args;++ const validUpdates: ValidUpdate[] = [];++ // 1. Pre-filter by timestamp+ const recentUpdates = since+ ? updates.filter((u) => {+ if (u.message) return u.message.date >= since;+ if (u.my_chat_member) return u.my_chat_member.date >= since;+ return false;+ })+ : updates;++ // 2. Phase 1: private /start (no privateChatId filter)+ if (!privateChatId) {+ const tokenKey = `telegram:workspace_token:${workspaceId}`;+ const storedToken = await redisClient.get<string>(tokenKey);++ if (storedToken) {+ for (const update of recentUpdates) {+ const result = extractPrivateChatStart(update, storedToken);+ if (result) {+ // Single-use token: delete and stop+ await redisClient.del(tokenKey);+ validUpdates.push({ chatType: "private", ...result });+ break;+ }+ }+ }+ }+ // 3. Phase 2: group/supergroup additions+ else {+ for (const update of recentUpdates) {+ const result = extractGroupBotAddition(+ update,+ privateChatId,+ botUsername,+ );+ if (result) {+ validUpdates.push({ chatType: "group", ...result });+ }+ }+ }++ return validUpdates;+}diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 03d8b529a..6245018f0 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -83,6 +83,7 @@"lucide-react": "0.525.0","luxon": "3.5.0","next": "16.1.6",+ "qr-code-styling": "1.9.2","radix-ui": "1.4.3","react": "19.2.3","react-day-picker": "8.10.1",diff --git a/packages/ui/src/components/ui/qr-code.tsx b/packages/ui/src/components/ui/qr-code.tsxnew file mode 100644index 000000000..0ad8d0e1d--- /dev/null+++ b/packages/ui/src/components/ui/qr-code.tsx@@ -0,0 +1,70 @@+"use client";++import { useEffect, useRef, useState } from "react";+import QRCodeStyling, {+ type Options as QRCodeOptions,+} from "qr-code-styling";+import { cn } from "@openstatus/ui/lib/utils";++export interface QRCodeProps {+ data: string;+ image?: string;+ size?: number;+ className?: string;+ options?: Partial<QRCodeOptions>;+}++export const QRCode = ({+ data,+ image,+ size = 200,+ className,+ options,+}: QRCodeProps) => {+ const [qrCode] = useState<QRCodeStyling>(+ new QRCodeStyling({+ width: size,+ height: size,+ type: "svg",+ data,+ image,+ dotsOptions: {+ color: "#000000",+ type: "rounded",+ },+ backgroundOptions: {+ color: "#ffffff",+ },+ imageOptions: {+ crossOrigin: "anonymous",+ margin: 20,+ },+ ...options,+ }),+ );+ const ref = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (ref.current) {+ qrCode.append(ref.current);+ }+ }, [qrCode, ref]);++ useEffect(() => {+ if (!qrCode) return;+ qrCode.update({+ data,+ image,+ width: size,+ height: size,+ ...options,+ });+ }, [qrCode, data, image, size, options]);++ return (+ <div+ ref={ref}+ className={cn("flex items-center justify-center", className)}+ />+ );+};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d6b503e95..e4bfa9543 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2166,6 +2166,9 @@ importers:next-themes:specifier: 0.4.6+ qr-code-styling:+ specifier: 1.9.2+ version: 1.9.2radix-ui:specifier: 1.4.3version: 1.4.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -10513,6 +10516,13 @@ packages:resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==}+ resolution: {integrity: sha512-RgJaZJ1/RrXJ6N0j7a+pdw3zMBmzZU4VN2dtAZf8ZggCfRB5stEQ3IoDNGaNhYY3nnZKYlYSLl5YkfWN5dPutg==}+ engines: {node: '>=18.18.0'}++ resolution: {integrity: sha512-pItrW0Z9HnDBnFmgiNrY1uxRdri32Uh9EjNYLPVC2zZ3ZRIIEqBoDgm4DkvDwNNDHTK7FNkmr8zAa77BYc9xNw==}+resolution: {integrity: sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==}engines: {node: '>=0.6'}@@ -21674,6 +21684,12 @@ snapshots:+ dependencies:+ qrcode-generator: 1.5.2++ [email protected]: {}+dependencies:side-channel: 1.1.0