Building a Wedding Photo Gallery Bot: Part 2 – Telegram Bot Development & Integration

Building a Wedding Photo Gallery Bot: Part 2 - Telegram Bot Development & Integration

From BotFather to production: Building a feature-rich Telegram bot for wedding photo collection


Introduction

Welcome back to our wedding photo gallery series! In Part 1, we set up our infrastructure with Docker, Coolify, and PostgreSQL. Now comes the exciting part: building the Telegram bot that lets wedding guests upload photos, send wishes, and join the celebration.

By the end of this article, you’ll have a fully functional Telegram bot that:

  • ✅ Registers guests automatically
  • ✅ Handles photo uploads (single and multiple)
  • ✅ Supports HEIC/HEIF iPhone photos
  • ✅ Collects wishes from guests
  • ✅ Manages group chat integration
  • ✅ Provides interactive inline buttons
  • ✅ Handles photo deletion and management

Tech Stack:

  • Next.js 16 API Routes (webhook handler)
  • Telegram Bot API
  • Prisma ORM (database)
  • TypeScript (type safety)
  • Node.js file system (photo storage)

Understanding Telegram Bot Architecture

How Telegram Bots Work

Telegram bots communicate via two methods:

  1. Polling: Bot continuously asks Telegram “any new messages?”
    • ❌ Resource intensive
    • ❌ Slower response times
    • ✅ Works behind firewalls
  2. Webhooks: Telegram sends messages to your server
    • ✅ Real-time updates
    • ✅ Efficient (no polling)
    • ✅ Required for production

Our choice: Webhooks for instant photo uploads

Bot Flow Diagram

User sends photo → Telegram API → Our Webhook Endpoint
                                         ↓
                                  Verify Request
                                         ↓
                                  Download Photo
                                         ↓
                                  Save to Storage
                                         ↓
                                  Save to Database
                                         ↓
                                  Send Confirmation

Part 1: Creating Your Telegram Bot

Step 1: Chat with BotFather

BotFather is Telegram’s official bot for creating bots.

  1. Open Telegram
  2. Search for @BotFather
  3. Send /newbot
  4. Follow the prompts:
BotFather: Alright, a new bot. How are we going to call it?
You: Wedding Photo Gallery

BotFather: Good. Now let's choose a username for your bot.
You: myname_wedding_bot

BotFather: Done! Your token is: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz

Save this token! It’s your bot’s API key.

Step 2: Configure Bot Settings

Set bot description (what users see):

/setdescription

I help collect wedding photos from guests and display them in a beautiful gallery. Send /start to begin!

Set about text (bot profile):

/setabouttext

Wedding Photo Gallery Bot - Capture memories of our special day!

Set bot commands (command autocomplete):

/setcommands

start - Register and get started
help - Show help message
upload_photos - Learn how to upload photos
myphotos - View and manage your photos
wish - Send a wish to the newlyweds
delete_wish - View and delete your wishes
joingroup - Join the wedding photo group

Set bot photo (optional):

/setuserpic
[Upload a wedding-themed image]

Part 2: Project Setup

Directory Structure

wedding/
├── app/
│   ├── api/
│   │   ├── photos/
│   │   │   └── route.ts          # Fetch photos API
│   │   ├── telegram/
│   │   │   └── webhook/
│   │   │       └── route.ts      # Main bot logic (1350 lines!)
│   │   └── uploads/
│   │       └── [filename]/
│   │           └── route.ts      # Serve uploaded images
│   └── page.tsx
├── lib/
│   ├── prisma.ts                 # Database client
│   ├── telegram.ts               # Telegram API helpers
│   └── file-storage.ts           # Photo storage utils
├── types/
│   ├── telegram.ts               # Telegram types
│   └── database.ts               # Database types
├── prisma/
│   └── schema.prisma             # Database schema
├── public/
│   └── uploads/                  # Photo storage
└── .env

Install Dependencies

npm install @prisma/client prisma
npm install sharp                  # Image processing
npm install @types/node --save-dev

