Telegram alerts for new comments

Official(made by Sanity team)

By Simeon Griggs

Get instant Telegram notifications when new comments are posted, with direct links to your Sanity Studio.

schemaTypes/comment.ts

import {defineType} from 'sanity'

export const comment = defineType({
  name: 'comment',
  title: 'Comment',
  type: 'document',
  fields: [
    {
      name: 'comment',
      title: 'Comment',
      type: 'text', // or 'string'
      validation: (rule) => rule.required(),
    },
    // Add other fields as needed
  ],
})

functions/telegram-notify/index.ts

import {env} from 'node:process'

import {documentEventHandler} from '@sanity/functions'

const {TELEGRAM_BOT_TOKEN = '', TELEGRAM_CHAT_ID = '', STUDIO_URL = 'http://localhost:3333'} = env

export const handler = documentEventHandler(async ({event}) => {
  const {_id, comment} = event.data

  if (!comment) {
    console.log('No comment in event data')
    return
  } else if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
    console.log('Environment variables not set')
    return
  }

  try {
    const message = `New comment received: ${comment}`
    const studioUrl = `${STUDIO_URL}/structure/comment;${_id}`

    const response = await fetch(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        chat_id: TELEGRAM_CHAT_ID,
        text: message,
        reply_markup: {
          inline_keyboard: [[{text: '📝 Open in Sanity Studio', url: studioUrl}]],
        },
      }),
    })

    if (!response.ok) {
      throw new Error(`Telegram API error: ${response.status} ${response.statusText}`)
    }

    const result = await response.json()
    console.log('Message sent successfully:', result)
  } catch (error) {
    console.error('Failed to send Telegram notification:', error)
    throw error
  }
})

sanity.blueprint.ts

import {defineBlueprint, defineDocumentFunction} from '@sanity/blueprints'
import process from 'node:process'

const {TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID} = process.env
if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
  throw new Error('TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID must be set')
}

export default defineBlueprint({
  // ...all other settings
  resources: [
    //...all other functions
    defineDocumentFunction({
      name: 'comment-telegram',
      event: {
        on: ['create'],
        filter: '_type == "comment" && defined(comment)',
        projection: '{_id, comment}',
      },
      env: {TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID},
    }),
  ],
})

The Problem

Content authors need to respond quickly to comments on their content, but checking the Studio regularly for new comments creates workflow interruptions and delays response times.

The Solution

This Sanity Function sends a Telegram notification when a comment is posted, with a helpful link to open the comment in your Sanity Studio.

Quick Start

View the complete example and source code.

Initialize blueprints if you haven't already: npx sanity blueprints init

Then: npx sanity blueprints add function --example telegram-notify

Then deploy: npx sanity blueprints deploy

Telegram Setup More detailed instructions available in the GitHub README

  1. Create Bot: Message /newbot to @BotFather on Telegram → Give it a name → Copy the bot token
  2. Get Chat ID: Send a message to your bot → Visit https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates → Copy your chat ID from the JSON response
  3. Set Environment Variables: Add TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, and STUDIO_URL to your .env file
  4. Configure Function: Add the telegram-notify function to your blueprint with the required environment variables

Visit https://core.telegram.org/bots for more information.

How It Works When a content editor publishes a new comment, the function automatically:

  1. Triggers on the publish event for comment documents with content
  2. Extracts the comment text and document ID
  3. Formats a notification message with a direct link to the Studio and sends the message to your designated Telegram chat

Key Benefits

  • Instant notifications ensure comments are never missed
  • Direct Studio links enable immediate response from any device
  • Simplifies content operations by eliminating manual Studio checking
  • Improves content velocity through faster comment response times

Perfect For

  • Editorial teams or individuals managing active comment sections
  • Content workflows requiring rapid community engagement
  • Authors needing mobile-first notification systems
  • Teams preferring Telegram over email or Slack notifications

The function works with any Sanity project containing a comment document type and can be easily customized to target different chats, include additional comment metadata, or format messages differently.

Contributor

Official Recipes by Sanity

First Published Timestamp Function

Featured contribution
Official(made by Sanity team)

Automatically track when content was first published with a timestamp that sets once and never overwrites, providing reliable publication history for analytics and editorial workflows.

Knut Melvær
Go to First Published Timestamp Function

Automatically tag blog posts

Featured contribution
Official(made by Sanity team)

AI-powered automatic tagging for Sanity blog posts that analyzes content to generate 3 relevant tags, maintaining consistency by reusing existing tags from your content library.

Go to Automatically tag blog posts