Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

discord-webhooks

БесплатноЗапускает вложенные скриптыНе проверен

Receive and verify Discord webhook events. Use when setting up Discord webhook handlers, debugging Ed25519 signature verification, handling PING endpoint…

hookdeckот hookdeck★ 104 звезды на GitHub

Об этом скилле

Discord Webhooks

When to Use This Skill

  • Setting up Discord webhook event handlers (outgoing webhooks)
  • Verifying Discord Ed25519 signatures with X-Signature-Ed25519 and X-Signature-Timestamp
  • Handling the PING (type 0) endpoint validation request
  • Handling events like APPLICATION_AUTHORIZED, APPLICATION_DEAUTHORIZED, ENTITLEMENT_CREATE, LOBBY_MESSAGE_CREATE, GAME_DIRECT_MESSAGE_CREATE, QUEST_USER_ENROLLMENT
  • Debugging "invalid request signature" errors when registering your webhook endpoint

Note: This skill covers outgoing webhooks (Discord → your server) — the same Ed25519 signing scheme is shared with Interactions endpoints. Incoming webhooks (your server → Discord channel via webhook URL) are not signed and not covered here.

Essential Code (USE THIS)

Discord uses Ed25519 asymmetric signatures (not HMAC). The signed content is the raw concatenation X-Signature-Timestamp + raw_body. Verification uses your application's public key (hex-encoded), available in the Discord Developer Portal.

Express Webhook Handler (Node.js)

Use the official-style discord-interactions helper (built on tweetnacl).

const express = require('express');
const { verifyKey } = require('discord-interactions');

const app = express();

// CRITICAL: Use express.raw() - verification needs raw body bytes
// Note: discord-interactions v4 returns a Promise from verifyKey — await it.
app.post('/webhooks/discord',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const signature = req.headers['x-signature-ed25519'];
    const timestamp = req.headers['x-signature-timestamp'];
    const publicKey = process.env.DISCORD_PUBLIC_KEY;

    if (!signature || !timestamp) {
      return res.status(401).send('Missing signature headers');
    }

    const isValid = await verifyKey(req.body, signature, timestamp, publicKey);
    if (!isValid) {
      return res.status(401).send('Invalid request signature');
    }

    const payload = JSON.parse(req.body.toString());

    // type: 0 = PING (endpoint validation). Reply 204 empty body.
    if (payload.type === 0) {
      return res.status(204).send();
    }

    // type: 1 = event payload
    if (payload.type === 1) {
      const event = payload.event;
      switch (event.type) {
        case 'APPLICATION_AUTHORIZED':
          console.log('App authorized for user:', event.data.user?.id);
          break;
        case 'APPLICATION_DEAUTHORIZED':
          console.log('App deauthorized for user:', event.data.user?.id);
          break;
        case 'ENTITLEMENT_CREATE':
          console.log('Entitlement created:', event.data.id);
          break;
        case 'LOBBY_MESSAGE_CREATE':
          console.log('Lobby message:', event.data.content);
          break;
        case 'GAME_DIRECT_MESSAGE_CREATE':
          console.log('Game DM:', event.data.content);
          break;
        default:
          console.log('Unhandled event type:', event.type);
      }
    }

    res.status(204).send();
  }
);

Python (FastAPI) Webhook Handler

Use PyNaCl for Ed25519 verification.

import os
import json
from fastapi import FastAPI, Request, Response, HTTPException
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError

app = FastAPI()

PUBLIC_KEY = os.environ["DISCORD_PUBLIC_KEY"]

def verify_discord_signature(body: bytes, signature: str, timestamp: str, public_key: str) -> bool:
    try:
        verify_key = VerifyKey(bytes.fromhex(public_key))
        verify_key.verify(timestamp.encode() + body, bytes.fromhex(signature))
        return True
    except (BadSignatureError, ValueError):
        return False

@app.post("/webhooks/discord")
async def discord_webhook(request: Request):
    signature = request.headers.get("x-signature-ed25519")
    timestamp = request.headers.get("x-signature-timestamp")
    if not signature or not timestamp:
        raise HTTPException(status_code=401, detail="Missing signature headers")

    body = await request.body()
    if not verify_discord_signature(body, signature, timestamp, PUBLIC_KEY):
        raise HTTPException(status_code=401, detail="Invalid request signature")

    payload = json.loads(body)

    # type 0 = PING endpoint validation
    if payload.get("type") == 0:
        return Response(status_code=204)

    # type 1 = event
    if payload.get("type") == 1:
        event = payload.get("event", {})
        event_type = event.get("type")
        # Handle event_type: APPLICATION_AUTHORIZED, ENTITLEMENT_CREATE, etc.
        print(f"Received Discord event: {event_type}")

    return Response(status_code=204)

For complete working examples with tests, see:

Полный SKILL.md на GitHub

Установить discord-webhooks в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

examples/express/.env.exampleexamples/express/README.mdexamples/express/package.jsonexamples/express/src/index.jsexamples/fastapi/.env.exampleexamples/fastapi/README.mdexamples/fastapi/main.pyexamples/fastapi/requirements.txtexamples/fastapi/test_webhook.pyexamples/nextjs/.env.exampleexamples/nextjs/README.mdexamples/nextjs/app/webhooks/discord/route.tsexamples/nextjs/package.jsonexamples/nextjs/vitest.config.tsreferences/overview.mdreferences/setup.mdreferences/verification.md

FAQ

Что делает скилл discord-webhooks?

Receive and verify Discord webhook events. Use when setting up Discord webhook handlers, debugging Ed25519 signature verification, handling PING endpoint validation, or processing events like APPLICATION_AUTHORIZED, ENTITLEMENT_CREATE, or LOBBY_MESSAGE_CREATE.

Как установить скилл discord-webhooks?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл discord-webhooks запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить discord-webhooks с