Integrations Guide - nself-org/nchat GitHub Wiki
Version: 0.5.0 Last Updated: January 2026
Complete guide to setting up and using integrations and webhooks in nself-chat.
- Overview
- Supported Integrations
- Slack Integration
- Discord Integration
- Telegram Integration
- GitHub Integration
- Jira Integration
- Incoming Webhooks
- Outgoing Webhooks
- Webhook Queue System
- Database Schema
- API Reference
nself-chat provides a comprehensive integration system that supports:
- OAuth-based integrations with popular services
- Bidirectional message sync between platforms
- Incoming webhooks to receive events from external services
- Outgoing webhooks to send events to external services
- Webhook queue with retry logic and rate limiting
- Import wizards for bulk message/channel imports
βββββββββββββββββββ
β nself-chat β
β βββββββββββββ β ββββββββββββ
β β Outgoing ββββΌββββββ>β External β
β β Webhooks β β β Services β
β βββββββββββββ β ββββββββββββ
β β β
β βββββββββββββ β β
β β Incoming β<ββΌββββββββββββββ
β β Webhooks β β
β βββββββββββββ β
β β
β βββββββββββββ β ββββββββββββ
β βIntegrationβ<ββΌββββββ>β Redis β
β β Queue β β β Queue β
β βββββββββββββ β ββββββββββββ
βββββββββββββββββββ
| Platform | Type | OAuth | Webhooks | Import | Bidirectional Sync |
|---|---|---|---|---|---|
| Slack | Communication | β | β | β | β |
| Discord | Communication | β | β | β | β |
| Telegram | Communication | β (Bot Token) | β | β | |
| GitHub | DevTools | β | β | β | β |
| Jira | DevTools | β | β | β | β |
| Google Drive | Storage | β | β | β | β |
-
Create Slack App:
- Go to https://api.slack.com/apps
- Click "Create New App"
- Choose "From scratch"
- Enter app name and workspace
-
Configure OAuth:
- Navigate to "OAuth & Permissions"
- Add redirect URL:
https://your-domain.com/api/auth/oauth/callback - Add scopes:
channels:historychannels:readchat:writefiles:readusers:readusers:read.email
-
Install App:
- Install to workspace
- Copy OAuth tokens
-
Setup Webhook (Optional):
- Navigate to "Event Subscriptions"
- Enable events
- Set Request URL:
https://your-domain.com/api/webhooks/slack - Subscribe to bot events:
message.channelsreaction_addedchannel_created
import { createSlackProvider } from '@/lib/integrations/slack/slack-client'
const provider = createSlackProvider({
clientId: process.env.SLACK_CLIENT_ID!,
clientSecret: process.env.SLACK_CLIENT_SECRET!,
redirectUri: 'https://your-domain.com/api/auth/oauth/callback',
})
// Import history
const result = await provider.importHistory(credentials, {
channelIds: ['C1234567890'],
startDate: '2024-01-01',
endDate: '2024-12-31',
})- Messages posted in nself-chat β forwarded to Slack
- Messages posted in Slack β received via webhook β posted to nself-chat
-
Create Discord Application:
- Go to https://discord.com/developers/applications
- Click "New Application"
- Enter application name
-
Configure Bot:
- Navigate to "Bot" section
- Create bot user
- Copy bot token
- Enable required intents:
- Presence Intent
- Server Members Intent
- Message Content Intent
-
Configure OAuth2:
- Navigate to "OAuth2" section
- Add redirect URL:
https://your-domain.com/api/auth/oauth/callback - Select scopes:
bot,identify,guilds - Select bot permissions: Read Messages, Send Messages, etc.
-
Invite Bot:
- Use OAuth2 URL generator to create invite link
- Invite bot to your Discord server
import { createDiscordProvider } from '@/lib/integrations/discord/discord-client'
const provider = createDiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
botToken: process.env.DISCORD_BOT_TOKEN!,
redirectUri: 'https://your-domain.com/api/auth/oauth/callback',
})
// Import history
const result = await provider.importHistory(credentials, {
guildIds: ['123456789012345678'],
channelIds: ['987654321098765432'],
startDate: '2024-01-01',
})Discord primarily uses Gateway WebSocket for bot events, but you can also use channel webhooks:
# Create Discord webhook
curl -X POST "https://your-domain.com/api/webhooks/discord" \
-H "Content-Type: application/json" \
-d '{"content": "Hello from external service!"}'-
Create Bot:
- Message @BotFather on Telegram
- Send
/newbotcommand - Follow prompts to create bot
- Copy bot token
-
Setup Webhook:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \ -d "url=https://your-domain.com/api/webhooks/telegram&secret_token=<YOUR_SECRET>"
-
Configure in nself-chat:
- No OAuth needed (uses bot token directly)
- Store bot token in environment variable
- Telegram Bot API cannot fetch historical messages
- Bots can only see messages sent after they were added to the chat
- For full history import, you'd need MTProto API (user account)
- Messages sync in real-time via webhook
import { createTelegramProvider } from '@/lib/integrations/telegram/telegram-client'
const provider = createTelegramProvider({
botToken: process.env.TELEGRAM_BOT_TOKEN!,
webhookUrl: 'https://your-domain.com/api/webhooks/telegram',
})
// Send message to chat
await provider.forwardMessage(
credentials,
-1001234567890, // Chat ID
'Hello from nself-chat!'
)-
Create GitHub OAuth App:
- Go to https://github.com/settings/developers
- Click "New OAuth App"
- Set Authorization callback URL:
https://your-domain.com/api/auth/oauth/callback
-
Setup Webhook:
- Go to repository settings
- Navigate to Webhooks
- Add webhook URL:
https://your-domain.com/api/webhooks/github - Select events: push, pull_request, issues, etc.
- Add secret for signature verification
-
push- Code pushed to repository -
pull_request- PR opened, closed, merged -
issues- Issues created, updated, closed -
issue_comment- Comments on issues/PRs -
pull_request_review- PR reviews -
release- New release created -
deployment- Deployment events
const client = provider.getClient(credentials)
const issue = await client.createIssue('owner', 'repo', {
title: 'Bug report from chat',
body: 'Issue details from message...',
labels: ['bug', 'from-chat'],
})-
Create Jira OAuth App:
- Go to https://developer.atlassian.com/console/myapps/
- Create new app
- Configure OAuth 2.0
- Add callback URL:
https://your-domain.com/api/auth/oauth/callback
-
Setup Webhook:
- Log in to Jira as admin
- Go to Settings > System > WebHooks
- Create webhook with URL:
https://your-domain.com/api/webhooks/jira - Select events: issue created, updated, etc.
jira:issue_createdjira:issue_updatedcomment_createdworklog_createdsprint_startedsprint_closed
const client = provider.getClient(credentials)
const issue = await client.createIssue('PROJECT', {
summary: 'Task from chat',
description: 'Details...',
issueType: 'Task',
})Incoming webhooks allow external services to POST messages to nself-chat channels.
import { getIncomingWebhookManager } from '@/lib/webhooks/incoming-webhooks'
const manager = getIncomingWebhookManager()
const webhook = manager.createWebhook({
name: 'External Service Webhook',
targetChannelId: 'channel-uuid',
enabled: true,
})
// Webhook URL
const url = `https://your-domain.com/api/webhooks/incoming/${webhook.token}`curl -X POST "https://your-domain.com/api/webhooks/incoming/<TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello from external service!",
"username": "External Bot",
"icon_url": "https://example.com/icon.png"
}'Outgoing webhooks send nself-chat events to external services.
import { getOutgoingWebhookManager } from '@/lib/webhooks/outgoing-webhooks'
const manager = getOutgoingWebhookManager()
const webhook = manager.createWebhook({
name: 'External Service',
url: 'https://external-service.com/webhook',
secret: 'your-secret-key',
events: ['message.created', 'channel.created', 'user.joined'],
})import { triggerWebhookEvent } from '@/lib/webhooks/outgoing-webhooks'
await triggerWebhookEvent(
'message.created',
{
messageId: '123',
channelId: '456',
content: 'Hello!',
author: { id: '789', username: 'user' },
},
{
userId: '789',
username: 'user',
}
)Outgoing webhooks include HMAC-SHA256 signature in X-Webhook-Signature header:
// Verify signature (Node.js example)
import crypto from 'crypto'
function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
const hmac = crypto.createHmac('sha256', secret)
const digest = 'sha256=' + hmac.update(payload).digest('hex')
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest))
}Webhooks use BullMQ + Redis for reliable delivery with retry logic.
import { initializeWebhookQueue } from '@/lib/webhooks/webhook-queue'
const manager = initializeWebhookQueue({
redis: {
host: 'localhost',
port: 6379,
password: process.env.REDIS_PASSWORD,
},
concurrency: 10,
maxRetries: 3,
retryDelay: 5000, // 5 seconds
timeout: 30000, // 30 seconds
})- Automatic Retries: Exponential backoff (5s, 10s, 20s)
- Rate Limiting: Configurable concurrency
- Delivery Tracking: Full audit log of all attempts
- Dead Letter Queue: Failed deliveries after max retries
- Statistics: Real-time queue metrics
const stats = await manager.getStats()
console.log(stats)
// {
// total: 1000,
// pending: 50,
// active: 10,
// completed: 900,
// failed: 40,
// delayed: 0
// }-
nchat_integrations- Integration configurations -
nchat_integration_mappings- Resource mappings (external β internal) -
nchat_outgoing_webhooks- Outgoing webhook configs -
nchat_webhook_deliveries- Delivery log -
nchat_incoming_webhooks- Incoming webhook configs -
nchat_integration_imports- Import job tracking -
nchat_integration_sync_queue- Sync operation queue
-- Get all active integrations
SELECT * FROM nchat_integrations
WHERE status = 'connected';
-- Get webhook delivery stats
SELECT
webhook_id,
COUNT(*) as total,
SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as successful,
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed
FROM nchat_webhook_deliveries
GROUP BY webhook_id;
-- Get pending sync operations
SELECT * FROM nchat_integration_sync_queue
WHERE status = 'pending'
AND scheduled_for <= NOW()
ORDER BY scheduled_for ASC
LIMIT 100;-
POST /api/auth/oauth/connect- Start OAuth flow -
GET /api/auth/oauth/callback- Handle OAuth callback -
POST /api/integrations/:id/disconnect- Disconnect integration -
POST /api/integrations/:id/import- Start import job -
GET /api/integrations/:id/status- Get integration status
-
POST /api/webhooks/incoming/:token- Receive incoming webhook -
POST /api/webhooks/github- GitHub webhook -
POST /api/webhooks/slack- Slack webhook -
POST /api/webhooks/discord- Discord webhook -
POST /api/webhooks/telegram- Telegram webhook -
POST /api/webhooks/jira- Jira webhook
- Always verify webhook signatures for incoming webhooks
- Use HTTPS for all webhook URLs
- Rotate secrets regularly
- IP whitelist when possible
- Rate limit webhook endpoints
- Use webhook queue for all outgoing webhooks
- Batch imports for large message histories
- Set concurrency limits to avoid overwhelming external APIs
- Monitor queue depth and adjust workers
- Log all webhook failures with full context
- Implement dead letter queue for manual review
- Alert on repeated failures
- Provide retry mechanism for transient failures
OAuth Callback Not Working:
- Verify redirect URI matches exactly
- Check OAuth app credentials
- Ensure callback endpoint is accessible
Webhooks Not Delivering:
- Check webhook queue is running
- Verify Redis connection
- Check network connectivity
- Review webhook logs
Import Failing:
- Verify API permissions/scopes
- Check rate limits
- Ensure date ranges are valid
- Review error logs
Enable debug logging:
DEBUG=integrations:* npm run devFor issues or questions:
- GitHub Issues: https://github.com/your-org/nself-chat/issues
- Documentation: https://docs.nself-chat.com
- Community: https://community.nself-chat.com