Skip to main content

Writing a Channel Plugin

This guide walks through writing a complete Channel plugin from scratch using a hypothetical Webhook platform as an example.

Overview

Minimal structure of a Channel plugin:

my-channel-plugin/
├── elftia-channel.json # Manifest file (required)
├── package.json # npm package description
├── tsconfig.json # TypeScript configuration
├── src/
│ └── index.ts # Entry file (exports factory function)
└── dist/
└── index.cjs # Compiled output (CommonJS format)

Step 1: Initialize Project

mkdir elftia-channel-webhook
cd elftia-channel-webhook
npm init -y

Install development dependencies:

npm install -D typescript tsup @elftia/channel-sdk

Step 2: Create Manifest File

Create elftia-channel.json:

{
"name": "elftia-channel-webhook",
"type": "webhook",
"displayName": "Webhook",
"version": "1.0.0",
"description": "Receive and send messages via HTTP Webhook",
"author": "Your Name",
"entry": "dist/index.cjs",
"credentials": [
{
"key": "incomingUrl",
"label": "Incoming Webhook URL",
"type": "text",
"required": true,
"placeholder": "https://example.com/webhook/incoming",
"helpText": "Webhook endpoint for receiving messages"
},
{
"key": "outgoingSecret",
"label": "Outgoing Secret",
"type": "password",
"required": false,
"helpText": "Secret key for validating outgoing requests"
}
],
"capabilities": {
"typing": false,
"reactions": false,
"attachments": false,
"threads": false,
"groupChat": false
},
"maxMessageLength": 10000
}

Step 3: Implement Plugin

Create src/index.ts:

import type {
ChannelPlugin,
ChannelPluginContext,
ChannelPluginFactory,
} from '@elftia/channel-sdk';

/**
* Webhook Channel plugin implementation
*/
class WebhookPlugin implements ChannelPlugin {
readonly type = 'webhook';
private connected = false;
private credentials: Record<string, string> = {};
private pollTimer: ReturnType<typeof setInterval> | null = null;

constructor(private ctx: ChannelPluginContext) {}

async connect(
credentials: Record<string, string>,
_options?: Record<string, unknown>,
): Promise<void> {
this.credentials = credentials;

if (!credentials.incomingUrl) {
throw new Error('Incoming Webhook URL is required');
}

this.ctx.log.info('Connecting to webhook endpoint', {
url: credentials.incomingUrl,
});

// Verify endpoint reachability
try {
const response = await fetch(credentials.incomingUrl, {
method: 'HEAD',
signal: AbortSignal.timeout(5000),
});
if (!response.ok) {
throw new Error(`Endpoint returned ${response.status}`);
}
} catch (err) {
throw new Error(
`Cannot reach webhook endpoint: ${(err as Error).message}`,
);
}

// Start polling for new messages (example: every 5 seconds)
this.pollTimer = setInterval(() => {
this.pollMessages().catch((err) => {
this.ctx.log.error('Poll error', err as Error);
});
}, 5000);

this.connected = true;
this.ctx.emitStatusChange('connected');
this.ctx.log.info('Connected successfully');
}

async disconnect(): Promise<void> {
if (this.pollTimer) {
clearInterval(this.pollTimer);
this.pollTimer = null;
}
this.connected = false;
this.ctx.emitStatusChange('disconnected');
this.ctx.log.info('Disconnected');
}

isConnected(): boolean {
return this.connected;
}

async sendMessage(chatId: string, text: string): Promise<void> {
const url = this.credentials.incomingUrl;
if (!url) throw new Error('Not connected');

const body = JSON.stringify({
chatId,
text,
secret: this.credentials.outgoingSecret,
});

const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(10000),
});

if (!response.ok) {
throw new Error(`Send failed: HTTP ${response.status}`);
}

this.ctx.log.debug('Message sent', { chatId, length: text.length });
}

async dispose(): Promise<void> {
await this.disconnect();
}

// ─── Internal methods ──────────────────────────

