Skip to content

Open-source status page, incident response and uptime monitoring

feat: notifications (#418)

Maximilian Kaske96ba552c0dde
diff --git a/apps/server/package.json b/apps/server/package.json
index 0ec2b6e1e..e6c82ee37 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -13,7 +13,9 @@
"@hono/sentry": "^1.0.0",
"@hono/zod-openapi": "0.7.1",
"@openstatus/db": "workspace:*",
+ "@openstatus/notification-discord": "workspace:*",
"@openstatus/notification-emails": "workspace:*",
+ "@openstatus/notification-slack": "workspace:*",
"@openstatus/plans": "workspace:*",
"@openstatus/tinybird": "workspace:*",
"@openstatus/upstash": "workspace:*",
diff --git a/apps/server/src/checker/alerting.ts b/apps/server/src/checker/alerting.ts
index 4238b828d..14a9a8889 100644
--- a/apps/server/src/checker/alerting.ts
+++ b/apps/server/src/checker/alerting.ts
@@ -1,7 +1,9 @@
-import type { z } from "zod";
-
import { db, eq, schema } from "@openstatus/db";
-import { selectNotificationSchema } from "@openstatus/db/src/schema";
+import type { MonitorStatus } from "@openstatus/db/src/schema";
+import {
+ selectMonitorSchema,
+ selectNotificationSchema,
+} from "@openstatus/db/src/schema";
import { publishPingRetryPolicy } from "./checker";
import type { Payload } from "./schema";
@@ -34,8 +36,9 @@ export const triggerAlerting = async ({ monitorId }: { monitorId: string }) => {
.where(eq(schema.monitor.id, Number(monitorId)))
.all();
for (const notif of notifications) {
+ const monitor = selectMonitorSchema.parse(notif.monitor);
await providerToFunction[notif.notification.provider]({
- monitor: notif.monitor,
+ monitor,
notification: selectNotificationSchema.parse(notif.notification),
});
}
@@ -46,7 +49,7 @@ export const updateMonitorStatus = async ({
status,
}: {
monitorId: string;
- status: z.infer<typeof schema.statusSchema>;
+ status: MonitorStatus;
}) => {
await db
.update(schema.monitor)
diff --git a/apps/server/src/checker/schema.ts b/apps/server/src/checker/schema.ts
index 9b85dedde..90009a375 100644
--- a/apps/server/src/checker/schema.ts
+++ b/apps/server/src/checker/schema.ts
@@ -1,17 +1,17 @@
import { z } from "zod";
-import { methods, status } from "@openstatus/db/src/schema";
+import { monitorMethods, monitorStatus } from "@openstatus/db/src/schema";
export const payloadSchema = z.object({
workspaceId: z.string(),
monitorId: z.string(),
- method: z.enum(methods),
+ method: z.enum(monitorMethods),
body: z.string().optional(),
headers: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
url: z.string(),
cronTimestamp: z.number(),
pageIds: z.array(z.string()),
- status: z.enum(status),
+ status: z.enum(monitorStatus),
});
export type Payload = z.infer<typeof payloadSchema>;
diff --git a/apps/server/src/checker/utils.ts b/apps/server/src/checker/utils.ts
index 4b073c146..86b245763 100644
--- a/apps/server/src/checker/utils.ts
+++ b/apps/server/src/checker/utils.ts
@@ -1,40 +1,22 @@
-import type { z } from "zod";
-
import type {
- basicMonitorSchema,
- providerName,
- selectNotificationSchema,
+ Monitor,
+ Notification,
+ NotificationProvider,
} from "@openstatus/db/src/schema";
+import { sendDiscordMessage } from "@openstatus/notification-discord";
import { send as sendEmail } from "@openstatus/notification-emails";
+import { sendSlackMessage } from "@openstatus/notification-slack";
-type ProviderName = (typeof providerName)[number];
-
-type sendNotificationType = ({
+type SendNotification = ({
monitor,
notification,
}: {
- monitor: z.infer<typeof basicMonitorSchema>;
- notification: z.infer<typeof selectNotificationSchema>;
+ monitor: Monitor;
+ notification: Notification;
}) => Promise<void>;
export const providerToFunction = {
email: sendEmail,
- slack: async ({
- monitor,
- notification,
- }: {
- monitor: any;
- notification: any;
- }) => {
- /* TODO: implement */
- },
- discord: async ({
- monitor,
- notification,
- }: {
- monitor: any;
- notification: any;
- }) => {
- /* TODO: implement */
- },
-} satisfies Record<ProviderName, sendNotificationType>;
+ slack: sendSlackMessage,
+ discord: sendDiscordMessage,
+} satisfies Record<NotificationProvider, SendNotification>;
diff --git a/apps/server/src/v1/incident.ts b/apps/server/src/v1/incident.ts
index ac1dfc607..1f410b110 100644
--- a/apps/server/src/v1/incident.ts
+++ b/apps/server/src/v1/incident.ts
@@ -2,8 +2,8 @@ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { and, db, eq } from "@openstatus/db";
import {
- availableStatus,
incident,
+ incidentStatus,
incidentUpdate,
} from "@openstatus/db/src/schema";
@@ -27,7 +27,7 @@ const ParamsSchema = z.object({
});
const incidentUpdateSchema = z.object({
- status: z.enum(availableStatus).openapi({
+ status: z.enum(incidentStatus).openapi({
description: "The status of the update",
}),
date: z.string().openapi({
@@ -43,7 +43,7 @@ const incidentSchema = z.object({
example: "Documenso",
description: "The title of the incident",
}),
- status: z.enum(availableStatus).openapi({
+ status: z.enum(incidentStatus).openapi({
description: "The current status of the incident",
}),
});
diff --git a/apps/server/src/v1/monitor.ts b/apps/server/src/v1/monitor.ts
index d6cad8546..98b6cc54c 100644
--- a/apps/server/src/v1/monitor.ts
+++ b/apps/server/src/v1/monitor.ts
@@ -3,10 +3,10 @@ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { db, eq, sql } from "@openstatus/db";
import {
flyRegions,
- methods,
monitor,
- periodicity,
-} from "@openstatus/db/src/schema/monitor";
+ monitorMethods,
+ monitorPeriodicity,
+} from "@openstatus/db/src/schema";
import type { Variables } from "./index";
import { ErrorSchema } from "./shared";
@@ -25,7 +25,7 @@ const ParamsSchema = z.object({
}),
});
-export const periodicityEnum = z.enum(periodicity);
+export const periodicityEnum = z.enum(monitorPeriodicity);
export const regionEnum = z
.enum(flyRegions)
.or(z.literal(""))
@@ -63,7 +63,7 @@ const MonitorSchema = z
description: "The description of your monitor",
})
.nullable(),
- method: z.enum(methods).default("GET").openapi({ example: "GET" }),
+ method: z.enum(monitorMethods).default("GET").openapi({ example: "GET" }),
body: z
.preprocess((val) => {
return String(val);
@@ -120,7 +120,7 @@ const monitorInput = z
example: "Documenso website",
description: "The description of your monitor",
}),
- method: z.enum(methods).default("GET").openapi({ example: "GET" }),
+ method: z.enum(monitorMethods).default("GET").openapi({ example: "GET" }),
body: z.string().openapi({
example: "Hello World",
description: "The body",
diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts
index 4f11a03dc..fd36f9494 100644
--- a/apps/web/next-env.d.ts
+++ b/apps/web/next-env.d.ts
@@ -1,5 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
+/// <reference types="next/navigation-types/compat/navigation" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
diff --git a/apps/web/package.json b/apps/web/package.json
index f9622c688..ce5b5e44e 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -19,6 +19,8 @@
"@openstatus/db": "workspace:*",
"@openstatus/emails": "workspace:*",
"@openstatus/notification-emails": "workspace:*",
+ "@openstatus/notification-discord": "workspace:*",
+ "@openstatus/notification-slack": "workspace:*",
"@openstatus/plans": "workspace:*",
"@openstatus/react": "workspace:*",
"@openstatus/tinybird": "workspace:*",
diff --git a/apps/web/src/app/api/checker/utils.ts b/apps/web/src/app/api/checker/utils.ts
index 2d8f611ab..4df098430 100644
--- a/apps/web/src/app/api/checker/utils.ts
+++ b/apps/web/src/app/api/checker/utils.ts
@@ -3,7 +3,9 @@ import type {
Notification,
NotificationProvider,
} from "@openstatus/db/src/schema";
+import { sendDiscordMessage } from "@openstatus/notification-discord";
import { send as sendEmail } from "@openstatus/notification-emails";
+import { sendSlackMessage } from "@openstatus/notification-slack";
type sendNotificationType = ({
monitor,
@@ -15,22 +17,6 @@ type sendNotificationType = ({
export const providerToFunction = {
email: sendEmail,
- slack: async ({
- monitor,
- notification,
- }: {
- monitor: any;
- notification: any;
- }) => {
- /* TODO: implement */
- },
- discord: async ({
- monitor,
- notification,
- }: {
- monitor: any;
- notification: any;
- }) => {
- /* TODO: implement */
- },
+ slack: sendSlackMessage,
+ discord: sendDiscordMessage,
} satisfies Record<NotificationProvider, sendNotificationType>;
diff --git a/apps/web/src/components/data-table/notification/columns.tsx b/apps/web/src/components/data-table/notification/columns.tsx
index 05a5f87bd..02edd649d 100644
--- a/apps/web/src/components/data-table/notification/columns.tsx
+++ b/apps/web/src/components/data-table/notification/columns.tsx
@@ -7,6 +7,8 @@ import { Badge } from "@openstatus/ui";
import { DataTableRowActions } from "./data-table-row-actions";
+// TODO: use the getProviderMetaData function from the notification form to access the data
+
export const columns: ColumnDef<Notification>[] = [
{
accessorKey: "name",
diff --git a/apps/web/src/components/forms/notification-form.tsx b/apps/web/src/components/forms/notification-form.tsx
index 34c5ef4b6..75fe1fd6a 100644
--- a/apps/web/src/components/forms/notification-form.tsx
+++ b/apps/web/src/components/forms/notification-form.tsx
@@ -1,16 +1,21 @@
"use client";
-import { useTransition } from "react";
+import { useMemo, useTransition } from "react";
import { useRouter } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
-import type { InsertNotification } from "@openstatus/db/src/schema";
+import type {
+ InsertNotification,
+ NotificationProvider,
+} from "@openstatus/db/src/schema";
import {
insertNotificationSchema,
notificationProvider,
notificationProviderSchema,
} from "@openstatus/db/src/schema";
+import { sendTestDiscordMessage } from "@openstatus/notification-discord";
+import { sendTestSlackMessage } from "@openstatus/notification-slack";
import {
Button,
Form,
@@ -30,15 +35,55 @@ import {
import { LoadingAnimation } from "@/components/loading-animation";
import { useToastAction } from "@/hooks/use-toast-action";
+import { toCapitalize } from "@/lib/utils";
import { api } from "@/trpc/client";
-/**
- * TODO: based on the providers `data` structure, create dynamic form inputs
- * e.g. Provider: Email will need an `email` input field and
- * we store it like `data: { email: "" }`
- * But Provider: Slack will maybe require `webhook` and `channel` and
- * we store it like `data: { webhook: "", channel: "" }`
- */
+function getDefaultProviderData(defaultValues?: InsertNotification) {
+ if (!defaultValues?.provider) return ""; // FIXME: input can empty - needs to be undefined
+ return JSON.parse(defaultValues?.data || "{}")[defaultValues?.provider];
+}
+
+function setProviderData(provider: NotificationProvider, data: string) {
+ return { [provider]: data };
+}
+
+function getProviderMetaData(provider: NotificationProvider) {
+ switch (provider) {
+ case "email":
+ return {
+ dataType: "email",
+ placeholder: "[email protected]",
+ setupDocLink: null,
+ sendTest: null,
+ };
+
+ case "slack":
+ return {
+ dataType: "url",
+ placeholder: "https://hooks.slack.com/services/xxx...",
+ setupDocLink:
+ "https://api.slack.com/messaging/webhooks#getting_started",
+ sendTest: sendTestSlackMessage,
+ };
+
+ case "discord":
+ return {
+ dataType: "url",
+ placeholder: "https://hooks.slack.com/services/xxx...", // FIXME:
+ setupDocLink:
+ "https://api.slack.com/messaging/webhooks#getting_started", // FIXME:
+ sendTest: sendTestDiscordMessage,
+ };
+
+ default:
+ return {
+ dataType: "url",
+ placeholder: "xxxx",
+ setupDocLink: `https://docs.openstatus.dev/integrations/${provider}`,
+ send: null,
+ };
+ }
+}
interface Props {
defaultValues?: InsertNotification;
@@ -52,6 +97,7 @@ export function NotificationForm({
onSubmit: onExternalSubmit,
}: Props) {
const [isPending, startTransition] = useTransition();
+ const [isTestPending, startTestTransition] = useTransition();
const { toast } = useToastAction();
const router = useRouter();
const form = useForm<InsertNotification>({
@@ -59,27 +105,30 @@ export function NotificationForm({
defaultValues: {
...defaultValues,
name: defaultValues?.name || "",
- data:
- defaultValues?.provider === "email"
- ? JSON.parse(defaultValues?.data).email
- : "",
+ data: getDefaultProviderData(defaultValues),
},
});
+ const watchProvider = form.watch("provider");
+ const watchWebhookUrl = form.watch("data");
+ const providerMetaData = useMemo(
+ () => getProviderMetaData(watchProvider),
+ [watchProvider],
+ );
async function onSubmit({ provider, data, ...rest }: InsertNotification) {
startTransition(async () => {
try {
if (defaultValues) {
await api.notification.updateNotification.mutate({
- provider: "email",
- data: JSON.stringify({ email: data }),
+ provider,
+ data: JSON.stringify(setProviderData(provider, data)),
...rest,
});
} else {
await api.notification.createNotification.mutate({
workspaceSlug,
- provider: "email",
- data: JSON.stringify({ email: data }),
+ provider,
+ data: JSON.stringify(setProviderData(provider, data)),
...rest,
});
}
@@ -93,6 +142,19 @@ export function NotificationForm({
});
}
+ async function sendTestWebhookPing() {
+ const webhookUrl = form.getValues("data");
+ if (!webhookUrl) return;
+ startTestTransition(async () => {
+ const isSuccessfull = await providerMetaData.sendTest?.(webhookUrl);
+ if (isSuccessfull) {
+ toast("test-success");
+ } else {
+ toast("test-error");
+ }
+ });
+ }
+
return (
<Form {...form}>
<form
@@ -129,7 +191,6 @@ export function NotificationForm({
<SelectItem
key={provider}
value={provider}
- disabled={provider !== "email"} // only allow email for now
className="capitalize"
>
{provider}
@@ -160,28 +221,60 @@ export function NotificationForm({
</FormItem>
)}
/>
- <FormField
- control={form.control}
- name="data"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Email</FormLabel>
- <FormControl>
- <Input
- type="email"
- required
- placeholder="[email protected]"
- {...field}
- />
- </FormControl>
- <FormDescription>The data required.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
+ {watchProvider && (
+ <FormField
+ control={form.control}
+ name="data"
+ render={({ field }) => (
+ <FormItem className="sm:col-span-full">
+ {/* make the first letter capital */}
+ <div className="flex items-center justify-between">
+ <FormLabel>{toCapitalize(watchProvider)}</FormLabel>
+ </div>
+ <FormControl>
+ <Input
+ type={providerMetaData.dataType}
+ placeholder={providerMetaData.placeholder}
+ {...field}
+ />
+ </FormControl>
+ <FormDescription className="flex items-center justify-between">
+ The data required.
+ {providerMetaData.setupDocLink && (
+ <a
+ href={providerMetaData.setupDocLink}
+ target="_blank"
+ className="underline hover:no-underline"
+ >
+ How to setup your {toCapitalize(watchProvider)}{" "}
+ webhook
+ </a>
+ )}
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
</div>
</div>
- <div className="flex sm:justify-end">
+ <div className="flex gap-4 sm:justify-end">
+ {providerMetaData.sendTest && (
+ <Button
+ type="button"
+ variant="secondary"
+ className="w-full sm:w-auto"
+ size="lg"
+ disabled={!watchWebhookUrl || isTestPending}
+ onClick={sendTestWebhookPing}
+ >
+ {!isTestPending ? (
+ "Test Webhook"
+ ) : (
+ <LoadingAnimation variant="inverse" />
+ )}
+ </Button>
+ )}
<Button className="w-full sm:w-auto" size="lg" disabled={isPending}>
{!isPending ? "Confirm" : <LoadingAnimation />}
</Button>
diff --git a/apps/web/src/components/layout/breadcrumbs.tsx b/apps/web/src/components/layout/breadcrumbs.tsx
new file mode 100644
index 000000000..bb64497f9
--- /dev/null
+++ b/apps/web/src/components/layout/breadcrumbs.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { Fragment } from "react";
+import { usePathname } from "next/navigation";
+import { ChevronRight } from "lucide-react";
+
+// TODO: create place to put into layout.tsx
+
+export function Breadcrumbs() {
+ const pathname = usePathname();
+ const result = pathname.split("/").slice(3);
+
+ return (
+ <ul className="flex items-center">
+ {result.map((path, i) => {
+ return (
+ <Fragment key={i}>
+ <li>{path}</li>
+ {i !== result.length - 1 ? (
+ <ChevronRight className="text-muted-foreground mx-2 h-3 w-3" />
+ ) : null}
+ </Fragment>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts
index 7444624bc..98f82a904 100644
--- a/apps/web/src/lib/utils.ts
+++ b/apps/web/src/lib/utils.ts
@@ -59,3 +59,12 @@ export function manipulateDate(
toDate: isToDateMidnight ? addOneDayToDate : date?.to?.getTime() || null,
};
}
+
+export function toCapitalize(inputString: string) {
+ const words = inputString.split(/[\s_]+/); // Split the input string by spaces or underscores
+
+ // Capitalize the first letter of each word
+ return words
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
+ .join("");
+}
diff --git a/packages/notifications/discord/.gitignore b/packages/notifications/discord/.gitignore
new file mode 100644
index 000000000..f81d56eaa
--- /dev/null
+++ b/packages/notifications/discord/.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/discord/README.md b/packages/notifications/discord/README.md
new file mode 100644
index 000000000..2df8a1d56
--- /dev/null
+++ b/packages/notifications/discord/README.md
@@ -0,0 +1,16 @@
+# @openstatus/notifications-discord
+
+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.
diff --git a/packages/notifications/discord/package.json b/packages/notifications/discord/package.json
new file mode 100644
index 000000000..430436b6c
--- /dev/null
+++ b/packages/notifications/discord/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "@openstatus/notification-discord",
+ "version": "1.0.0",
+ "main": "src/index.ts",
+ "dependencies": {
+ "@openstatus/db": "workspace:*"
+ },
+ "devDependencies": {
+ "@openstatus/tsconfig": "workspace:*",
+ "@types/node": "20.8.0",
+ "@types/react": "18.2.24",
+ "@types/react-dom": "18.2.8",
+ "next": "13.5.3",
+ "typescript": "5.2.2"
+ }
+}
\ No newline at end of file
diff --git a/packages/notifications/discord/src/index.ts b/packages/notifications/discord/src/index.ts
new file mode 100644
index 000000000..299220d1a
--- /dev/null
+++ b/packages/notifications/discord/src/index.ts
@@ -0,0 +1,54 @@
+import type { Monitor, Notification } from "@openstatus/db/src/schema";
+
+const postToWebhook = async (content: string, webhookUrl: string) => {
+ await fetch(webhookUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ content,
+ avatar_url:
+ "https://img.stackshare.io/service/104872/default_dc6948366d9bae553adbb8f51252eafbc5d2043a.jpg",
+ username: "OpenStatus Notifications",
+ }),
+ });
+};
+
+export const sendDiscordMessage = async ({
+ monitor,
+ notification,
+}: {
+ monitor: Monitor;
+ notification: Notification;
+}) => {
+ const notificationData = JSON.parse(notification.data);
+ const { discord: webhookUrl } = notificationData; // webhook url
+ const { name } = monitor;
+
+ try {
+ await postToWebhook(
+ `Your monitor ${name} is down 🚨
+
+ Your monitor with url ${monitor.url} is down.`,
+ webhookUrl,
+ );
+ } catch (err) {
+ // Do something
+ }
+};
+
+export const sendTestDiscordMessage = async (webhookUrl: string) => {
+ if (!webhookUrl) {
+ return false;
+ }
+ try {
+ await postToWebhook(
+ "This is a test notification from OpenStatus. \nIf you see this, it means that your webhook is working! 🎉",
+ webhookUrl,
+ );
+ return true;
+ } catch (err) {
+ return false;
+ }
+};
diff --git a/packages/notifications/discord/tsconfig.json b/packages/notifications/discord/tsconfig.json
new file mode 100644
index 000000000..a8a8c9309
--- /dev/null
+++ b/packages/notifications/discord/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@openstatus/tsconfig/nextjs.json",
+ "include": ["src", "*.ts"]
+}
diff --git a/packages/notifications/slack/package.json b/packages/notifications/slack/package.json
new file mode 100644
index 000000000..5bfbd8fb7
--- /dev/null
+++ b/packages/notifications/slack/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "@openstatus/notification-slack",
+ "version": "0.0.0",
+ "main": "src/index.ts",
+ "dependencies": {
+ "@openstatus/db": "workspace:*"
+ },
+ "devDependencies": {
+ "@openstatus/tsconfig": "workspace:*",
+ "@types/node": "20.8.0",
+ "@types/react": "18.2.24",
+ "@types/react-dom": "18.2.8",
+ "next": "13.5.3",
+ "typescript": "5.2.2"
+ }
+}
\ No newline at end of file
diff --git a/packages/notifications/slack/src/index.ts b/packages/notifications/slack/src/index.ts
new file mode 100644
index 000000000..400f1d233
--- /dev/null
+++ b/packages/notifications/slack/src/index.ts
@@ -0,0 +1,77 @@
+import type { Monitor, Notification } from "@openstatus/db/src/schema";
+
+const postToWebhook = async (body: any, webhookUrl: string) => {
+ try {
+ await fetch(webhookUrl, {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ } catch (e) {
+ console.log(e);
+ throw e;
+ }
+};
+
+export const sendSlackMessage = async ({
+ monitor,
+ notification,
+}: {
+ monitor: Monitor;
+ notification: Notification;
+}) => {
+ const notificationData = JSON.parse(notification.data);
+ const { slack: webhookUrl } = notificationData; // webhook url
+ const { name } = monitor;
+
+ try {
+ await postToWebhook(
+ {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `Your monitor <${monitor.url}/|${name}> is down 🚨 \n\n Powered by <https://www.openstatus.dev/|OpenStatus>.`,
+ },
+ accessory: {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "Open Monitor",
+ emoji: true,
+ },
+ value: `monitor_url_${monitor.url}`,
+ url: monitor.url,
+ },
+ },
+ ],
+ },
+ webhookUrl,
+ );
+ } catch (err) {
+ console.log(err);
+ // Do something
+ }
+};
+
+export const sendTestSlackMessage = async (webhookUrl: string) => {
+ try {
+ await postToWebhook(
+ {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "This is a test notification from <https://www.openstatus.dev/|OpenStatus>.\n If you can read this, your Slack webhook is functioning correctly!",
+ },
+ },
+ ],
+ },
+ webhookUrl,
+ );
+ return true;
+ } catch (err) {
+ return false;
+ }
+};
diff --git a/packages/notifications/slack/tsconfig.json b/packages/notifications/slack/tsconfig.json
new file mode 100644
index 000000000..a8a8c9309
--- /dev/null
+++ b/packages/notifications/slack/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@openstatus/tsconfig/nextjs.json",
+ "include": ["src", "*.ts"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5743abace..d6f097b2d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -87,9 +87,15 @@ importers:
'@openstatus/db':
specifier: workspace:*
version: link:../../packages/db
+ '@openstatus/notification-discord':
+ specifier: workspace:*
+ version: link:../../packages/notifications/discord
'@openstatus/notification-emails':
specifier: workspace:*
version: link:../../packages/notifications/email
+ '@openstatus/notification-slack':
+ specifier: workspace:*
+ version: link:../../packages/notifications/slack
'@openstatus/plans':
specifier: workspace:*
version: link:../../packages/plans
@@ -151,9 +157,15 @@ importers:
'@openstatus/emails':
specifier: workspace:*
version: link:../../packages/emails
+ '@openstatus/notification-discord':
+ specifier: workspace:*
+ version: link:../../packages/notifications/discord
'@openstatus/notification-emails':
specifier: workspace:*
version: link:../../packages/notifications/email
+ '@openstatus/notification-slack':
+ specifier: workspace:*
+ version: link:../../packages/notifications/slack
'@openstatus/plans':
specifier: workspace:*
version: link:../../packages/plans
@@ -585,6 +597,31 @@ importers:
specifier: 5.2.2
version: 5.2.2
+ packages/notifications/discord:
+ dependencies:
+ '@openstatus/db':
+ specifier: workspace:*
+ version: link:../../db
+ devDependencies:
+ '@openstatus/tsconfig':
+ specifier: workspace:*
+ version: link:../../tsconfig
+ '@types/node':
+ specifier: 20.8.0
+ version: 20.8.0
+ '@types/react':
+ specifier: 18.2.24
+ version: 18.2.24
+ '@types/react-dom':
+ specifier: 18.2.8
+ version: 18.2.8
+ next:
+ specifier: 13.5.3
+ typescript:
+ specifier: 5.2.2
+ version: 5.2.2
+
packages/notifications/email:
dependencies:
'@openstatus/db':
@@ -631,6 +668,31 @@ importers:
specifier: 5.2.2
version: 5.2.2
+ packages/notifications/slack:
+ dependencies:
+ '@openstatus/db':
+ specifier: workspace:*
+ version: link:../../db
+ devDependencies:
+ '@openstatus/tsconfig':
+ specifier: workspace:*
+ version: link:../../tsconfig
+ '@types/node':
+ specifier: 20.8.0
+ version: 20.8.0
+ '@types/react':
+ specifier: 18.2.24
+ version: 18.2.24
+ '@types/react-dom':
+ specifier: 18.2.8
+ version: 18.2.8
+ next:
+ specifier: 13.5.3
+ typescript:
+ specifier: 5.2.2
+ version: 5.2.2
+
packages/plans:
dependencies:
'@openstatus/db':
@@ -4923,6 +4985,7 @@ packages:
/@swagger-api/[email protected]:
resolution: {integrity: sha512-19NR9lTHMOQTIEV4tJq+FlHQAYnjyH+DgI4mmRu6UMFSZjRjutYF7B8lCGogSus9Uwy8YpUk00prLFTld00wgA==}
+ requiresBuild: true
dependencies:
'@babel/runtime-corejs3': 7.23.2
'@swagger-api/apidom-ast': 0.78.0