Skip to content

Open-source status page, incident response and uptime monitoring

feat: telegram bot notifications (#1622)

Maximilian Kaske5de1e45aac72
diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json
index 3c1a959aa..3432334ee 100644
--- a/apps/dashboard/package.json
+++ b/apps/dashboard/package.json
@@ -36,6 +36,7 @@
"@openstatus/notification-opsgenie": "workspace:*",
"@openstatus/notification-pagerduty": "workspace:*",
"@openstatus/notification-slack": "workspace:*",
+ "@openstatus/notification-telegram": "workspace:*",
"@openstatus/notification-webhook": "workspace:*",
"@openstatus/react": "workspace:*",
"@openstatus/regions": "workspace:*",
diff --git a/apps/dashboard/src/components/forms/notifications/form-discord.tsx b/apps/dashboard/src/components/forms/notifications/form-discord.tsx
index 78489319b..659ec14c4 100644
--- a/apps/dashboard/src/components/forms/notifications/form-discord.tsx
+++ b/apps/dashboard/src/components/forms/notifications/form-discord.tsx
@@ -163,7 +163,12 @@ export function FormDiscord({
)}
/>
<div>
- <Button variant="outline" size="sm" onClick={testAction}>
+ <Button
+ variant="outline"
+ size="sm"
+ type="button"
+ onClick={testAction}
+ >
Send Test
</Button>
</div>
diff --git a/apps/dashboard/src/components/forms/notifications/form-telegram.tsx b/apps/dashboard/src/components/forms/notifications/form-telegram.tsx
new file mode 100644
index 000000000..9f4def9dd
--- /dev/null
+++ b/apps/dashboard/src/components/forms/notifications/form-telegram.tsx
@@ -0,0 +1,241 @@
+"use client";
+
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/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 { Button } from "@/components/ui/button";
+import { Form } from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { useTRPC } from "@/lib/trpc/client";
+import { cn } from "@/lib/utils";
+import { zodResolver } from "@hookform/resolvers/zod";
+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";
+
+const schema = z.object({
+ name: z.string(),
+ provider: z.literal("telegram"),
+ data: z.object({
+ chatId: z.string(),
+ }),
+ monitors: z.array(z.number()),
+});
+
+type FormValues = z.infer<typeof schema>;
+
+export function FormTelegram({
+ monitors,
+ defaultValues,
+ onSubmit,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
+ defaultValues?: FormValues;
+ onSubmit: (values: FormValues) => Promise<void>;
+ monitors: { id: number; name: string }[];
+}) {
+ const form = useForm<FormValues>({
+ resolver: zodResolver(schema),
+ defaultValues: defaultValues ?? {
+ name: "",
+ provider: "telegram",
+ data: {
+ chatId: "",
+ },
+ 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]);
+
+ function submitAction(values: FormValues) {
+ if (isPending) return;
+
+ startTransition(async () => {
+ try {
+ const promise = onSubmit(values);
+ toast.promise(promise, {
+ loading: "Saving...",
+ success: "Saved",
+ error: (error) => {
+ if (isTRPCClientError(error)) {
+ return error.message;
+ }
+ return "Failed to save";
+ },
+ });
+ 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 (error instanceof Error) {
+ return error.message;
+ }
+ return "Failed to send test";
+ },
+ });
+ await promise;
+ } catch (error) {
+ console.error(error);
+ }
+ });
+ }
+
+ return (
+ <Form {...form}>
+ <form
+ className={cn("grid gap-4", className)}
+ onSubmit={form.handleSubmit(submitAction)}
+ {...props}
+ >
+ <FormCardContent className="grid gap-4">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input placeholder="My Notifier" {...field} />
+ </FormControl>
+ <FormMessage />
+ <FormDescription>
+ Enter a descriptive name for your notifier.
+ </FormDescription>
+ </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>
+ <Button
+ variant="outline"
+ size="sm"
+ type="button"
+ onClick={testAction}
+ >
+ Send Test
+ </Button>
+ </div>
+ </FormCardContent>
+ <FormCardSeparator />
+ <FormCardContent>
+ <FormField
+ control={form.control}
+ name="monitors"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Monitors</FormLabel>
+ <FormDescription>
+ Select the monitors you want to notify.
+ </FormDescription>
+ <div className="grid gap-3">
+ <div className="flex items-center gap-2">
+ <FormControl>
+ <Checkbox
+ id="all"
+ checked={field.value?.length === monitors.length}
+ onCheckedChange={(checked) => {
+ field.onChange(
+ checked ? monitors.map((m) => m.id) : [],
+ );
+ }}
+ />
+ </FormControl>
+ <Label htmlFor="all">Select all</Label>
+ </div>
+ {monitors.map((item) => (
+ <div key={item.id} className="flex items-center gap-2">
+ <FormControl>
+ <Checkbox
+ id={String(item.id)}
+ checked={field.value?.includes(item.id)}
+ onCheckedChange={(checked) => {
+ const newValue = checked
+ ? [...(field.value || []), item.id]
+ : field.value?.filter((id) => id !== item.id);
+ field.onChange(newValue);
+ }}
+ />
+ </FormControl>
+ <Label htmlFor={String(item.id)}>{item.name}</Label>
+ </div>
+ ))}
+ </div>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </FormCardContent>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/dashboard/src/components/forms/notifications/form.tsx b/apps/dashboard/src/components/forms/notifications/form.tsx
index 38436e5cd..d258430c0 100644
--- a/apps/dashboard/src/components/forms/notifications/form.tsx
+++ b/apps/dashboard/src/components/forms/notifications/form.tsx
@@ -31,6 +31,7 @@ const schema = z.object({
"opsgenie",
"pagerduty",
"ntfy",
+ "telegram",
]),
data: z.record(z.string(), z.string()).or(z.string()),
monitors: z.array(z.number()),
diff --git a/apps/dashboard/src/components/forms/notifications/sheet.tsx b/apps/dashboard/src/components/forms/notifications/sheet.tsx
index baa7c5dcd..e92b431e6 100644
--- a/apps/dashboard/src/components/forms/notifications/sheet.tsx
+++ b/apps/dashboard/src/components/forms/notifications/sheet.tsx
@@ -63,7 +63,11 @@ export function FormSheetNotifier({
data:
typeof defaultValues?.data === "string"
? defaultValues?.data
- : defaultValues?.data?.[provider],
+ : defaultValues?.data &&
+ typeof defaultValues.data === "object" &&
+ provider in defaultValues.data
+ ? defaultValues.data[provider]
+ : defaultValues?.data,
}
: undefined
}
diff --git a/apps/dashboard/src/data/notifications.client.ts b/apps/dashboard/src/data/notifications.client.ts
index 9851920d5..f93de98fd 100644
--- a/apps/dashboard/src/data/notifications.client.ts
+++ b/apps/dashboard/src/data/notifications.client.ts
@@ -5,8 +5,9 @@ import { FormOpsGenie } from "@/components/forms/notifications/form-opsgenie";
import { FormPagerDuty } from "@/components/forms/notifications/form-pagerduty";
import { FormSlack } from "@/components/forms/notifications/form-slack";
import { FormSms } from "@/components/forms/notifications/form-sms";
+import { FormTelegram } from "@/components/forms/notifications/form-telegram";
import { FormWebhook } from "@/components/forms/notifications/form-webhook";
-import { DiscordIcon } from "@openstatus/icons";
+import { DiscordIcon, TelegramIcon } from "@openstatus/icons";
import { OpsGenieIcon } from "@openstatus/icons";
import { PagerDutyIcon } from "@openstatus/icons";
import { SlackIcon } from "@openstatus/icons";
@@ -15,6 +16,7 @@ import { sendTest as sendTestNtfy } from "@openstatus/notification-ntfy";
import { sendTest as sendTestOpsGenie } from "@openstatus/notification-opsgenie";
import { sendTest as sendTestPagerDuty } from "@openstatus/notification-pagerduty";
import { sendTestSlackMessage as sendTestSlack } from "@openstatus/notification-slack";
+import { sendTest as sendTestTelegram } from "@openstatus/notification-telegram";
import { sendTest as sendTestWebhook } from "@openstatus/notification-webhook";
import {
BellIcon,
@@ -104,6 +106,12 @@ export const config = {
form: FormNtfy,
sendTest: sendTestNtfy,
},
+ telegram: {
+ icon: TelegramIcon,
+ label: "Telegram",
+ form: FormTelegram,
+ sendTest: sendTestTelegram,
+ },
};
export type NotifierProvider = keyof typeof config;
diff --git a/apps/docs/src/content/docs/reference/notification.mdx b/apps/docs/src/content/docs/reference/notification.mdx
index 77de11c8c..347ef0d3d 100644
--- a/apps/docs/src/content/docs/reference/notification.mdx
+++ b/apps/docs/src/content/docs/reference/notification.mdx
@@ -24,6 +24,16 @@ Require a [discord webhook](https://support.discord.com/hc/en-us/articles/228383
Require a phone number
+### Telegram
+
+Requires to know the chat id.
+
+> This integration is fully functional but accessing the chat id is not smooth yet. It requires manual effort to access your chat id. **You can ask RawDataBot `@raw_info_bot` for your chat id.**
+
+The bot's id is `@openstatushq_bot` to make sure you are getting the correct notifications.
+
+Please
+
### Webhook
- URL (require)
diff --git a/apps/web/public/assets/changelog/telegram-bot-integration.png b/apps/web/public/assets/changelog/telegram-bot-integration.png
new file mode 100644
index 000000000..cd453bc11
Binary files /dev/null and b/apps/web/public/assets/changelog/telegram-bot-integration.png differ
diff --git a/apps/web/src/content/pages/changelog/telegram-bot-integration.mdx b/apps/web/src/content/pages/changelog/telegram-bot-integration.mdx
new file mode 100644
index 000000000..eaa4afa1e
--- /dev/null
+++ b/apps/web/src/content/pages/changelog/telegram-bot-integration.mdx
@@ -0,0 +1,10 @@
+---
+title: "Telegram Bot Integration"
+description: ""
+image: "/assets/changelog/telegram-bot-integration.png"
+publishedAt: "2025-12-09"
+author: "openstatus"
+category: "notifications"
+---
+
+You can connect your uptime notifications to the `@openstatushq_bot` telegram bot.
\ No newline at end of file
diff --git a/apps/web/src/content/pages/product/uptime-monitoring.mdx b/apps/web/src/content/pages/product/uptime-monitoring.mdx
index 44b260d71..ad232c6a5 100644
--- a/apps/web/src/content/pages/product/uptime-monitoring.mdx
+++ b/apps/web/src/content/pages/product/uptime-monitoring.mdx
@@ -87,7 +87,7 @@ Set different notification channels and **get notified** whenever a not satisfyi
We support:
-- Socials: Slack, Discord
+- Socials: Slack, Discord, Telegram Bot
- Direct: Email, SMS
- Incident Management: OpsGenie, PagerDuty
- Custom: Webhook, Ntfy
diff --git a/apps/workflows/Dockerfile b/apps/workflows/Dockerfile
index f59e2ce1f..774c44291 100644
--- a/apps/workflows/Dockerfile
+++ b/apps/workflows/Dockerfile
@@ -40,6 +40,7 @@ RUN \
--mount=type=bind,target=packages/notifications/opsgenie/package.json,source=packages/notifications/opsgenie/package.json \
--mount=type=bind,target=packages/notifications/pagerduty/package.json,source=packages/notifications/pagerduty/package.json \
--mount=type=bind,target=packages/notifications/slack/package.json,source=packages/notifications/slack/package.json \
+ --mount=type=bind,target=packages/notifications/telegram/package.json,source=packages/notifications/telegram/package.json \
--mount=type=bind,target=packages/notifications/twillio-sms/package.json,source=packages/notifications/twillio-sms/package.json \
--mount=type=bind,target=packages/notifications/webhook/package.json,source=packages/notifications/webhook/package.json \
--mount=type=bind,target=packages/regions/package.json,source=packages/regions/package.json \
diff --git a/apps/workflows/dofigen.lock b/apps/workflows/dofigen.lock
index 17a8dd934..482430636 100644
--- a/apps/workflows/dofigen.lock
+++ b/apps/workflows/dofigen.lock
@@ -12,14 +12,35 @@ effective: |
- /packages/error
- /packages/tracker
builders:
- install:
+ build:
fromImage:
path: oven/bun
digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
label:
+ org.opencontainers.image.base.name: docker.io/oven/bun:1.3.3
+ org.opencontainers.image.stage: build
org.opencontainers.image.base.digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
+ workdir: /app/apps/workflows
+ env:
+ NODE_ENV: production
+ copy:
+ - paths:
+ - .
+ target: /app/
+ - fromBuilder: install
+ paths:
+ - /app/node_modules
+ target: /app/node_modules
+ run:
+ - bun build --compile --target bun --sourcemap --format=cjs src/index.ts --outfile=app --external '@libsql/*' --external libsql
+ install:
+ fromImage:
+ path: oven/bun
+ digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
+ label:
org.opencontainers.image.base.name: docker.io/oven/bun:1.3.3
org.opencontainers.image.stage: install
+ org.opencontainers.image.base.digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
workdir: /app/
run:
- bun install --production --frozen-lockfile --verbose
@@ -50,6 +71,8 @@ effective: |
source: packages/notifications/pagerduty/package.json
- target: packages/notifications/slack/package.json
source: packages/notifications/slack/package.json
+ - target: packages/notifications/telegram/package.json
+ source: packages/notifications/telegram/package.json
- target: packages/notifications/twillio-sms/package.json
source: packages/notifications/twillio-sms/package.json
- target: packages/notifications/webhook/package.json
@@ -71,8 +94,8 @@ effective: |
path: oven/bun
digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
label:
- org.opencontainers.image.base.digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
org.opencontainers.image.base.name: docker.io/oven/bun:1.3.3
+ org.opencontainers.image.base.digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
workdir: /app/apps/workflows
copy:
- paths:
@@ -85,8 +108,8 @@ effective: |
path: debian
digest: sha256:530a3348fc4b5734ffe1a137ddbcee6850154285251b53c3425c386ea8fac77b
label:
- org.opencontainers.image.base.digest: sha256:530a3348fc4b5734ffe1a137ddbcee6850154285251b53c3425c386ea8fac77b
org.opencontainers.image.base.name: docker.io/debian:bullseye-slim
+ org.opencontainers.image.base.digest: sha256:530a3348fc4b5734ffe1a137ddbcee6850154285251b53c3425c386ea8fac77b
run:
- apt update && apt install -y ca-certificates && update-ca-certificates
libsql:
@@ -94,8 +117,8 @@ effective: |
path: oven/bun
digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
label:
- org.opencontainers.image.base.digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
org.opencontainers.image.base.name: docker.io/oven/bun:1.3.3
+ org.opencontainers.image.base.digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
workdir: /app/
copy:
- fromBuilder: docker
@@ -104,39 +127,18 @@ effective: |
target: /app/package.json
run:
- bun install
- build:
- fromImage:
- path: oven/bun
- digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
- label:
- org.opencontainers.image.base.name: docker.io/oven/bun:1.3.3
- org.opencontainers.image.base.digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
- org.opencontainers.image.stage: build
- workdir: /app/apps/workflows
- env:
- NODE_ENV: production
- copy:
- - paths:
- - .
- target: /app/
- - fromBuilder: install
- paths:
- - /app/node_modules
- target: /app/node_modules
- run:
- - bun build --compile --target bun --sourcemap --format=cjs src/index.ts --outfile=app --external '@libsql/*' --external libsql
fromImage:
path: debian
digest: sha256:530a3348fc4b5734ffe1a137ddbcee6850154285251b53c3425c386ea8fac77b
label:
- io.dofigen.version: 2.5.1
+ org.opencontainers.image.source: https://github.com/openstatusHQ/openstatus
+ org.opencontainers.image.vendor: OpenStatus
+ org.opencontainers.image.title: OpenStatus Workflows
org.opencontainers.image.base.name: docker.io/debian:bullseye-slim
org.opencontainers.image.base.digest: sha256:530a3348fc4b5734ffe1a137ddbcee6850154285251b53c3425c386ea8fac77b
- org.opencontainers.image.title: OpenStatus Workflows
- org.opencontainers.image.vendor: OpenStatus
- org.opencontainers.image.description: Background job processing and probe scheduling for OpenStatus
org.opencontainers.image.authors: OpenStatus Team
- org.opencontainers.image.source: https://github.com/openstatusHQ/openstatus
+ io.dofigen.version: 2.5.1
+ org.opencontainers.image.description: Background job processing and probe scheduling for OpenStatus
workdir: /app/
copy:
- fromBuilder: build
@@ -162,17 +164,17 @@ effective: |
- port: 3000
images:
docker.io:
- library:
- debian:
- bullseye-slim:
- digest: sha256:530a3348fc4b5734ffe1a137ddbcee6850154285251b53c3425c386ea8fac77b
oven:
bun:
1.3.3:
digest: sha256:fbf8e67e9d3b806c86be7a2f2e9bae801f2d9212a21db4dcf8cc9889f5a3c9c4
+ library:
+ debian:
+ bullseye-slim:
+ digest: sha256:530a3348fc4b5734ffe1a137ddbcee6850154285251b53c3425c386ea8fac77b
resources:
dofigen.yml:
- hash: 3544a43f3fd756222397a837650af396178e9fde624ba9b1b32bc1943324cc02
+ hash: 297382ef47be04c67f610380fadff8e2b9333ab28594ff6e0512b75a23d4c3b0
content: |
ignore:
- node_modules
@@ -205,6 +207,7 @@ resources:
- packages/notifications/opsgenie/package.json
- packages/notifications/pagerduty/package.json
- packages/notifications/slack/package.json
+ - packages/notifications/telegram/package.json
- packages/notifications/twillio-sms/package.json
- packages/notifications/webhook/package.json
- packages/regions/package.json
diff --git a/apps/workflows/dofigen.yml b/apps/workflows/dofigen.yml
index 5a3166d2b..5795361b2 100644
--- a/apps/workflows/dofigen.yml
+++ b/apps/workflows/dofigen.yml
@@ -29,6 +29,7 @@ builders:
- packages/notifications/opsgenie/package.json
- packages/notifications/pagerduty/package.json
- packages/notifications/slack/package.json
+ - packages/notifications/telegram/package.json
- packages/notifications/twillio-sms/package.json
- packages/notifications/webhook/package.json
- packages/regions/package.json
diff --git a/apps/workflows/package.json b/apps/workflows/package.json
index ad1b12aba..1ec136118 100644
--- a/apps/workflows/package.json
+++ b/apps/workflows/package.json
@@ -19,6 +19,7 @@
"@openstatus/notification-opsgenie": "workspace:*",
"@openstatus/notification-pagerduty": "workspace:*",
"@openstatus/notification-slack": "workspace:*",
+ "@openstatus/notification-telegram": "workspace:*",
"@openstatus/notification-twillio-sms": "workspace:*",
"@openstatus/notification-webhook": "workspace:*",
"@openstatus/regions": "workspace:*",
diff --git a/apps/workflows/src/checker/utils.ts b/apps/workflows/src/checker/utils.ts
index daa056009..413222fb1 100644
--- a/apps/workflows/src/checker/utils.ts
+++ b/apps/workflows/src/checker/utils.ts
@@ -3,6 +3,7 @@ import type {
Notification,
NotificationProvider,
} from "@openstatus/db/src/schema";
+import type { Region } from "@openstatus/db/src/schema/constants";
import {
sendAlert as sendDiscordAlert,
sendDegraded as sendDiscordDegraded,
@@ -18,30 +19,31 @@ import {
sendDegraded as sendNtfyDegraded,
sendRecovery as sendNtfyRecovery,
} from "@openstatus/notification-ntfy";
+import {
+ sendAlert as sendOpsGenieAlert,
+ sendDegraded as sendOpsGenieDegraded,
+ sendRecovery as sendOpsGenieRecovery,
+} from "@openstatus/notification-opsgenie";
+import {
+ sendDegraded as sendPagerDutyDegraded,
+ sendRecovery as sendPagerDutyRecovery,
+ sendAlert as sendPagerdutyAlert,
+} from "@openstatus/notification-pagerduty";
import {
sendAlert as sendSlackAlert,
sendDegraded as sendSlackDegraded,
sendRecovery as sendSlackRecovery,
} from "@openstatus/notification-slack";
+import {
+ sendAlert as sendTelegramAlert,
+ sendDegraded as sendTelegramDegraded,
+ sendRecovery as sendTelegramRecovery,
+} from "@openstatus/notification-telegram";
import {
sendAlert as sendSmsAlert,
sendDegraded as sendSmsDegraded,
sendRecovery as sendSmsRecovery,
} from "@openstatus/notification-twillio-sms";
-
-import {
- sendDegraded as sendPagerDutyDegraded,
- sendRecovery as sendPagerDutyRecovery,
- sendAlert as sendPagerdutyAlert,
-} from "@openstatus/notification-pagerduty";
-
-import type { Region } from "@openstatus/db/src/schema/constants";
-import {
- sendAlert as sendOpsGenieAlert,
- sendDegraded as sendOpsGenieDegraded,
- sendRecovery as sendOpsGenieRecovery,
-} from "@openstatus/notification-opsgenie";
-
import {
sendAlert as sendWebhookAlert,
sendDegraded as sendWebhookDegraded,
@@ -115,4 +117,9 @@ export const providerToFunction = {
sendRecovery: sendWebhookRecovery,
sendDegraded: sendWebhookDegraded,
},
+ telegram: {
+ sendAlert: sendTelegramAlert,
+ sendRecovery: sendTelegramRecovery,
+ sendDegraded: sendTelegramDegraded,
+ },
} satisfies Record<NotificationProvider, Notif>;
diff --git a/packages/api/package.json b/packages/api/package.json
index 088a61971..156ffb331 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -13,6 +13,7 @@
"@openstatus/db": "workspace:*",
"@openstatus/emails": "workspace:*",
"@openstatus/error": "workspace:*",
+ "@openstatus/notification-telegram": "workspace:*",
"@openstatus/regions": "workspace:*",
"@openstatus/tinybird": "workspace:*",
"@openstatus/upstash": "workspace:*",
diff --git a/packages/api/src/router/notification.ts b/packages/api/src/router/notification.ts
index bdc2d55d1..74598f216 100644
--- a/packages/api/src/router/notification.ts
+++ b/packages/api/src/router/notification.ts
@@ -11,10 +11,12 @@ import {
notificationsToMonitors,
selectMonitorSchema,
selectNotificationSchema,
+ telegramDataSchema,
} from "@openstatus/db/src/schema";
import { Events } from "@openstatus/analytics";
import { SchemaError } from "@openstatus/error";
+import { sendTest as sendTelegramTest } from "@openstatus/notification-telegram";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const notificationRouter = createTRPCRouter({
@@ -282,6 +284,7 @@ export const notificationRouter = createTRPCRouter({
}),
)
.mutation(async (opts) => {
+ console.log(opts.input);
const whereCondition: SQL[] = [
eq(notification.id, opts.input.id),
eq(notification.workspaceId, opts.ctx.workspace.id),
@@ -326,12 +329,14 @@ export const notificationRouter = createTRPCRouter({
and(eq(notificationsToMonitors.notificationId, opts.input.id)),
);
- await tx.insert(notificationsToMonitors).values(
- opts.input.monitors.map((monitorId) => ({
- notificationId: opts.input.id,
- monitorId,
- })),
- );
+ if (opts.input.monitors.length) {
+ await tx.insert(notificationsToMonitors).values(
+ opts.input.monitors.map((monitorId) => ({
+ notificationId: opts.input.id,
+ monitorId,
+ })),
+ );
+ }
});
}),
@@ -445,4 +450,36 @@ export const notificationRouter = createTRPCRouter({
)
.run();
}),
+
+ sendTest: protectedProcedure
+ .input(
+ z.object({
+ provider: z.enum(notificationProvider),
+ data: z.record(
+ z.enum(notificationProvider),
+ z.record(z.string(), z.string()).or(z.string()),
+ ),
+ }),
+ )
+ .mutation(async (opts) => {
+ if (opts.input.provider === "telegram") {
+ const _data = telegramDataSchema.safeParse(opts.input.data);
+ if (!_data.success) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: SchemaError.fromZod(_data.error, opts.input).message,
+ });
+ }
+ await sendTelegramTest({
+ chatId: _data.data.telegram.chatId,
+ });
+
+ return;
+ }
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Invalid provider",
+ });
+ }),
});
diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.ts
index e5943e1d1..faace3be4 100644
--- a/packages/api/src/router/page.ts
+++ b/packages/api/src/router/page.ts
@@ -40,7 +40,7 @@ if (process.env.NODE_ENV === "test") {
require("../test/preload");
}
-const redis = Redis.fromEnv();
+const _redis = Redis.fromEnv();
// Helper functions to reuse Vercel API logic
async function addDomainToVercel(domain: string) {
diff --git a/packages/db/src/schema/notifications/constants.ts b/packages/db/src/schema/notifications/constants.ts
index 1876df226..4d840ba82 100644
--- a/packages/db/src/schema/notifications/constants.ts
+++ b/packages/db/src/schema/notifications/constants.ts
@@ -7,4 +7,5 @@ export const notificationProvider = [
"slack",
"sms",
"webhook",
+ "telegram",
] as const;
diff --git a/packages/db/src/schema/notifications/validation.ts b/packages/db/src/schema/notifications/validation.ts
index 5036b955a..33b5e5c3e 100644
--- a/packages/db/src/schema/notifications/validation.ts
+++ b/packages/db/src/schema/notifications/validation.ts
@@ -62,6 +62,9 @@ export const opsgenieDataSchema = z.object({
region: z.enum(["us", "eu"]),
}),
});
+export const telegramDataSchema = z.object({
+ telegram: z.object({ chatId: z.string() }),
+});
export const NotificationDataSchema = z.union([
emailDataSchema,
@@ -72,6 +75,7 @@ export const NotificationDataSchema = z.union([
opsgenieDataSchema,
ntfyDataSchema,
webhookDataSchema,
+ telegramDataSchema,
]);
export const InsertNotificationWithDataSchema = z.discriminatedUnion(
diff --git a/packages/icons/src/index.tsx b/packages/icons/src/index.tsx
index 16e45f192..a013b6a86 100644
--- a/packages/icons/src/index.tsx
+++ b/packages/icons/src/index.tsx
@@ -7,3 +7,4 @@ export * from "./opsgenie";
export * from "./fly";
export * from "./railway";
export * from "./koyeb";
+export * from "./telegram";
diff --git a/packages/icons/src/telegram.tsx b/packages/icons/src/telegram.tsx
new file mode 100644
index 000000000..8c8a0b04d
--- /dev/null
+++ b/packages/icons/src/telegram.tsx
@@ -0,0 +1,15 @@
+export function TelegramIcon(props: React.ComponentProps<"svg">) {
+ return (
+ <svg
+ role="img"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ stroke="currentColor"
+ fill="currentColor"
+ {...props}
+ >
+ <title>Telegram</title>
+ <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
+ </svg>
+ );
+}
diff --git a/packages/notifications/discord/package.json b/packages/notifications/discord/package.json
index b7ef216bf..9a7d58c0a 100644
--- a/packages/notifications/discord/package.json
+++ b/packages/notifications/discord/package.json
@@ -9,6 +9,7 @@
"devDependencies": {
"@openstatus/tsconfig": "workspace:*",
"@types/node": "22.10.2",
+ "bun-types": "1.3.1",
"typescript": "5.7.2"
}
}
diff --git a/packages/notifications/discord/src/index.test.ts b/packages/notifications/discord/src/index.test.ts
new file mode 100644
index 000000000..bab388b10
--- /dev/null
+++ b/packages/notifications/discord/src/index.test.ts
@@ -0,0 +1,166 @@
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { selectNotificationSchema } from "@openstatus/db/src/schema";
+import {
+ sendAlert,
+ sendDegraded,
+ sendRecovery,
+ sendTestDiscordMessage,
+} from "./index";
+
+describe("Discord Notifications", () => {
+ // biome-ignore lint/suspicious/noExplicitAny: <explanation>
+ let fetchMock: any = undefined;
+
+ beforeEach(() => {
+ fetchMock = spyOn(global, "fetch").mockImplementation(() =>
+ Promise.resolve(new Response(null, { status: 200 })),
+ );
+ });
+
+ afterEach(() => {
+ if (fetchMock) {
+ fetchMock.mockRestore();
+ }
+ });
+
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "iad",
+ });
+
+ const createMockNotification = () => ({
+ id: 1,
+ name: "Discord Notification",
+ provider: "discord",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: '{"discord":"https://discord.com/api/webhooks/123456789/abcdefgh"}',
+ });
+
+ test("Send Alert", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Something went wrong",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe(
+ "https://discord.com/api/webhooks/123456789/abcdefgh",
+ );
+ expect(callArgs[1].method).toBe("POST");
+ expect(callArgs[1].headers["Content-Type"]).toBe("application/json");
+
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.content).toContain("🚨 Alert");
+ expect(body.content).toContain("API Health Check");
+ expect(body.content).toContain("Something went wrong");
+ expect(body.username).toBe("OpenStatus Notifications");
+ expect(body.avatar_url).toBeDefined();
+ });
+
+ test("Send Recovery", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendRecovery({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 200,
+ message: "Service recovered",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.content).toContain("✅ Recovered");
+ expect(body.content).toContain("API Health Check");
+ });
+
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ message: "Service degraded",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.content).toContain("⚠️ Degraded");
+ expect(body.content).toContain("API Health Check");
+ });
+
+ test("Send Test Discord Message", async () => {
+ const webhookUrl = "https://discord.com/api/webhooks/123456789/abcdefgh";
+
+ const result = await sendTestDiscordMessage(webhookUrl);
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe(webhookUrl);
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.content).toContain("🧪 Test");
+ expect(body.content).toContain("OpenStatus");
+ });
+
+ test("Send Test Discord Message with empty webhookUrl", async () => {
+ const result = await sendTestDiscordMessage("");
+
+ expect(result).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ test("Handle fetch error gracefully", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ // Should not throw - function catches errors internally
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/notifications/email/src/index.test.ts b/packages/notifications/email/src/index.test.ts
index b74cd0b7a..36ca67034 100644
--- a/packages/notifications/email/src/index.test.ts
+++ b/packages/notifications/email/src/index.test.ts
@@ -1,119 +1,166 @@
-import {
- describe,
- mock,
- // jest,
- test,
-} from "bun:test";
-
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { selectNotificationSchema } from "@openstatus/db/src/schema";
import { sendAlert, sendDegraded, sendRecovery } from "./index";
+const sendMonitorAlertMock = mock(async (_callArgs) => {});
+
mock.module("@openstatus/emails/src/client", () => ({
- EmailClient: mock(() => ({
- sendMonitorAlert: mock(async () => {}),
- })),
+ EmailClient: mock((_args: { apiKey: string }) => {
+ return {
+ sendMonitorAlert: sendMonitorAlertMock,
+ };
+ }),
}));
describe("Email Notifications", () => {
- test("Send degraded", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
+ beforeEach(() => {
+ sendMonitorAlertMock.mockClear();
+ });
- const a = {
- id: 1,
- name: "email Notification",
- provider: "email",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"email":"[email protected]"}',
- };
+ afterEach(() => {
+ sendMonitorAlertMock.mockClear();
+ });
- const n = selectNotificationSchema.parse(a);
- await sendDegraded({
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "iad",
+ });
+
+ const createMockNotification = () => ({
+ id: 1,
+ name: "Email Notification",
+ provider: "email",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: '{"email":"[email protected]"}',
+ });
+
+ test("Send Alert", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
message: "Something went wrong",
+ latency: 1500,
+ region: "iad",
cronTimestamp: Date.now(),
});
+
+ expect(sendMonitorAlertMock).toHaveBeenCalledTimes(1);
+ const callArgs = sendMonitorAlertMock.mock.calls[0][0];
+ expect(callArgs.name).toBe("API Health Check");
+ expect(callArgs.type).toBe("alert");
+ expect(callArgs.to).toBe("[email protected]");
+ expect(callArgs.url).toBe("https://api.example.com/health");
+ expect(callArgs.status).toBe("500");
+ expect(callArgs.latency).toBe("1500ms");
+ expect(callArgs.message).toBe("Something went wrong");
+ expect(callArgs.timestamp).toBeDefined();
});
- test("Send Recovered", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
+ test("Send Alert without optional fields", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
- const a = {
- id: 1,
- name: "Email Notification",
- provider: "email",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"email":"[email protected]"}',
- };
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ cronTimestamp: Date.now(),
+ });
+
+ expect(sendMonitorAlertMock).toHaveBeenCalledTimes(1);
+ const callArgs = sendMonitorAlertMock.mock.calls[0][0];
+ expect(callArgs.status).toBeUndefined();
+ expect(callArgs.latency).toBe("N/A");
+ expect(callArgs.region).toBe("N/A");
+ });
+
+ test("Send Recovery", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
- const n = selectNotificationSchema.parse(a);
await sendRecovery({
// @ts-expect-error
monitor,
- notification: n,
- statusCode: 500,
- message: "Something went wrong",
+ notification,
+ statusCode: 200,
+ latency: 100,
+ region: "ams",
cronTimestamp: Date.now(),
});
+
+ expect(sendMonitorAlertMock).toHaveBeenCalledTimes(1);
+ const callArgs = sendMonitorAlertMock.mock.calls[0][0];
+ expect(callArgs.type).toBe("recovery");
+ expect(callArgs.name).toBe("API Health Check");
+ expect(callArgs.to).toBe("[email protected]");
+ expect(callArgs.status).toBe("200");
+ expect(callArgs.latency).toBe("100ms");
});
- test("Send Alert", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
- const a = {
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ latency: 2000,
+ region: "lax",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(sendMonitorAlertMock).toHaveBeenCalledTimes(1);
+ const callArgs = sendMonitorAlertMock.mock.calls[0][0];
+ expect(callArgs.type).toBe("degraded");
+ expect(callArgs.name).toBe("API Health Check");
+ expect(callArgs.status).toBe("503");
+ expect(callArgs.latency).toBe("2000ms");
+ });
+
+ test("Handles invalid notification data gracefully", async () => {
+ const monitor = createMockMonitor();
+ const invalidNotification = selectNotificationSchema.parse({
id: 1,
- name: "PagerDuty Notification",
+ name: "Email Notification",
provider: "email",
workspaceId: 1,
createdAt: new Date(),
updatedAt: new Date(),
- data: '{"email":"[email protected]"}',
- };
-
- const n = selectNotificationSchema.parse(a);
+ data: '{"invalid":"data"}',
+ });
await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
- statusCode: 500,
- message: "Something went wrong",
+ notification: invalidNotification,
cronTimestamp: Date.now(),
});
+
+ // Should not call sendMonitorAlert when data is invalid
+ expect(sendMonitorAlertMock).not.toHaveBeenCalled();
});
});
diff --git a/packages/notifications/ntfy/package.json b/packages/notifications/ntfy/package.json
index c9a591e18..c526c8005 100644
--- a/packages/notifications/ntfy/package.json
+++ b/packages/notifications/ntfy/package.json
@@ -9,6 +9,7 @@
"devDependencies": {
"@openstatus/tsconfig": "workspace:*",
"@types/node": "22.10.2",
+ "bun-types": "1.3.1",
"typescript": "5.7.2"
}
}
diff --git a/packages/notifications/ntfy/src/index.test.ts b/packages/notifications/ntfy/src/index.test.ts
new file mode 100644
index 000000000..527b08c57
--- /dev/null
+++ b/packages/notifications/ntfy/src/index.test.ts
@@ -0,0 +1,271 @@
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { selectNotificationSchema } from "@openstatus/db/src/schema";
+import { sendAlert, sendDegraded, sendRecovery, sendTest } from "./index";
+
+describe("Ntfy Notifications", () => {
+ // biome-ignore lint/suspicious/noExplicitAny: <explanation>
+ let fetchMock: any = undefined;
+
+ beforeEach(() => {
+ fetchMock = spyOn(global, "fetch").mockImplementation(() =>
+ Promise.resolve(new Response(null, { status: 200 })),
+ );
+ });
+
+ afterEach(() => {
+ if (fetchMock) {
+ fetchMock.mockRestore();
+ }
+ });
+
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "us-east-1",
+ });
+
+ const createMockNotification = (withToken = false, withServerUrl = false) => {
+ const data: {
+ ntfy: { topic: string; token?: string; serverUrl?: string };
+ } = {
+ ntfy: {
+ topic: "my-topic",
+ },
+ };
+ if (withToken) {
+ data.ntfy.token = "test-token-123";
+ }
+ if (withServerUrl) {
+ data.ntfy.serverUrl = "https://ntfy.example.com";
+ }
+ return {
+ id: 1,
+ name: "Ntfy Notification",
+ provider: "ntfy",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: JSON.stringify(data),
+ };
+ };
+
+ test("Send Alert with default server", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Something went wrong",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://ntfy.sh/my-topic");
+ expect(callArgs[1].method).toBe("post");
+ expect(callArgs[1].body).toContain("API Health Check");
+ expect(callArgs[1].body).toContain("status code 500");
+ expect(callArgs[1].headers).not.toHaveProperty("Authorization");
+ });
+
+ test("Send Alert with custom server", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(false, true),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://ntfy.example.com/my-topic");
+ });
+
+ test("Send Alert with token", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(true),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[1].headers.Authorization).toBe("Bearer test-token-123");
+ });
+
+ test("Send Alert without statusCode", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ message: "Connection timeout",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[1].body).toContain("error: Connection timeout");
+ });
+
+ test("Send Recovery", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendRecovery({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 200,
+ message: "Service recovered",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[1].body).toContain("is up again");
+ });
+
+ test("Send Recovery with token", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(true),
+ );
+
+ await sendRecovery({
+ // @ts-expect-error
+ monitor,
+ notification,
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[1].headers.Authorization).toBe("Bearer test-token-123");
+ });
+
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ message: "Service degraded",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[1].body).toContain("is degraded");
+ });
+
+ test("Send Test with default server", async () => {
+ const result = await sendTest({
+ topic: "test-topic",
+ });
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://ntfy.sh/test-topic");
+ expect(callArgs[1].body).toBe("This is a test message from OpenStatus");
+ expect(callArgs[1].headers).not.toHaveProperty("Authorization");
+ });
+
+ test("Send Test with custom server", async () => {
+ const result = await sendTest({
+ topic: "test-topic",
+ serverUrl: "https://ntfy.example.com",
+ });
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://ntfy.example.com/test-topic");
+ });
+
+ test("Send Test with token", async () => {
+ const result = await sendTest({
+ topic: "test-topic",
+ token: "test-token",
+ });
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[1].headers.Authorization).toBe("Bearer test-token");
+ });
+
+ test("Handle fetch error gracefully", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ // Should not throw - function catches errors internally
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ test("Send Test returns false on error", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const result = await sendTest({
+ topic: "test-topic",
+ });
+
+ expect(result).toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/notifications/opsgenie/package.json b/packages/notifications/opsgenie/package.json
index 0faf0a7c4..c1a8cd6ab 100644
--- a/packages/notifications/opsgenie/package.json
+++ b/packages/notifications/opsgenie/package.json
@@ -14,6 +14,7 @@
"@types/node": "20.8.0",
"@types/react": "19.2.2",
"@types/react-dom": "19.2.2",
+ "bun-types": "1.3.1",
"typescript": "5.7.2"
}
}
diff --git a/packages/notifications/opsgenie/src/index.test.ts b/packages/notifications/opsgenie/src/index.test.ts
new file mode 100644
index 000000000..6e93bf1ab
--- /dev/null
+++ b/packages/notifications/opsgenie/src/index.test.ts
@@ -0,0 +1,160 @@
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { selectNotificationSchema } from "@openstatus/db/src/schema";
+import { sendAlert, sendDegraded, sendTest } from "./index";
+
+describe("OpsGenie Notifications", () => {
+ // biome-ignore lint/suspicious/noExplicitAny: <explanation>
+ let fetchMock: any = undefined;
+
+ beforeEach(() => {
+ fetchMock = spyOn(global, "fetch").mockImplementation(() =>
+ Promise.resolve(new Response(null, { status: 200 })),
+ );
+ });
+
+ afterEach(() => {
+ if (fetchMock) {
+ fetchMock.mockRestore();
+ }
+ });
+
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "us-east-1",
+ });
+
+ const createMockNotification = (region: "eu" | "us" = "us") => ({
+ id: 1,
+ name: "OpsGenie Notification",
+ provider: "opsgenie",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: JSON.stringify({
+ opsgenie: {
+ apiKey: "test-api-key-123",
+ region,
+ },
+ }),
+ });
+
+ test("Send Alert with US region", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification("us"),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Something went wrong",
+ incidentId: "incident-123",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://api.opsgenie.com/v2/alerts");
+ expect(callArgs[1].method).toBe("POST");
+ expect(callArgs[1].headers["Content-Type"]).toBe("application/json");
+ expect(callArgs[1].headers.Authorization).toBe("GenieKey test-api-key-123");
+
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.message).toBe("API Health Check is down");
+ expect(body.alias).toBe("monitor-1}-incident-123");
+ expect(body.details.severity).toBe("down");
+ expect(body.details.status).toBe(500);
+ expect(body.details.message).toBe("Something went wrong");
+ });
+
+ test("Send Alert with EU region", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification("eu"),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ incidentId: "incident-456",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://api.eu.opsgenie.com/v2/alerts");
+ });
+
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ message: "Service degraded",
+ incidentId: "incident-789",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.details.severity).toBe("degraded");
+ expect(body.message).toBe("API Health Check is down");
+ });
+
+ test("Handle fetch error gracefully", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ // Should not throw - function catches errors internally
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ incidentId: "incident-123",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ test("Send Test returns false on error", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const result = await sendTest({
+ apiKey: "test-api-key",
+ region: "us",
+ });
+
+ expect(result).toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/notifications/pagerduty/src/index.test.ts b/packages/notifications/pagerduty/src/index.test.ts
index edd1e83b7..2af8e7d19 100644
--- a/packages/notifications/pagerduty/src/index.test.ts
+++ b/packages/notifications/pagerduty/src/index.test.ts
@@ -1,14 +1,6 @@
-import {
- afterEach,
- beforeEach,
- describe,
- expect,
- jest,
- spyOn,
- test,
-} from "bun:test";
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { selectNotificationSchema } from "@openstatus/db/src/schema";
-import { sendAlert, sendDegraded, sendRecovery } from "./index";
+import { sendAlert, sendDegraded, sendRecovery, sendTest } from "./index";
describe("PagerDuty Notifications", () => {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
@@ -22,111 +14,193 @@ describe("PagerDuty Notifications", () => {
});
afterEach(() => {
- jest.resetAllMocks();
+ if (fetchMock) {
+ fetchMock.mockRestore();
+ }
});
- test("Send degraded", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "us-east-1",
+ });
- const a = {
- id: 1,
- name: "PagerDuty Notification",
- provider: "pagerduty",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"pagerduty":"{\\"integration_keys\\":[{\\"integration_key\\":\\"my_key\\",\\"name\\":\\"Default Service\\",\\"id\\":\\"ABCD\\",\\"type\\":\\"service\\"}],\\"account\\":{\\"subdomain\\":\\"test\\",\\"name\\":\\"test\\"}}"}',
- };
+ const createMockNotification = () => ({
+ id: 1,
+ name: "PagerDuty Notification",
+ provider: "pagerduty",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: '{"pagerduty":"{\\"integration_keys\\":[{\\"integration_key\\":\\"my_key\\",\\"name\\":\\"Default Service\\",\\"id\\":\\"ABCD\\",\\"type\\":\\"service\\"}],\\"account\\":{\\"subdomain\\":\\"test\\",\\"name\\":\\"test\\"}}"}',
+ });
- const n = selectNotificationSchema.parse(a);
- await sendDegraded({
+ test("Send Alert", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
message: "Something went wrong",
+ incidentId: "incident-123",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
- });
- test("Send Recovered", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://events.pagerduty.com/v2/enqueue");
+ expect(callArgs[1].method).toBe("POST");
- const a = {
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.routing_key).toBe("my_key");
+ expect(body.dedup_key).toBe("monitor-1}-incident-123");
+ expect(body.event_action).toBe("trigger");
+ expect(body.payload.summary).toBe("API Health Check is down");
+ expect(body.payload.severity).toBe("error");
+ expect(body.payload.custom_details.statusCode).toBe(500);
+ expect(body.payload.custom_details.message).toBe("Something went wrong");
+ });
+
+ test("Send Alert with multiple integration keys", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse({
id: 1,
name: "PagerDuty Notification",
provider: "pagerduty",
workspaceId: 1,
createdAt: new Date(),
updatedAt: new Date(),
- data: '{"pagerduty":"{\\"integration_keys\\":[{\\"integration_key\\":\\"my_key\\",\\"name\\":\\"Default Service\\",\\"id\\":\\"ABCD\\",\\"type\\":\\"service\\"}],\\"account\\":{\\"subdomain\\":\\"test\\",\\"name\\":\\"test\\"}}"}',
- };
+ data: '{"pagerduty":"{\\"integration_keys\\":[{\\"integration_key\\":\\"key1\\",\\"name\\":\\"Service 1\\",\\"id\\":\\"ABCD\\",\\"type\\":\\"service\\"},{\\"integration_key\\":\\"key2\\",\\"name\\":\\"Service 2\\",\\"id\\":\\"EFGH\\",\\"type\\":\\"service\\"}],\\"account\\":{\\"subdomain\\":\\"test\\",\\"name\\":\\"test\\"}}"}',
+ });
- const n = selectNotificationSchema.parse(a);
- await sendRecovery({
+ await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
- message: "Something went wrong",
+ message: "Error",
+ incidentId: "incident-456",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[0][1].body).toContain("key1");
+ expect(fetchMock.mock.calls[1][1].body).toContain("key2");
});
- test("Send Alert", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
- const a = {
- id: 1,
- name: "PagerDuty Notification",
- provider: "pagerduty",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"pagerduty":"{\\"integration_keys\\":[{\\"integration_key\\":\\"my_key\\",\\"name\\":\\"Default Service\\",\\"id\\":\\"ABCD\\",\\"type\\":\\"service\\"}],\\"account\\":{\\"subdomain\\":\\"test\\",\\"name\\":\\"test\\"}}"}',
- };
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
- const n = selectNotificationSchema.parse(a);
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ message: "Service degraded",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.payload.summary).toBe("API Health Check is degraded");
+ expect(body.payload.severity).toBe("warning");
+ expect(body.dedup_key).toBe("monitor-1}");
+ });
+
+ test("Send Recovery", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendRecovery({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 200,
+ message: "Service recovered",
+ incidentId: "incident-123",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://events.pagerduty.com/v2/enqueue");
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.routing_key).toBe("my_key");
+ expect(body.dedup_key).toBe("monitor-1}-incident-123");
+ expect(body.event_action).toBe("resolve");
+ });
+ test("Send Test", async () => {
+ const result = await sendTest({
+ integrationKey: "test-integration-key",
+ });
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://events.pagerduty.com/v2/enqueue");
+ expect(callArgs[1].method).toBe("POST");
+
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.routing_key).toBe("test-integration-key");
+ expect(body.dedup_key).toBe("openstatus-test");
+ expect(body.event_action).toBe("trigger");
+ expect(body.payload.summary).toBe("This is a test from OpenStatus");
+ expect(body.payload.severity).toBe("error");
+ expect(body.payload.custom_details.statusCode).toBe(418);
+ });
+
+ test("Send Test returns false on error", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const result = await sendTest({
+ integrationKey: "test-key",
+ });
+
+ expect(result).toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ test("Handle fetch error gracefully", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ // Should not throw - function catches errors internally
await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
- message: "Something went wrong",
+ message: "Error",
+ incidentId: "incident-123",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
diff --git a/packages/notifications/slack/src/index.test.ts b/packages/notifications/slack/src/index.test.ts
index ec520c1df..3ee8a3e81 100644
--- a/packages/notifications/slack/src/index.test.ts
+++ b/packages/notifications/slack/src/index.test.ts
@@ -1,14 +1,11 @@
-import {
- afterEach,
- beforeEach,
- describe,
- expect,
- jest,
- spyOn,
- test,
-} from "bun:test";
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { selectNotificationSchema } from "@openstatus/db/src/schema";
-import { sendAlert, sendDegraded, sendRecovery } from "./index";
+import {
+ sendAlert,
+ sendDegraded,
+ sendRecovery,
+ sendTestSlackMessage,
+} from "./index";
describe("Slack Notifications", () => {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
@@ -22,111 +19,173 @@ describe("Slack Notifications", () => {
});
afterEach(() => {
- jest.resetAllMocks();
+ if (fetchMock) {
+ fetchMock.mockRestore();
+ }
});
- test("Send degraded", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
-
- const a = {
- id: 1,
- name: "slack Notification",
- provider: "slack",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"slack":"https://hooks.slack.com/services/url"}',
- };
-
- const n = selectNotificationSchema.parse(a);
- await sendDegraded({
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "us-east-1",
+ });
+
+ const createMockNotification = () => ({
+ id: 1,
+ name: "Slack Notification",
+ provider: "slack",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: '{"slack":"https://hooks.slack.com/services/url"}',
+ });
+
+ test("Send Alert", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
message: "Something went wrong",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe("https://hooks.slack.com/services/url");
+ expect(callArgs[1].method).toBe("POST");
+
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.blocks).toBeDefined();
+ expect(body.blocks.length).toBeGreaterThan(0);
+ expect(body.blocks[1].text.text).toContain("🚨 Alert");
+ expect(body.blocks[1].text.text).toContain("API Health Check");
+ expect(body.blocks[1].text.text).toContain("Something went wrong");
+ });
+
+ test("Send Alert without statusCode", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ message: "Connection timeout",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.blocks[1].text.text).toContain("_empty_");
});
- test("Send Recovered", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
-
- const a = {
- id: 1,
- name: "slack Notification",
- provider: "slack",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"slack":"https://hooks.slack.com/services/url"}',
- };
-
- const n = selectNotificationSchema.parse(a);
+ test("Send Recovery", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
await sendRecovery({
// @ts-expect-error
monitor,
- notification: n,
- statusCode: 500,
- message: "Something went wrong",
+ notification,
+ statusCode: 200,
+ message: "Service recovered",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.blocks[1].text.text).toContain("✅ Recovered");
+ expect(body.blocks[1].text.text).toContain("API Health Check");
});
- test("Send Alert", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
- const a = {
- id: 1,
- name: "slack Notification",
- provider: "slack",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"slack":"https://hooks.slack.com/services/url"}',
- };
-
- const n = selectNotificationSchema.parse(a);
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ message: "Service degraded",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.blocks[1].text.text).toContain("⚠️ Degraded");
+ expect(body.blocks[1].text.text).toContain("API Health Check");
+ });
+
+ test("Send Test Slack Message", async () => {
+ const webhookUrl = "https://hooks.slack.com/services/test/url";
+ const result = await sendTestSlackMessage(webhookUrl);
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe(webhookUrl);
+
+ const body = JSON.parse(callArgs[1].body);
+ expect(body.blocks[1].text.text).toContain("🧪 Test");
+ expect(body.blocks[1].text.text).toContain("OpenStatus");
+ });
+
+ test("Send Test Slack Message returns false on error", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const result = await sendTestSlackMessage(
+ "https://hooks.slack.com/services/test/url",
+ );
+
+ expect(result).toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ test("Handle fetch error gracefully", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ // Should not throw - function catches errors internally
await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
- message: "Something went wrong",
+ message: "Error",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
diff --git a/packages/notifications/telegram/.gitignore b/packages/notifications/telegram/.gitignore
new file mode 100644
index 000000000..f81d56eaa
--- /dev/null
+++ b/packages/notifications/telegram/.gitignore
@@ -0,0 +1,169 @@
+# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
+
+# Logs
+
+logs
+_.log
+npm-debug.log_
+yarn-debug.log*
+yarn-error.log*
+lerna-debug.log*
+.pnpm-debug.log*
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+
+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
+
+# Runtime data
+
+pids
+_.pid
+_.seed
+\*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+
+lib-cov
+
+# Coverage directory used by tools like istanbul
+
+coverage
+\*.lcov
+
+# nyc test coverage
+
+.nyc_output
+
+# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
+
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+
+bower_components
+
+# node-waf configuration
+
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+
+build/Release
+
+# Dependency directories
+
+node_modules/
+jspm_packages/
+
+# Snowpack dependency directory (https://snowpack.dev/)
+
+web_modules/
+
+# TypeScript cache
+
+\*.tsbuildinfo
+
+# Optional npm cache directory
+
+.npm
+
+# Optional eslint cache
+
+.eslintcache
+
+# Optional stylelint cache
+
+.stylelintcache
+
+# Microbundle cache
+
+.rpt2_cache/
+.rts2_cache_cjs/
+.rts2_cache_es/
+.rts2_cache_umd/
+
+# Optional REPL history
+
+.node_repl_history
+
+# Output of 'npm pack'
+
+\*.tgz
+
+# Yarn Integrity file
+
+.yarn-integrity
+
+# dotenv environment variable files
+
+.env
+.env.development.local
+.env.test.local
+.env.production.local
+.env.local
+
+# parcel-bundler cache (https://parceljs.org/)
+
+.cache
+.parcel-cache
+
+# Next.js build output
+
+.next
+out
+
+# Nuxt.js build / generate output
+
+.nuxt
+dist
+
+# Gatsby files
+
+.cache/
+
+# Comment in the public line in if your project uses Gatsby and not Next.js
+
+# https://nextjs.org/blog/next-9-1#public-directory-support
+
+# public
+
+# vuepress build output
+
+.vuepress/dist
+
+# vuepress v2.x temp and cache directory
+
+.temp
+.cache
+
+# Docusaurus cache and generated files
+
+.docusaurus
+
+# Serverless directories
+
+.serverless/
+
+# FuseBox cache
+
+.fusebox/
+
+# DynamoDB Local files
+
+.dynamodb/
+
+# TernJS port file
+
+.tern-port
+
+# Stores VSCode versions used for testing VSCode extensions
+
+.vscode-test
+
+# yarn v2
+
+.yarn/cache
+.yarn/unplugged
+.yarn/build-state.yml
+.yarn/install-state.gz
+.pnp.\*
diff --git a/packages/notifications/telegram/README.md b/packages/notifications/telegram/README.md
new file mode 100644
index 000000000..8ccc7aaf8
--- /dev/null
+++ b/packages/notifications/telegram/README.md
@@ -0,0 +1,48 @@
+# @openstatus/notification-telegram
+To install dependencies:
+
+```bash
+bun install
+```
+
+To run:
+
+```bash
+bun run src/index.ts
+```
+
+This project was created using `bun init` in bun v1.0.0. [Bun](https://bun.sh)
+is a fast all-in-one JavaScript runtime.
+
+
+---
+
+Important `@BotFather` commands to update the bot.
+
+```
+Change profile image
+/setuserpic
+Change display name
+/setname
+Change bot description
+/setdescription
+Short about text shown in bio preview
+/setabouttext
+```
+
+---
+
+#### TODO
+
+This integration is very "raw". We need to let the user search for their chat id (e.g. by asking RawDataBot `@raw_info_bot`).
+
+In the future, we could work with `/setcommands` behaviors to send the value to our `/getUpdates` endpoint and access the chat id. We will need to forward a specific unique identifier with it to match the chat id with the proper notification.
+
+An improved UX option:
+
+```
+1. user enters `/connect` command
+2. we listen to the `/getUpdates` messages and generate an id, store it for a few days in redis, and send it back to the user's chat id
+3. user enters generated id into openstatus dashboard to connect with chat id - we validate it from the `/getUpdates`
+```
+
diff --git a/packages/notifications/telegram/excalidraw.png b/packages/notifications/telegram/excalidraw.png
new file mode 100644
index 000000000..fb04477fd
Binary files /dev/null and b/packages/notifications/telegram/excalidraw.png differ
diff --git a/packages/notifications/telegram/package.json b/packages/notifications/telegram/package.json
new file mode 100644
index 000000000..77d460f64
--- /dev/null
+++ b/packages/notifications/telegram/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@openstatus/notification-telegram",
+ "version": "1.0.0",
+ "main": "src/index.ts",
+ "dependencies": {
+ "@openstatus/db": "workspace:*",
+ "zod": "3.25.76"
+ },
+ "devDependencies": {
+ "@openstatus/tsconfig": "workspace:*",
+ "@types/node": "22.10.2",
+ "bun-types": "1.3.1",
+ "typescript": "5.7.2"
+ }
+}
diff --git a/packages/notifications/telegram/src/index.test.ts b/packages/notifications/telegram/src/index.test.ts
new file mode 100644
index 000000000..c479e97c9
--- /dev/null
+++ b/packages/notifications/telegram/src/index.test.ts
@@ -0,0 +1,208 @@
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { selectNotificationSchema } from "@openstatus/db/src/schema";
+import { sendAlert, sendDegraded, sendRecovery, sendTest } from "./index";
+
+describe("Telegram Notifications", () => {
+ // biome-ignore lint/suspicious/noExplicitAny: <explanation>
+ let fetchMock: any = undefined;
+ const originalEnv = process.env.TELEGRAM_BOT_TOKEN;
+
+ beforeEach(() => {
+ process.env.TELEGRAM_BOT_TOKEN = "test-bot-token-123";
+ fetchMock = spyOn(global, "fetch").mockImplementation(() =>
+ Promise.resolve(new Response(null, { status: 200 })),
+ );
+ });
+
+ afterEach(() => {
+ if (fetchMock) {
+ fetchMock.mockRestore();
+ }
+ if (originalEnv) {
+ process.env.TELEGRAM_BOT_TOKEN = originalEnv;
+ } else {
+ process.env.TELEGRAM_BOT_TOKEN = undefined;
+ }
+ });
+
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "us-east-1",
+ });
+
+ const createMockNotification = () => ({
+ id: 1,
+ name: "Telegram Notification",
+ provider: "telegram",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: JSON.stringify({
+ telegram: {
+ chatId: "123456789",
+ },
+ }),
+ });
+
+ test("Send Alert", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Something went wrong",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toContain(
+ "https://api.telegram.org/bottest-bot-token-123/sendMessage",
+ );
+ expect(callArgs[0]).toContain("chat_id=123456789");
+ expect(callArgs[0]).toContain("API Health Check");
+ });
+
+ test("Send Alert without statusCode", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ message: "Connection timeout",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toContain("error: Connection timeout");
+ });
+
+ test("Send Recovery", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendRecovery({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 200,
+ message: "Service recovered",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toContain("is up again");
+ });
+
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ message: "Service degraded",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toContain("is degraded");
+ });
+
+ test("Send Test", async () => {
+ const result = await sendTest({
+ chatId: "123456789",
+ });
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toContain(
+ "https://api.telegram.org/bottest-bot-token-123/sendMessage",
+ );
+ expect(callArgs[0]).toContain("chat_id=123456789");
+ expect(callArgs[0]).toContain("This is a test message from OpenStatus");
+ });
+
+ test("Send Test returns false on error", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const result = await sendTest({
+ chatId: "123456789",
+ });
+
+ expect(result).toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ test("Handle fetch error gracefully", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ // Should not throw - function catches errors internally
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ test("sendMessage returns undefined when TELEGRAM_BOT_TOKEN is not set", async () => {
+ process.env.TELEGRAM_BOT_TOKEN = undefined;
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 500,
+ message: "Error",
+ cronTimestamp: Date.now(),
+ });
+
+ // Should not call fetch when token is missing
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/notifications/telegram/src/index.ts b/packages/notifications/telegram/src/index.ts
new file mode 100644
index 000000000..00bb3071e
--- /dev/null
+++ b/packages/notifications/telegram/src/index.ts
@@ -0,0 +1,132 @@
+import type { Monitor, Notification } from "@openstatus/db/src/schema";
+
+import type { Region } from "@openstatus/db/src/schema/constants";
+import { TelegramSchema } from "./schema";
+
+export const sendAlert = async ({
+ monitor,
+ notification,
+ statusCode,
+ message,
+ // biome-ignore lint/correctness/noUnusedVariables: <explanation>
+ incidentId,
+}: {
+ monitor: Monitor;
+ notification: Notification;
+ statusCode?: number;
+ message?: string;
+ incidentId?: string;
+ cronTimestamp: number;
+ latency?: number;
+ region?: Region;
+}) => {
+ const notificationData = TelegramSchema.parse(JSON.parse(notification.data));
+ const { name } = monitor;
+
+ const body = `Your monitor ${name} / ${monitor.url} is down with ${
+ statusCode ? `status code ${statusCode}` : `error: ${message}`
+ }`;
+
+ try {
+ await sendMessage({
+ chatId: notificationData.telegram.chatId,
+ message: body,
+ });
+ } catch (err) {
+ console.log(err);
+ // Do something
+ }
+};
+
+export const sendRecovery = async ({
+ monitor,
+ notification,
+ // biome-ignore lint/correctness/noUnusedVariables: <explanation>
+ statusCode,
+ // biome-ignore lint/correctness/noUnusedVariables: <explanation>
+ message,
+ // biome-ignore lint/correctness/noUnusedVariables: <explanation>
+ incidentId,
+}: {
+ monitor: Monitor;
+ notification: Notification;
+ statusCode?: number;
+ message?: string;
+ incidentId?: string;
+ cronTimestamp: number;
+ latency?: number;
+ region?: Region;
+}) => {
+ const notificationData = TelegramSchema.parse(JSON.parse(notification.data));
+ const { name } = monitor;
+
+ const body = `Your monitor ${name} / ${monitor.url} is up again`;
+ try {
+ await sendMessage({
+ chatId: notificationData.telegram.chatId,
+ message: body,
+ });
+ } catch (err) {
+ console.log(err);
+ // Do something
+ }
+};
+
+export const sendDegraded = async ({
+ monitor,
+ notification,
+ // biome-ignore lint/correctness/noUnusedVariables: <explanation>
+ statusCode,
+ // biome-ignore lint/correctness/noUnusedVariables: <explanation>
+ message,
+}: {
+ monitor: Monitor;
+ notification: Notification;
+ statusCode?: number;
+ message?: string;
+ incidentId?: string;
+ cronTimestamp: number;
+ latency?: number;
+ region?: Region;
+}) => {
+ const notificationData = TelegramSchema.parse(JSON.parse(notification.data));
+ const { name } = monitor;
+
+ const body = `Your monitor ${name} / ${monitor.url} is degraded `;
+
+ try {
+ await sendMessage({
+ chatId: notificationData.telegram.chatId,
+ message: body,
+ });
+ } catch (err) {
+ console.log(err);
+ // Do something
+ }
+};
+
+export const sendTest = async ({ chatId }: { chatId: string }) => {
+ try {
+ await sendMessage({
+ chatId,
+ message: "This is a test message from OpenStatus. You are good to go!",
+ });
+ } catch (err) {
+ console.log(err);
+ return false;
+ }
+ return true;
+};
+
+export async function sendMessage({
+ chatId,
+ message,
+}: {
+ chatId: string;
+ message: string;
+}) {
+ if (!process.env.TELEGRAM_BOT_TOKEN) return;
+ return fetch(
+ `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage?chat_id=${chatId}&text=${message}`,
+ );
+}
diff --git a/packages/notifications/telegram/src/schema.ts b/packages/notifications/telegram/src/schema.ts
new file mode 100644
index 000000000..dd4785b7c
--- /dev/null
+++ b/packages/notifications/telegram/src/schema.ts
@@ -0,0 +1,7 @@
+import { z } from "zod";
+
+export const TelegramSchema = z.object({
+ telegram: z.object({
+ chatId: z.string(),
+ }),
+});
diff --git a/packages/notifications/telegram/tsconfig.json b/packages/notifications/telegram/tsconfig.json
new file mode 100644
index 000000000..a8a8c9309
--- /dev/null
+++ b/packages/notifications/telegram/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@openstatus/tsconfig/nextjs.json",
+ "include": ["src", "*.ts"]
+}
diff --git a/packages/notifications/twillio-sms/src/index.test.ts b/packages/notifications/twillio-sms/src/index.test.ts
index f47d7b86f..74db91b51 100644
--- a/packages/notifications/twillio-sms/src/index.test.ts
+++ b/packages/notifications/twillio-sms/src/index.test.ts
@@ -1,132 +1,177 @@
-import {
- afterEach,
- beforeEach,
- describe,
- expect,
- jest,
- spyOn,
- test,
-} from "bun:test";
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { selectNotificationSchema } from "@openstatus/db/src/schema";
import { sendAlert, sendDegraded, sendRecovery } from "./index";
-describe("Slack Notifications", () => {
+describe("Twilio SMS Notifications", () => {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
let fetchMock: any = undefined;
+ const originalEnv = {
+ TWILLIO_ACCOUNT_ID: process.env.TWILLIO_ACCOUNT_ID,
+ TWILLIO_AUTH_TOKEN: process.env.TWILLIO_AUTH_TOKEN,
+ };
beforeEach(() => {
- // @ts-expect-error
+ process.env.TWILLIO_ACCOUNT_ID = "test-account-id";
+ process.env.TWILLIO_AUTH_TOKEN = "test-auth-token";
fetchMock = spyOn(global, "fetch").mockImplementation(() =>
Promise.resolve(new Response(null, { status: 200 })),
);
});
afterEach(() => {
- jest.resetAllMocks();
+ if (fetchMock) {
+ fetchMock.mockRestore();
+ }
+ if (originalEnv.TWILLIO_ACCOUNT_ID) {
+ process.env.TWILLIO_ACCOUNT_ID = originalEnv.TWILLIO_ACCOUNT_ID;
+ } else {
+ process.env.TWILLIO_ACCOUNT_ID = undefined;
+ }
+ if (originalEnv.TWILLIO_AUTH_TOKEN) {
+ process.env.TWILLIO_AUTH_TOKEN = originalEnv.TWILLIO_AUTH_TOKEN;
+ } else {
+ process.env.TWILLIO_AUTH_TOKEN = undefined;
+ }
});
- test("Send degraded", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
-
- const a = {
- id: 1,
- name: "slack Notification",
- provider: "slack",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"sms":"+33623456789"}',
- };
-
- const n = selectNotificationSchema.parse(a);
- await sendDegraded({
+ const createMockMonitor = () => ({
+ id: "monitor-1",
+ name: "API Health Check",
+ url: "https://api.example.com/health",
+ jobType: "http" as const,
+ periodicity: "5m" as const,
+ status: "active" as const,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ region: "us-east-1",
+ });
+
+ const createMockNotification = () => ({
+ id: 1,
+ name: "Twilio SMS Notification",
+ provider: "sms",
+ workspaceId: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ data: '{"sms":"+33623456789"}',
+ });
+
+ test("Send Alert", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
message: "Something went wrong",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ expect(callArgs[0]).toBe(
+ "https://api.twilio.com/2010-04-01/Accounts/test-account-id/Messages.json",
+ );
+ expect(callArgs[1].method).toBe("post");
+ expect(callArgs[1].headers.Authorization).toBe(
+ `Basic ${btoa("test-account-id:test-auth-token")}`,
+ );
+
+ const formData = callArgs[1].body as FormData;
+ expect(formData.get("To")).toBe("+33623456789");
+ expect(formData.get("From")).toBe("+14807252613");
+ expect(formData.get("Body")).toContain("API Health Check");
+ expect(formData.get("Body")).toContain("status code 500");
+ });
+
+ test("Send Alert without statusCode", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendAlert({
+ // @ts-expect-error
+ monitor,
+ notification,
+ message: "Connection timeout",
+ cronTimestamp: Date.now(),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const formData = callArgs[1].body as FormData;
+ expect(formData.get("Body")).toContain("error: Connection timeout");
});
- test("Send Recovered", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
-
- const a = {
- id: 1,
- name: "slack Notification",
- provider: "slack",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"sms":"+33623456789"}',
- };
-
- const n = selectNotificationSchema.parse(a);
+ test("Send Recovery", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
await sendRecovery({
// @ts-expect-error
monitor,
- notification: n,
- statusCode: 500,
- message: "Something went wrong",
+ notification,
+ statusCode: 200,
+ message: "Service recovered",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const formData = callArgs[1].body as FormData;
+ expect(formData.get("Body")).toContain("is up again");
+ expect(formData.get("Body")).toContain("API Health Check");
});
- test("Send Alert", async () => {
- const monitor = {
- id: "monitor-1",
- name: "API Health Check",
- url: "https://api.example.com/health",
- jobType: "http" as const,
- periodicity: "5m" as const,
- status: "active" as const, // or "down", "degraded"
- createdAt: new Date(),
- updatedAt: new Date(),
- region: "us-east-1",
- };
- const a = {
- id: 1,
- name: "slack Notification",
- provider: "slack",
- workspaceId: 1,
- createdAt: new Date(),
- updatedAt: new Date(),
- data: '{"sms":"+33623456789"}',
- };
-
- const n = selectNotificationSchema.parse(a);
+ test("Send Degraded", async () => {
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ await sendDegraded({
+ // @ts-expect-error
+ monitor,
+ notification,
+ statusCode: 503,
+ message: "Service degraded",
+ cronTimestamp: Date.now(),
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const callArgs = fetchMock.mock.calls[0];
+ const formData = callArgs[1].body as FormData;
+ expect(formData.get("Body")).toContain("is degraded");
+ expect(formData.get("Body")).toContain("API Health Check");
+ });
+
+ test("Handle fetch error gracefully", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.reject(new Error("Network error")),
+ );
+
+ const monitor = createMockMonitor();
+ const notification = selectNotificationSchema.parse(
+ createMockNotification(),
+ );
+
+ // Should not throw - function catches errors internally
await sendAlert({
// @ts-expect-error
monitor,
- notification: n,
+ notification,
statusCode: 500,
- message: "Something went wrong",
+ message: "Error",
cronTimestamp: Date.now(),
});
- expect(fetchMock).toHaveBeenCalled();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c8a62ba8c..6a0271dcd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -107,6 +107,9 @@ importers:
'@openstatus/notification-slack':
specifier: workspace:*
version: link:../../packages/notifications/slack
+ '@openstatus/notification-telegram':
+ specifier: workspace:*
+ version: link:../../packages/notifications/telegram
'@openstatus/notification-webhook':
specifier: workspace:*
version: link:../../packages/notifications/webhook
@@ -1082,6 +1085,9 @@ importers:
'@openstatus/notification-slack':
specifier: workspace:*
version: link:../../packages/notifications/slack
+ '@openstatus/notification-telegram':
+ specifier: workspace:*
+ version: link:../../packages/notifications/telegram
'@openstatus/notification-twillio-sms':
specifier: workspace:*
version: link:../../packages/notifications/twillio-sms
@@ -1165,6 +1171,9 @@ importers:
'@openstatus/error':
specifier: workspace:*
version: link:../error
+ '@openstatus/notification-telegram':
+ specifier: workspace:*
+ version: link:../notifications/telegram
'@openstatus/regions':
specifier: workspace:*
version: link:../regions
@@ -1403,6 +1412,9 @@ importers:
'@types/node':
specifier: 22.10.2
version: 22.10.2
+ bun-types:
+ specifier: 1.3.1
+ version: 1.3.1(@types/[email protected])
typescript:
specifier: 5.7.2
version: 5.7.2
@@ -1474,6 +1486,9 @@ importers:
'@types/node':
specifier: 22.10.2
version: 22.10.2
+ bun-types:
+ specifier: 1.3.1
+ version: 1.3.1(@types/[email protected])
typescript:
specifier: 5.7.2
version: 5.7.2
@@ -1508,6 +1523,9 @@ importers:
'@types/react-dom':
specifier: 19.2.2
version: 19.2.2(@types/[email protected])
+ bun-types:
+ specifier: 1.3.1
+ version: 1.3.1(@types/[email protected])
typescript:
specifier: 5.7.2
version: 5.7.2
@@ -1571,6 +1589,28 @@ importers:
specifier: 5.7.2
version: 5.7.2
+ packages/notifications/telegram:
+ dependencies:
+ '@openstatus/db':
+ specifier: workspace:*
+ version: link:../../db
+ zod:
+ specifier: 3.25.76
+ version: 3.25.76
+ devDependencies:
+ '@openstatus/tsconfig':
+ specifier: workspace:*
+ version: link:../../tsconfig
+ '@types/node':
+ specifier: 22.10.2
+ version: 22.10.2
+ bun-types:
+ specifier: 1.3.1
+ version: 1.3.1(@types/[email protected])
+ typescript:
+ specifier: 5.7.2
+ version: 5.7.2
+
packages/notifications/twillio-sms:
dependencies:
'@openstatus/db':
@@ -14505,9 +14545,9 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
react: 19.0.0
react-dom: 19.0.0([email protected])
optionalDependencies:
@@ -14596,14 +14636,14 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
'@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
react: 19.0.0
@@ -14640,11 +14680,11 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -14824,11 +14864,11 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-use-escape-keydown': 1.1.1(@types/[email protected])([email protected])
react: 19.0.0
@@ -14865,14 +14905,14 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -14924,10 +14964,10 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -15056,22 +15096,22 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])
'@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
'@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
aria-hidden: 1.2.6
@@ -15153,19 +15193,19 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])
'@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
aria-hidden: 1.2.6
@@ -15235,13 +15275,13 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@floating-ui/react-dom': 2.1.6([email protected]([email protected]))([email protected])
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-use-rect': 1.1.1(@types/[email protected])([email protected])
@@ -15263,9 +15303,9 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
'@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -15323,7 +15363,7 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
@@ -15342,7 +15382,7 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
'@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
react: 19.0.0
@@ -15477,15 +15517,15 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
react: 19.0.0
@@ -15682,15 +15722,15 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -15714,14 +15754,14 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -15740,10 +15780,10 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
@@ -15791,20 +15831,20 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/[email protected])
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
'@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
react: 19.0.0
react-dom: 19.0.0([email protected])
optionalDependencies:
@@ -15975,9 +16015,9 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.1.9(@types/[email protected])
dependencies:
react: 19.0.0
react-dom: 19.0.0([email protected])
optionalDependencies:
@@ -16118,13 +16158,13 @@ snapshots:
'@babel/traverse': 7.27.0
'@lottiefiles/dotlottie-react': 0.13.3([email protected])
'@radix-ui/colors': 3.0.0
- '@radix-ui/react-collapsible': 1.1.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
- '@radix-ui/react-dropdown-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-collapsible': 1.1.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-dropdown-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
- '@radix-ui/react-toggle-group': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-toggle-group': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
'@types/node': 22.14.1
'@types/normalize-path': 3.0.2
'@types/react': 19.0.10