Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): send media through ctx.conversations.send (#605)
Yudhi Armyndharis030520a9437b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 419309d47..d7b67c212 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Plugins can send media through `ctx.conversations.send`.** The conversation-send capability now accepts `image`, `video`, `audio`, and `file` envelopes that carry a `mediaUrl`, sending them by URL through the same media pipeline as the REST media endpoints (the caption comes from `text`). It stays under the existing `conversation:send` permission and the plugin's activated-session scope — the text/reply behavior is unchanged. A `replyTo` on a media envelope is rejected, since the engine media path cannot quote a message.- **Official Java SDK (`com.rmyndharis:openwa`).** A hand-written, synchronous Java 17 client covering the full REST surface — all 12 resources (sessions, messages, contacts, groups, webhooks, chats, labels, channels, catalog, status, templates, health) plus API-key validation — with typed request builders, immutable response records, a typed error hierarchy, and an injectable HTTP transport for testing. One runtime dependency (Gson); published to Maven Central as `com.rmyndharis:openwa:0.1.1`. Lives in `sdk/java` and is drift-tested against the backend DTOs like the JavaScript, Python, and PHP SDKs. (#602)## [0.8.1] - 2026-07-02diff --git a/src/core/plugins/conversation-send-facade.spec.ts b/src/core/plugins/conversation-send-facade.spec.tsindex 0c45d1131..d7ca62dac 100644--- a/src/core/plugins/conversation-send-facade.spec.ts+++ b/src/core/plugins/conversation-send-facade.spec.ts@@ -59,4 +59,71 @@ describe('conversation.send facade', () => {expect(runGuarded).toHaveBeenCalled();expect(res).toEqual({ id: 'm1' });});++ it('routes a media envelope to sendMedia with the caption from text, not sendText', async () => {+ const sendMedia = jest.fn().mockResolvedValue({ id: 'm2' });+ const sendText = jest.fn();+ const facade = buildConversationSendFacade({+ manifest: manifest(['conversation:send']) as never,+ assertPermission: () => undefined,+ assertSessionActive: jest.fn(),+ resolveChatId: () => Promise.resolve('[email protected]'),+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),+ sendText,+ reply: jest.fn(),+ sendMedia,+ } as never);+ const res = await facade.send({+ type: 'image',+ mediaUrl: 'https://cdn.example/x.jpg',+ text: 'a caption',+ sessionId: 's',+ chatId: '[email protected]',+ });+ expect(sendMedia).toHaveBeenCalledWith('s', {+ chatId: '[email protected]',+ url: 'https://cdn.example/x.jpg',+ type: 'image',+ caption: 'a caption',+ });+ expect(sendText).not.toHaveBeenCalled();+ expect(res).toEqual({ id: 'm2' });+ });++ it('rejects replyTo on a media envelope — media-reply is unsupported by the engine', async () => {+ const sendMedia = jest.fn();+ const facade = buildConversationSendFacade({+ manifest: manifest(['conversation:send']) as never,+ assertPermission: () => undefined,+ assertSessionActive: jest.fn(),+ resolveChatId: () => Promise.resolve('[email protected]'),+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),+ sendText: jest.fn(),+ reply: jest.fn(),+ sendMedia,+ } as never);+ await expect(+ facade.send({ type: 'image', mediaUrl: 'https://cdn.example/x.jpg', replyTo: 'Q1', sessionId: 's', chatId: 'c' }),+ ).rejects.toThrow(PluginCapabilityError);+ expect(sendMedia).not.toHaveBeenCalled();+ });++ it('falls back to a text send when a media type carries no mediaUrl (URL-in-text fallback)', async () => {+ const sendMedia = jest.fn();+ const sendText = jest.fn().mockResolvedValue({ id: 't1' });+ const facade = buildConversationSendFacade({+ manifest: manifest(['conversation:send']) as never,+ assertPermission: () => undefined,+ assertSessionActive: jest.fn(),+ resolveChatId: () => Promise.resolve('[email protected]'),+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),+ sendText,+ reply: jest.fn(),+ sendMedia,+ } as never);+ const res = await facade.send({ type: 'video', text: 'https://cdn.example/v.mp4', sessionId: 's', chatId: 'c' });+ expect(sendMedia).not.toHaveBeenCalled();+ expect(sendText).toHaveBeenCalledWith('s', { chatId: 'c', text: 'https://cdn.example/v.mp4' });+ expect(res).toEqual({ id: 't1' });+ });});diff --git a/src/core/plugins/conversation-send-facade.ts b/src/core/plugins/conversation-send-facade.tsindex 6d3386e75..b2f8b97dd 100644--- a/src/core/plugins/conversation-send-facade.ts+++ b/src/core/plugins/conversation-send-facade.ts@@ -20,8 +20,22 @@ export interface ConversationSendDeps {runGuarded: <T>(events: string[], run: () => Promise<T>) => Promise<T>;sendText: (sessionId: string, opts: { chatId: string; text: string }) => Promise<unknown>;reply: (sessionId: string, opts: { chatId: string; quotedMessageId: string; text: string }) => Promise<unknown>;+ // Media send by URL. The loader binds this to the per-type MessageService media methods+ // (sendImage/sendVideo/sendAudio/sendDocument) — the facade stays DTO-agnostic.+ sendMedia: (+ sessionId: string,+ opts: { chatId: string; url: string; type: ConversationMediaType; caption?: string },+ ) => Promise<unknown>;}+/** Envelope types carried as media by URL. `location` is a non-text type but has no mediaUrl, so it is excluded. */+export type ConversationMediaType = 'image' | 'file' | 'audio' | 'video';++const MEDIA_TYPES: readonly ConversationMediaType[] = ['image', 'file', 'audio', 'video'];++const isMediaType = (type: ConversationSendEnvelope['type']): type is ConversationMediaType =>+ (MEDIA_TYPES as readonly string[]).includes(type);+const MESSAGE_HOOK_EVENTS = ['message:sending'];export function buildConversationSendFacade(deps: ConversationSendDeps) {@@ -32,8 +46,18 @@ export function buildConversationSendFacade(deps: ConversationSendDeps) {if (!sessionId) throw new PluginCapabilityError('conversation.send: sessionId is required');deps.assertSessionActive(sessionId);const chatId = env.chatId ?? (await deps.resolveChatId(env));- // Only text/reply are wired in P0; media types are additive in a later minor.return deps.runGuarded(MESSAGE_HOOK_EVENTS, async () => {+ // A media type carrying a mediaUrl is sent as native media. A media type WITHOUT a mediaUrl has+ // nothing to send as media, so it falls through to the text/reply path — a plugin that puts the+ // URL in `text` as a fallback still delivers a (text) message rather than erroring.+ if (isMediaType(env.type) && env.mediaUrl) {+ // The engine media path takes only (chatId, media) — it cannot quote a message, so a media+ // reply is not expressible. Reject rather than silently drop the quote.+ if (env.replyTo) {+ throw new PluginCapabilityError('conversation.send: replyTo is not supported for media messages');+ }+ return deps.sendMedia(sessionId, { chatId, url: env.mediaUrl, type: env.type, caption: env.text });+ }if (env.replyTo) {return deps.reply(sessionId, { chatId, quotedMessageId: env.replyTo, text: env.text ?? '' });}diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex 5b7fa1913..38f8bedbc 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -1,5 +1,5 @@import * as path from 'path';-import { resolvePluginMainPath, buildSandboxWorkerEnv } from './plugin-loader.service';+import { resolvePluginMainPath, buildSandboxWorkerEnv, dispatchConversationMedia } from './plugin-loader.service';/** Regression lock: a plugin's manifest.main must not escape its plugin directory. */describe('resolvePluginMainPath', () => {@@ -68,6 +68,37 @@ describe('buildSandboxWorkerEnv', () => {});});+/** conversation.send media types must route to the matching MessageService method (not a copy-paste sibling). */+describe('dispatchConversationMedia', () => {+ const svc = () => ({+ sendImage: jest.fn().mockResolvedValue({ messageId: 'i' }),+ sendVideo: jest.fn().mockResolvedValue({ messageId: 'v' }),+ sendAudio: jest.fn().mockResolvedValue({ messageId: 'a' }),+ sendDocument: jest.fn().mockResolvedValue({ messageId: 'd' }),+ });+ const opts = (type: 'image' | 'video' | 'audio' | 'file') => ({+ chatId: '[email protected]',+ url: 'https://cdn.example/m',+ caption: 'cap',+ type,+ });++ it.each([+ ['image', 'sendImage'],+ ['video', 'sendVideo'],+ ['audio', 'sendAudio'],+ ['file', 'sendDocument'],+ ] as const)('routes %s to %s with a url+caption DTO', async (type, method) => {+ const s = svc();+ await dispatchConversationMedia(s, 's', opts(type));+ expect(s[method]).toHaveBeenCalledWith('s', { chatId: '[email protected]', url: 'https://cdn.example/m', caption: 'cap' });+ // No sibling method is invoked for the wrong type.+ for (const other of ['sendImage', 'sendVideo', 'sendAudio', 'sendDocument'] as const) {+ if (other !== method) expect(s[other]).not.toHaveBeenCalled();+ }+ });+});+import * as fs from 'fs';import * as os from 'os';import { PluginLoaderService } from './plugin-loader.service';diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex e625ce711..57822c983 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -31,7 +31,7 @@ import { PluginWorkerHost } from './sandbox/plugin-worker-host';import { WorkerThreadChannel } from './sandbox/worker-thread-channel';import { dispatchCapabilityVerb } from './sandbox/capability-router';import { PluginLogLevel } from './sandbox/protocol';-import { buildConversationSendFacade } from './conversation-send-facade';+import { buildConversationSendFacade, ConversationMediaType } from './conversation-send-facade';import { shouldDispatchToPlugin } from './handover-gate';import { makeOnWebhookSubscribe } from './webhook-subscribe.util';import { INGRESS_DISPATCH_TIMEOUT_MS } from '../../modules/integration/integration.constants';@@ -97,6 +97,30 @@ export function buildSandboxWorkerEnv(source: NodeJS.ProcessEnv = process.env):return env;}+/**+ * Translate a normalized conversation media send into the concrete MessageService media method for the+ * envelope's type. Kept pure (no `this`) so the loader binds it directly and it can be unit-tested in+ * isolation. The switch is exhaustive over ConversationMediaType — adding a type without a case is a+ * compile error here rather than a silent runtime fall-through.+ */+export function dispatchConversationMedia(+ svc: Pick<MessageService, 'sendImage' | 'sendVideo' | 'sendAudio' | 'sendDocument'>,+ sessionId: string,+ opts: { chatId: string; url: string; type: ConversationMediaType; caption?: string },+): Promise<unknown> {+ const dto = { chatId: opts.chatId, url: opts.url, caption: opts.caption };+ switch (opts.type) {+ case 'image':+ return svc.sendImage(sessionId, dto);+ case 'video':+ return svc.sendVideo(sessionId, dto);+ case 'audio':+ return svc.sendAudio(sessionId, dto);+ case 'file':+ return svc.sendDocument(sessionId, dto);+ }+}+@Injectable()export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {private readonly logger = createLogger('PluginLoaderService');@@ -1043,6 +1067,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {: run(),sendText: (sessionId, opts) => this.getMessageService().sendText(sessionId, opts),reply: (sessionId, opts) => this.getMessageService().reply(sessionId, opts),+ sendMedia: (sessionId, opts) => dispatchConversationMedia(this.getMessageService(), sessionId, opts),} satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability,handover: {set: async (key, state) => {