Environment Variables

Create .env:

# Database (from Part 1)
DATABASE_URL="postgresql://postgres:password@wedding-gallery-db:5432/postgres"

# Telegram Bot
TELEGRAM_BOT_TOKEN="123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
TELEGRAM_BOT_USERNAME="myname_wedding_bot"
TELEGRAM_WEBHOOK_SECRET="generate-random-secret"

# Optional: Wedding group chat
WEDDING_GROUP_CHAT_ID="-1001234567890"

# Storage
STORAGE_DIR="/app/public/uploads"
NEXT_PUBLIC_BASE_URL="https://your-domain.com"

# Node
NODE_ENV="production"

Generate webhook secret:

openssl rand -base64 32

Part 3: Telegram Type Definitions

Create types/telegram.ts:

// Telegram API types
export interface TelegramUpdate {
  update_id: number;
  message?: TelegramMessage;
  callback_query?: TelegramCallbackQuery;
}

export interface TelegramMessage {
  message_id: number;
  from?: TelegramUser;
  chat: TelegramChat;
  date: number;
  text?: string;
  photo?: TelegramPhotoSize[];
  document?: TelegramDocument;
  video?: TelegramVideo;
  caption?: string;
  media_group_id?: string;
  new_chat_members?: TelegramUser[];
  entities?: TelegramMessageEntity[];
}

export interface TelegramUser {
  id: number;
  is_bot: boolean;
  first_name: string;
  last_name?: string;
  username?: string;
}

export interface TelegramChat {
  id: number;
  type: 'private' | 'group' | 'supergroup' | 'channel';
  title?: string;
  username?: string;
}

export interface TelegramPhotoSize {
  file_id: string;
  file_unique_id: string;
  width: number;
  height: number;
  file_size?: number;
}

export interface TelegramDocument {
  file_id: string;
  file_unique_id: string;
  file_name?: string;
  mime_type?: string;
  file_size?: number;
}

export interface TelegramCallbackQuery {
  id: string;
  from: TelegramUser;
  message?: TelegramMessage;
  data?: string;
}

export interface TelegramMessageEntity {
  type: string;
  offset: number;
  length: number;
}

Part 4: Telegram API Helper Functions

Create lib/telegram.ts:

const TELEGRAM_API = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}`;

/**
 * Verify webhook request is from Telegram
 */
export function verifyTelegramRequest(secret: string): boolean {
  return secret === process.env.TELEGRAM_WEBHOOK_SECRET;
}

/**
 * Send text message to user
 */
export async function sendMessage(
  chatId: number,
  text: string,
  replyToMessageId?: number
) {
  const response = await fetch(`${TELEGRAM_API}/sendMessage`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      chat_id: chatId,
      text,
      parse_mode: 'Markdown',
      reply_to_message_id: replyToMessageId,
    }),
  });

  return response.json();
}

/**
 * Send message with inline buttons
 */
export async function sendMessageWithButtons(
  chatId: number,
  text: string,
  buttons: any[][],
  replyToMessageId?: number
) {
  const response = await fetch(`${TELEGRAM_API}/sendMessage`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      chat_id: chatId,
      text,
      parse_mode: 'Markdown',
      reply_markup: { inline_keyboard: buttons },
      reply_to_message_id: replyToMessageId,
    }),
  });

  return response.json();
}

/**
 * Get highest resolution photo from array
 */
export function getHighestResolutionPhoto(photos: any[]) {
  return photos.reduce((prev, current) =>
    current.file_size > prev.file_size ? current : prev
  );
}

/**
 * Get file info from Telegram
 */
export async function getFileInfo(fileId: string) {
  const response = await fetch(`${TELEGRAM_API}/getFile?file_id=${fileId}`);
  const data = await response.json();
  return data.ok ? data.result : null;
}

/**
 * Download file from Telegram
 */
export async function downloadTelegramFile(filePath: string) {
  const fileUrl = `https://api.telegram.org/file/bot${process.env.TELEGRAM_BOT_TOKEN}/${filePath}`;
  const response = await fetch(fileUrl);
  return Buffer.from(await response.arrayBuffer());
}

