Code Snippets

A curated library of useful code snippets, N8n workflows, and quick references.

8 snippets found

Telegram Send Message with Inline Keyboard

Send a message with inline keyboard buttons using Telegram Bot API in N8n Code Node.

Telegramjavascript
javascript
// Send message with inline keyboard via Telegram Bot API
const botToken = $env.TELEGRAM_BOT_TOKEN;
const chatId = $input.first().json.chat_id;

const response = await fetch(
  `https://api.telegram.org/bot${botToken}/sendMessage`,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      chat_id: chatId,
      text: "Choose an option:",
      parse_mode: "HTML",
      reply_markup: {
        inline_keyboard: [
          [
            { text: "✅ Approve", callback_data: "approve" },
            { text: "❌ Reject", callback_data: "reject" },
          ],
          [{ text: "📋 Details", callback_data: "details" }],
        ],
      },
    }),
  }
);

return [{ json: await response.json() }];
telegrambotinline-keyboardn8nVideo

PostgreSQL Upsert with RETURNING

Insert or update a row on conflict and return the result. Perfect for syncing data from external APIs.

PostgreSQLsql
sql
-- Upsert: Insert or update user on conflict
-- Perfect for syncing Telegram user data
INSERT INTO users (
  telegram_id,
  username,
  first_name,
  last_seen,
  message_count
)
VALUES ($1, $2, $3, NOW(), 1)
ON CONFLICT (telegram_id)
DO UPDATE SET
  username = EXCLUDED.username,
  first_name = EXCLUDED.first_name,
  last_seen = NOW(),
  message_count = users.message_count + 1
RETURNING *;
postgresqlupserton-conflictreturning

N8n Code Node: API Pagination Loop

Fetch all pages from a paginated API endpoint in a single N8n Code Node execution.

Code Nodejavascript
javascript
// Fetch all pages from a paginated API
const baseUrl = "https://api.example.com/data";
const allItems = [];
let page = 1;
let hasMore = true;

while (hasMore) {
  const response = await this.helpers.httpRequest({
    url: `${baseUrl}?page=${page}&limit=100`,
    method: "GET",
    headers: {
      Authorization: `Bearer ${$env.API_TOKEN}`,
    },
  });

  allItems.push(...response.data);
  hasMore = response.pagination.hasNext;
  page++;

  // Safety limit
  if (page > 50) break;
}

return allItems.map(item => ({ json: item }));
n8npaginationapiloopGitHub

Verify Webhook Signature in N8n

Validate incoming webhook signatures using HMAC-SHA256 to ensure requests are authentic.

Code Nodejavascript
javascript
// Verify webhook signature (HMAC-SHA256)
const crypto = require('crypto');

const secret = $env.WEBHOOK_SECRET;
const payload = JSON.stringify($input.first().json);
const signature = $input.first().headers['x-signature'];

const expected = crypto
  .createHmac('sha256', secret)
  .update(payload)
  .digest('hex');

if (signature !== `sha256=${expected}`) {
  throw new Error('Invalid webhook signature');
}

return $input.all();
n8nwebhooksecurityhmac

Query JSONB Fields in PostgreSQL

Extract and filter data from JSONB columns using PostgreSQL operators.

PostgreSQLsql
sql
-- Query JSONB fields in PostgreSQL
-- Get users who have 'n8n' in their skills array
SELECT
  id,
  username,
  metadata->>'email' AS email,
  metadata->'skills' AS skills,
  created_at
FROM users
WHERE
  metadata->'skills' @> '["n8n"]'::jsonb
  AND (metadata->>'active')::boolean = true
ORDER BY created_at DESC
LIMIT 20;

-- Update a nested JSONB field
UPDATE users
SET metadata = jsonb_set(
  metadata,
  '{last_login}',
  to_jsonb(NOW()::text)
)
WHERE telegram_id = $1;
postgresqljsonbqueryfilter

Download File from Telegram

Download a file sent to your Telegram bot and save it using N8n.

Telegramjavascript
javascript
// Download file from Telegram message
const botToken = $env.TELEGRAM_BOT_TOKEN;
const fileId = $input.first().json.message.document.file_id;

// Step 1: Get file path
const fileInfo = await fetch(
  `https://api.telegram.org/bot${botToken}/getFile?file_id=${fileId}`
).then(r => r.json());

const filePath = fileInfo.result.file_path;

// Step 2: Download file
const fileUrl = `https://api.telegram.org/file/bot${botToken}/${filePath}`;
const fileBuffer = await fetch(fileUrl).then(r => r.arrayBuffer());

return [{
  json: {
    fileName: filePath.split('/').pop(),
    fileSize: fileBuffer.byteLength,
    fileUrl,
  },
  binary: {
    data: {
      data: Buffer.from(fileBuffer).toString('base64'),
      mimeType: 'application/octet-stream',
      fileName: filePath.split('/').pop(),
    },
  },
}];
telegrambotfiledownloadVideo

N8n Error Handling with Telegram Alert

A reusable error handling pattern that catches workflow errors and sends detailed alerts to Telegram.

N8n Generaljavascript
javascript
// Error handler — send alert to Telegram
const botToken = $env.TELEGRAM_BOT_TOKEN;
const adminChatId = $env.ADMIN_CHAT_ID;

const error = $input.first().json;
const workflowName = $workflow.name;
const timestamp = new Date().toISOString();

const message = [
  "🚨 <b>Workflow Error</b>",
  "",
  `📋 <b>Workflow:</b> ${workflowName}`,
  `⏰ <b>Time:</b> ${timestamp}`,
  `❌ <b>Error:</b> <code>${error.message || 'Unknown'}</code>`,
  `📍 <b>Node:</b> ${error.node || 'N/A'}`,
  "",
  "Check the execution log for details.",
].join("\n");

await fetch(
  `https://api.telegram.org/bot${botToken}/sendMessage`,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      chat_id: adminChatId,
      text: message,
      parse_mode: "HTML",
    }),
  }
);

return [{ json: { alertSent: true } }];
n8nerror-handlingtelegrammonitoring

Docker Cleanup Script

Clean up unused Docker images, containers, and volumes to free disk space on your VPS.

N8n Generalbash
bash
#!/bin/bash
# Docker cleanup script — safe for production VPS

echo "🧹 Docker Cleanup Starting..."

# Remove stopped containers
echo "Removing stopped containers..."
docker container prune -f

# Remove unused images (not used by any container)
echo "Removing dangling images..."
docker image prune -f

# Remove unused volumes (careful!)
echo "Removing unused volumes..."
docker volume prune -f

# Show disk usage
echo ""
echo "📊 Docker disk usage:"
docker system df

echo "✅ Cleanup complete!"
dockercleanupvpsbash