private async pollMessages(): Promise<void> {
const lastPollTime = await this.ctx.storage.get<string>('lastPollTime');
const since = lastPollTime || new Date(0).toISOString();

const url = `${this.credentials.incomingUrl}?since=${encodeURIComponent(since)}`;

const response = await fetch(url, {
signal: AbortSignal.timeout(5000),
});

if (!response.ok) return;

const data = (await response.json()) as {
messages: Array<{
id: string;
chatId: string;
senderId: string;
senderName: string;
content: string;
timestamp: string;
}>;
};

for (const msg of data.messages) {
this.ctx.emitMessage({
id: msg.id,
chatId: msg.chatId,
senderId: msg.senderId,
senderName: msg.senderName,
content: msg.content,
timestamp: msg.timestamp,
isFromMe: false,
isGroup: false,
});
}

if (data.messages.length > 0) {
const latest = data.messages[data.messages.length - 1];
await this.ctx.storage.set('lastPollTime', latest.timestamp);
}
}
}

/**
* Factory function — plugin's default export
*/
const factory: ChannelPluginFactory = (ctx) => new WebhookPlugin(ctx);
export default factory;

Step 4: Configure Build

Create tsconfig.json:

{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"outDir": "dist",
"declaration": false,
"skipLibCheck": true
},
"include": ["src"]
}

Add build scripts to package.json:

{
"name": "elftia-channel-webhook",
"version": "1.0.0",
"main": "dist/index.cjs",
"scripts": {
"build": "tsup src/index.ts --format cjs --outDir dist --clean",
"dev": "tsup src/index.ts --format cjs --outDir dist --watch"
},
"devDependencies": {
"@elftia/channel-sdk": "^1.0.0",
"tsup": "^8.0.0",
"typescript": "^5.6.0"
}
}

Build the plugin:

npm run build

Confirm that dist/index.cjs has been generated.

Step 5: Local Testing

Link the plugin directory to Elftia's plugins directory:

# Windows
mklink /J "%APPDATA%\elftia\channel-plugins\webhook" "C:\path\to\elftia-channel-webhook"

# macOS / Linux
ln -s /path/to/elftia-channel-webhook ~/.config/elftia/channel-plugins/webhook

Or use Elftia's local installation feature:

ChannelPluginLoader.installFromLocal('/path/to/elftia-channel-webhook')

Verify Loading

  1. Start Elftia
  2. Open Settings → Channels → Add Channel
  3. Confirm that Webhook appears in the list
  4. Create an instance, fill in credentials, test connection

Development Mode

Use npm run dev (watch mode) during development; tsup will automatically recompile after code changes. Restart Elftia to load the latest code.

Step 6: Publish to Marketplace

Packaging

Package the plugin as a .zip file (root must contain elftia-channel.json):

cd elftia-channel-webhook
zip -r elftia-channel-webhook-1.0.0.zip \
elftia-channel.json \
package.json \
dist/

Publishing

Submit to Elftia Channel Plugin Marketplace:

  1. Ensure the version in elftia-channel.json is correct
  2. Calculate SHA-256 checksum of the zip file
  3. Submit the zip file and checksum to the Marketplace repository
  4. After review approval, the plugin will appear in the CDN's channel-manifest.json

Development Notes

Entry File Format

Plugin entry must be in CommonJS format (.cjs or standard .js) because Elftia loads plugins with require():

const mod = require(entryPath);
const factory = mod.default || mod;

Error Handling

  • Errors in connect() are caught by Registry and the instance state is set to error
  • Errors in sendMessage() are caught by Router and logged
  • Use ctx.log.error() to log internal errors
  • Always set timeouts for network requests

Status Reporting

Use ctx.emitStatusChange() to promptly report status changes:

StatusWhen to Report
connectingStarting to establish connection
connectedConnection successful
disconnectedActively disconnected
errorConnection failed or runtime error
reconnectingAutomatically reconnecting

Registry standardizes status handling: it won't downgrade connected to connecting (prevents state flicker from auto-reconnect).

Storage Best Practices

  • Use ctx.storage to store state that needs to persist across sessions (e.g. polling offset)
  • Values are JSON-serialized; ensure stored data is serializable
  • Framework automatically clears all storage data for an instance when it is deleted

Data Directory

ctx.dataDir provides a persistent filesystem directory suitable for storing:

  • Downloaded files (e.g. received images)
  • Cache data
  • Temporary files

Directory is automatically created by the framework with path format: {userData}/channel-data/{channelId}/

System Prompt Injection

If your platform has special message formats or capability tags, you can implement the getSystemPrompt() method:

getSystemPrompt(context: SystemPromptContext): string | undefined {
if (context.isGroup) {
return `You are in a Webhook group chat. Reply with plain text format.`;
}
return `You are having a Webhook direct chat with ${context.senderName}.`;
}

The returned text will be appended to the Agent's base system prompt, letting the AI understand the current platform context.

Next Steps