/**
 * Send photo to chat
 */
export async function sendPhotoToChat(
  chatId: number,
  fileId: string,
  caption?: string
) {
  const response = await fetch(`${TELEGRAM_API}/sendPhoto`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      chat_id: chatId,
      photo: fileId,
      caption,
      parse_mode: 'Markdown',
    }),
  });

  const data = await response.json();
  return data.ok ? data.result : null;
}

/**
 * Send chat action (typing, uploading, etc.)
 */
export async function sendChatAction(chatId: number, action: string) {
  await fetch(`${TELEGRAM_API}/sendChatAction`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ chat_id: chatId, action }),
  });
}

/**
 * Delete message
 */
export async function deleteMessage(chatId: number, messageId: number) {
  await fetch(`${TELEGRAM_API}/deleteMessage`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ chat_id: chatId, message_id: messageId }),
  });
}

/**
 * Answer callback query (button press)
 */
export async function answerCallbackQuery(
  queryId: string,
  text?: string,
  showAlert = false
) {
  await fetch(`${TELEGRAM_API}/answerCallbackQuery`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      callback_query_id: queryId,
      text,
      show_alert: showAlert,
    }),
  });
}

/**
 * Create chat invite link
 */
export async function createChatInviteLink(chatId: number) {
  const response = await fetch(`${TELEGRAM_API}/createChatInviteLink`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      chat_id: chatId,
      creates_join_request: false,
    }),
  });

  const data = await response.json();
  if (data.ok) {
    return { success: true, link: data.result.invite_link };
  }
  return { success: false, error: data.description };
}

Part 5: File Storage Implementation

Create lib/file-storage.ts:

import fs from 'fs/promises';
import path from 'path';
import sharp from 'sharp';

const STORAGE_DIR = process.env.STORAGE_DIR || '/app/public/uploads';

/**
 * Ensure storage directory exists
 */
async function ensureStorageDir() {
  try {
    await fs.access(STORAGE_DIR);
  } catch {
    await fs.mkdir(STORAGE_DIR, { recursive: true });
  }
}

/**
 * Upload photo to storage
 */
export async function uploadPhotoToStorage(
  fileBuffer: Buffer,
  fileName: string
) {
  try {
    await ensureStorageDir();

    const filePath = path.join(STORAGE_DIR, fileName);

    // Convert HEIC to JPEG if needed
    let processedBuffer = fileBuffer;
    if (fileName.toLowerCase().endsWith('.heic') || fileName.toLowerCase().endsWith('.heif')) {
      processedBuffer = await sharp(fileBuffer)
        .jpeg({ quality: 90 })
        .toBuffer();
      fileName = fileName.replace(/.(heic|heif)$/i, '.jpg');
    }

    // Optimize image (compress without losing quality)
    const optimizedBuffer = await sharp(processedBuffer)
      .resize(1920, 1920, { fit: 'inside', withoutEnlargement: true })
      .jpeg({ quality: 85, progressive: true })
      .toBuffer();

    await fs.writeFile(filePath, optimizedBuffer);

    const publicUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/api/uploads/${fileName}`;

    return {
      path: fileName,
      publicUrl,
    };
  } catch (error) {
    console.error('Error uploading photo:', error);
    return null;
  }
}

/**
 * Delete photo from storage
 */
export async function deletePhotoFromStorage(fileName: string) {
  try {
    const filePath = path.join(STORAGE_DIR, fileName);
    await fs.unlink(filePath);
  } catch (error) {
    console.error('Error deleting photo:', error);
  }
}

Part 6: Webhook Handler – The Heart of the Bot

Create app/api/telegram/webhook/route.ts. This is where all the magic happens!

Structure Overview

// Main webhook endpoint
export async function POST(request: NextRequest) {
  // 1. Verify request is from Telegram
  // 2. Parse update
  // 3. Route to appropriate handler
  // 4. Return response
}

// Handler functions
async function handleRegistration()      // /start command
async function handlePhotoUpload()       // Photo messages
async function handleWishCommand()       // /wish command
async function handleMyPhotos()          // /myphotos command
async function handleDeletePhoto()       // Photo deletion
async function handleCallbackQuery()     // Button presses
async function handleJoinGroupCommand()  // /joingroup command

Key Features Implementation

1. User Registration (/start command)

async function handleRegistration(
  user: any,
  chatId: number,
  messageId: number
) {
  // Check if user exists
  const existingGuest = await prisma.guest.findFirst({
    where: { telegramUserId: BigInt(user.id) },
  });

  if (existingGuest) {
    // Welcome back message
    await sendMessageWithButtons(
      chatId,
      `Welcome back, ${user.first_name}! 👋nn...`,
      [
        [
          { text: '📸 My Photos', callback_data: 'cmd_myphotos' },
          { text: '💝 Leave a Wish', callback_data: 'cmd_wish' },
        ],
        [{ text: '👥 Join Wedding Group', callback_data: 'cmd_joingroup' }],
      ],
      messageId
    );
    return;
  }

  // Register new guest
  await prisma.guest.create({
    data: {
      telegramUserId: BigInt(user.id),
      telegramUsername: user.username,
      firstName: user.first_name,
      lastName: user.last_name,
    },
  });

  await sendMessageWithButtons(chatId, 'Welcome message...', buttons, messageId);
}

Key Concepts:

  • BigInt: Telegram user IDs exceed JavaScript’s safe integer range
  • Upsert logic: Check existence before creating
  • Inline buttons: Interactive UI for better UX

2. Photo Upload (Single Photo)

async function handlePhotoUpload(
  user: any,
  photos: any[],
  caption: string | undefined,
  chatId: number,
  messageId: number
) {
  // Show "uploading photo" indicator
  await sendChatAction(chatId, 'upload_photo');

  // Get or create guest
  let guest = await prisma.guest.findFirst({
    where: { telegramUserId: BigInt(user.id) },
  });

  if (!guest) {
    guest = await prisma.guest.create({
      data: {
        telegramUserId: BigInt(user.id),
        telegramUsername: user.username,
        firstName: user.first_name,
        lastName: user.last_name,
      },
    });
  }

  // Get highest resolution photo
  const highestResPhoto = getHighestResolutionPhoto(photos);

  // Get file info from Telegram
  const fileInfo = await getFileInfo(highestResPhoto.file_id);

  // Download file
  const fileBuffer = await downloadTelegramFile(fileInfo.file_path);

  // Upload to our storage
  const fileName = `photo-${user.id}-${Date.now()}.jpg`;
  const uploadResult = await uploadPhotoToStorage(fileBuffer, fileName);

  // Save to database
  const photo = await prisma.photo.create({
    data: {
      guestId: guest.id,
      storagePath: uploadResult.path,
      publicUrl: uploadResult.publicUrl,
      telegramFileId: highestResPhoto.file_id,
      caption: caption,
    },
  });

  // Send confirmation
  await sendMessage(
    chatId,
    `✅ Your photo has been added to the wedding gallery!nn🌐 View gallery: ${galleryUrl}#gallery`,
    messageId
  );

  // Forward to wedding group (if configured)
  if (WEDDING_GROUP_CHAT_ID) {
    const groupMessageResult = await sendPhotoToChat(
      WEDDING_GROUP_CHAT_ID,
      highestResPhoto.file_id,
      `📸 Photo from ${user.first_name}${caption ? `nn${caption}` : ''}`
    );

    // Save group message ID for deletion feature
    if (groupMessageResult?.message_id) {
      await prisma.photo.update({
        where: { id: photo.id },
        data: { groupMessageId: groupMessageResult.message_id.toString() },
      });
    }
  }
}

Key Concepts:

  • Telegram file handling: file_id → getFile → download → process
  • Image optimization: Resize and compress with Sharp
  • HEIC support: Convert iPhone photos to JPEG
  • Group forwarding: Share photos with all guests
  • Message tracking: Store group message ID for deletion

3. Multiple Photos (Media Group)

When users send multiple photos at once, Telegram sends them as a “media group”:

// Track media groups
const mediaGroups = new Map<string, { photos: any[]; timeout: NodeJS.Timeout }>();

async function handleMediaGroup(
  user: any,
  mediaGroupId: string,
  photos: any[],
  caption: string | undefined,
  chatId: number,
  messageId: number
) {
  if (!mediaGroups.has(mediaGroupId)) {
    // First photo in group - create timeout
    const timeout = setTimeout(async () => {
      const group = mediaGroups.get(mediaGroupId);
      if (group) {
        await processMediaGroupPhotos(user, group.photos, chatId);
        mediaGroups.delete(mediaGroupId);
      }
    }, 1000); // Wait 1 second for all photos

    mediaGroups.set(mediaGroupId, {
      photos: [{ photos, caption, messageId }],
      timeout,
    });
  } else {
    // Add to existing group
    const group = mediaGroups.get(mediaGroupId)!;
    group.photos.push({ photos, caption, messageId });
  }
}

Why the timeout?

  • Telegram sends media group photos as separate messages
  • We batch them together using a 1-second delay
  • Process all photos at once for efficiency

4. Wishes Feature

// Track users waiting to send wishes
const usersWaitingForWish = new Set<number>();

async function handleWishCommand(
  user: any,
  messageText: string,
  chatId: number,
  messageId: number
) {
  const wishText = messageText.replace('/wish', '').trim();

  if (wishText) {
    // Wish provided in same message
    await saveWish(user, wishText, chatId, messageId);
  } else {
    // Prompt user for wish
    usersWaitingForWish.add(user.id);
    await sendMessage(
      chatId,
      '💝 Please send your heartfelt wish for the newlyweds!nn✨ Just type your message in the next message.',
      messageId
    );
  }
}

async function handleWishMessage(
  user: any,
  message: string,
  chatId: number,
  messageId: number
) {
  // User sent wish as follow-up message
  usersWaitingForWish.delete(user.id);
  await saveWish(user, message, chatId, messageId);
}

async function saveWish(
  user: any,
  wish: string,
  chatId: number,
  messageId: number
) {
  let guest = await prisma.guest.findFirst({
    where: { telegramUserId: BigInt(user.id) },
  });

  if (!guest) {
    guest = await prisma.guest.create({ /* ... */ });
  }

  await prisma.wish.create({
    data: {
      guestId: guest.id,
      message: wish,
    },
  });

  await sendMessage(
    chatId,
    `💌 Thank you for your beautiful wish!nn"${wish}"nn✨ Your message has been added to the gallery!`,
    messageId
  );
}

Key Concepts:

  • State management: Track users in “wish mode”
  • Flexible input: Accept /wish message or two-step flow
  • Auto-registration: Create guest if not exists

5. Photo Management (/myphotos + Deletion)

async function handleMyPhotos(user: any, chatId: number, messageId: number) {
  const guest = await prisma.guest.findFirst({
    where: { telegramUserId: BigInt(user.id) },
    include: {
      photos: {
        orderBy: { uploadedAt: 'desc' },
      },
    },
  });

  if (!guest || guest.photos.length === 0) {
    await sendMessage(
      chatId,
      'You haven't uploaded any photos yet. Send me some photos to get started! 📸',
      messageId
    );
    return;
  }

  await sendMessage(
    chatId,
    `You have uploaded ${guest.photos.length} photo(s). Tap the 🗑️ Delete button below any photo to remove it.`,
    messageId
  );

  // Send each photo with delete button
  for (let index = 0; index < guest.photos.length; index++) {
    const photo = guest.photos[index];
    const caption = `Photo ${index + 1}${photo.caption ? ': ' + photo.caption : ''}`;

    await sendPhotoWithButtons(chatId, photo.telegramFileId, caption, [
      [{ text: '🗑️ Delete', callback_data: `delete_${photo.id}` }],
    ]);
  }
}

// Handle delete button press
async function handleCallbackQuery(callbackQuery: any) {
  const data = callbackQuery.data;

  if (data?.startsWith('delete_')) {
    const photoId = data.replace('delete_', '');

    // Find and verify ownership
    const photo = await prisma.photo.findUnique({
      where: { id: photoId },
      include: { guest: true },
    });

    if (photo.guest.telegramUserId !== BigInt(user.id)) {
      await answerCallbackQuery(
        callbackQuery.id,
        'You can only delete your own photos',
        true
      );
      return;
    }

    // Delete from storage
    await deletePhotoFromStorage(photo.storagePath);

    // Delete from group chat
    if (photo.groupMessageId && WEDDING_GROUP_CHAT_ID) {
      await deleteMessage(WEDDING_GROUP_CHAT_ID, parseInt(photo.groupMessageId));
    }

    // Delete from database
    await prisma.photo.delete({ where: { id: photoId } });

    await answerCallbackQuery(callbackQuery.id, 'Photo deleted successfully ✅');
  }
}

Key Concepts:

  • Ownership verification: Users can only delete their own photos
  • Cascading deletion: Storage + database + group message
  • Inline buttons: Each photo has its own delete button

6. Group Chat Integration

async function handleJoinGroupCommand(
  user: any,
  chatId: number,
  messageId: number
) {
  // Send confirmation prompt
  await sendMessageWithButtons(
    chatId,
    `🎉 Would you like to join the wedding photo group?nnBy joining:n✅ You'll see all wedding photos shared by guestsn✅ Your photos will be shared with everyonen✅ You can chat with other guests`,
    [
      [
        { text: '✅ Yes, join group', callback_data: 'confirm_join_yes' },
        { text: '❌ No thanks', callback_data: 'confirm_join_no' },
      ],
    ],
    messageId
  );
}

async function handleGroupJoinConfirmation(/* ... */) {
  // Create invite link
  const inviteResult = await createChatInviteLink(WEDDING_GROUP_CHAT_ID);

  if (!inviteResult.success) {
    await sendMessage(
      chatId,
      '⚠️ Bot needs admin rights in the group to create invite links.',
      messageId
    );
    return;
  }

  // Update guest status
  await prisma.guest.update({
    where: { id: guest.id },
    data: { inWeddingGroup: true },
  });

  await sendMessage(
    chatId,
    `🎉 Great! Click the link below to join the wedding group:nn${inviteResult.link}`
  );
}

Requirements:

  • Bot must be admin in group
  • Admin must grant “Invite users via link” permission

Part 7: Setting Up the Webhook

Create Webhook Setup Script

Create scripts/setup-webhook.sh:

#!/bin/bash

# Load environment variables
source .env

WEBHOOK_URL="${NEXT_PUBLIC_BASE_URL}/api/telegram/webhook"

echo "Setting up webhook for: $WEBHOOK_URL"

curl -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/setWebhook" 
  -H "Content-Type: application/json" 
  -d "{
    "url": "${WEBHOOK_URL}",
    "secret_token": "${TELEGRAM_WEBHOOK_SECRET}",
    "allowed_updates": ["message", "callback_query"],
    "max_connections": 40
  }"

echo "nnChecking webhook info:"
curl "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/getWebhookInfo"

Make it executable:

chmod +x scripts/setup-webhook.sh

Run After Deployment

./scripts/setup-webhook.sh

Expected output:

{
  "ok": true,
  "result": {
    "url": "https://your-domain.com/api/telegram/webhook",
    "has_custom_certificate": false,
    "pending_update_count": 0,
    "max_connections": 40
  }
}

Part 8: Testing Your Bot

Local Development with ngrok

For local testing:

# Install ngrok
npm install -g ngrok

# Start Next.js dev server
npm run dev

# In another terminal, start ngrok
ngrok http 3000

# Set webhook to ngrok URL
curl -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/setWebhook" 
  -H "Content-Type: application/json" 
  -d "{
    "url": "https://abc123.ngrok.io/api/telegram/webhook",
    "secret_token": "${TELEGRAM_WEBHOOK_SECRET}"
  }"

Test Scenarios

  1. Registration:
    • Send /start to bot
    • Should receive welcome message with buttons
  2. Photo Upload:
    • Send a photo
    • Should receive confirmation
    • Photo should appear in database
  3. Multiple Photos:
    • Select multiple photos and send together
    • Should receive single confirmation for all
  4. HEIC Photos (iPhone):
    • Send photo as file
    • Should convert to JPEG automatically
  5. Wishes:
    • Send /wish Your message here
    • Should save to database
  6. Photo Management:
    • Send /myphotos
    • Should display all photos with delete buttons
  7. Group Join:
    • Send /joingroup
    • Should receive invite link (if bot is admin)

Part 9: Advanced Features

Feature 1: Get Group Chat ID

To enable group forwarding, you need the group chat ID:

// In webhook handler, log group chat IDs
if (update.message?.chat?.type === 'group' || update.message?.chat?.type === 'supergroup') {
  console.log('📊 GROUP CHAT DETECTED:');
  console.log(`  Title: ${update.message.chat.title}`);
  console.log(`  Chat ID: ${update.message.chat.id}`);
  console.log(`  👉 Add this to your .env: WEDDING_GROUP_CHAT_ID=${update.message.chat.id}`);
}

Add bot to group, send a message, check logs for the ID.

Feature 2: New Member Welcome

if (message.new_chat_members && message.new_chat_members.length > 0) {
  for (const newMember of message.new_chat_members) {
    if (!newMember.is_bot) {
      await handleNewMemberWelcome(newMember, message.chat.id);
    }
  }
}

async function handleNewMemberWelcome(newMember: any, groupChatId: number) {
  const welcomeMessage = `🎉 Welcome to the Wedding Photo Group!nn👋 Hi ${newMember.first_name}!nnSend /start to @${process.env.TELEGRAM_BOT_USERNAME} to register and start uploading photos!`;

  try {
    await sendMessage(newMember.id, welcomeMessage);
  } catch (error) {
    // User hasn't started bot yet - can't send private message
    console.error('Failed to send welcome message:', error);
  }
}

Feature 3: Bot Mention in Groups

Only respond when bot is mentioned in group chats:

const isGroup = message.chat.type === 'group' || message.chat.type === 'supergroup';

if (isGroup) {
  const botUsername = process.env.TELEGRAM_BOT_USERNAME || 'waiter';
  const isMentioned = message.text?.includes(`@${botUsername}`) ||
    message.entities?.some(entity =>
      entity.type === 'mention' &&
      message.text?.substring(entity.offset, entity.offset + entity.length) === `@${botUsername}`
    );

  if (!isMentioned && !message.text?.startsWith('/')) {
    return NextResponse.json({ ok: true }); // Ignore
  }
}

Part 10: Error Handling & Best Practices

1. Security: Webhook Verification

Always verify requests:

export async function POST(request: NextRequest) {
  const secret = request.headers.get('X-Telegram-Bot-Api-Secret-Token');

  if (!secret || !verifyTelegramRequest(secret)) {
    console.error('Invalid or missing secret token');
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  // Process webhook...
}

2. Graceful Error Handling

try {
  await handlePhotoUpload(user, photos, caption, chatId, messageId);
} catch (error) {
  console.error('Error in handlePhotoUpload:', error);
  await sendMessage(
    chatId,
    'Sorry, there was an error uploading your photo.',
    messageId
  );
}

3. Database Error Recovery

try {
  await prisma.guest.create({ data: { /* ... */ } });
} catch (error) {
  if (error.code === 'P2002') {
    // Unique constraint violation - user already exists
    console.log('User already registered');
  } else {
    throw error;
  }
}

4. Rate Limiting

Telegram API has limits:

  • Messages: 30 messages per second
  • Same user: 1 message per second
  • Group messages: 20 messages per minute

Implement queuing for high-traffic scenarios.

5. Logging Best Practices

console.log(`📸 Photo uploaded by ${user.first_name} (ID: ${user.id})`);
console.error(`❌ Failed to download file: ${fileId}`, error);
console.info(`✅ Guest registered: ${user.username}`);

Troubleshooting Common Issues

Issue 1: Webhook Not Receiving Updates

Check webhook status:

curl "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/getWebhookInfo"

Look for:

  • url: Should match your domain
  • pending_update_count: Should be 0
  • last_error_date: If present, indicates errors

Fix:

# Delete webhook
curl -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/deleteWebhook"

# Set again
./scripts/setup-webhook.sh

Issue 2: Photos Not Uploading

Check:

  1. Storage directory exists and is writable
  2. Sharp is installed (npm list sharp)
  3. File size isn’t too large (Telegram max: 20MB)

Debug:

console.log('File info:', fileInfo);
console.log('Buffer size:', fileBuffer.length);
console.log('Upload result:', uploadResult);

Issue 3: BigInt Serialization Error

When returning data to frontend:

// ❌ Wrong - BigInt can't be serialized to JSON
return NextResponse.json({ userId: user.telegramUserId });

// ✅ Correct - Convert to string
return NextResponse.json({ userId: user.telegramUserId.toString() });

Performance Optimization

1. Image Processing

// Optimize images before storing
const optimizedBuffer = await sharp(fileBuffer)
  .resize(1920, 1920, { fit: 'inside', withoutEnlargement: true })
  .jpeg({ quality: 85, progressive: true })
  .toBuffer();

2. Batch Operations

Process media groups in batch:

// Instead of uploading photos one by one
for (const photo of photos) {
  await uploadPhoto(photo);
}

// Use Promise.all for parallel processing
await Promise.all(
  photos.map(photo => uploadPhoto(photo))
);

3. Database Indexing

Already covered in Part 1, but ensure:

  • telegram_user_id is indexed
  • uploaded_at is indexed for sorting
  • photo_id + guest_id composite index for likes

Bot Analytics & Monitoring

Track Key Metrics

// In webhook handler
const metrics = {
  totalPhotos: await prisma.photo.count(),
  totalGuests: await prisma.guest.count(),
  totalWishes: await prisma.wish.count(),
  photosToday: await prisma.photo.count({
    where: {
      uploadedAt: { gte: new Date(new Date().setHours(0, 0, 0, 0)) },
    },
  }),
};

console.log('📊 Metrics:', metrics);

Monitor Bot Health

Create health check endpoint:

// app/api/health/route.ts
export async function GET() {
  const dbStatus = await prisma.$queryRaw`SELECT 1`;

  return NextResponse.json({
    status: 'healthy',
    database: dbStatus ? 'connected' : 'disconnected',
    timestamp: new Date().toISOString(),
  });
}

What’s Next?

Congratulations! You now have a fully functional Telegram bot that:

  • ✅ Registers guests automatically
  • ✅ Handles photo uploads (single & multiple)
  • ✅ Converts iPhone HEIC photos
  • ✅ Collects wishes from guests
  • ✅ Manages group chat integration
  • ✅ Provides interactive buttons
  • ✅ Handles photo deletion

In Part 3, we’ll:

  • Deploy the Next.js web application to Coolify
  • Configure custom domain with Hostinger
  • Set up SSL certificates
  • Implement Redis caching for 600+ guests
  • Add Server-Sent Events (SSE) for real-time updates
  • Configure performance optimizations

Resources


Questions?

Drop your questions in the comments! Next article coming soon: Deployment & Scaling (Part 3).


Built with ❤️ for capturing unforgettable moments

You might also like

More stories worth your time — dive in while you are here.

Comments

Sign in with GitHub to comment or react. Threads live in GitHub Discussions, so you can also reply from GitHub.