feat(sdk): add media sends, quoted replies, and event waits
Add local media upload-and-send helpers with an optional Node file source and stage-aware errors. Add explicit quoted replies and cancellable event waits while preserving existing methods and handler contracts. Propagate group-file publication failures instead of reporting success. Cover cancellation, cleanup, signed message IDs, package exports, consumer types, and real HTTP/WebSocket upload-to-send integration. Validation: pnpm run ci (6231 tests passed, 9 skipped); SDK package contents verified with npm pack --dry-run --ignore-scripts.
This commit is contained in:
28 files changed
+1798
-37
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { createSnowLumaApiError, SnowLumaConnectionError } from '../errors.js';
|
||||
import { normalizeMessage } from '../messages/index.js';
|
||||
import { downloadFileStream, uploadFileStream } from './file-streams.js';
|
||||
import { sendUploadedMedia } from './media.js';
|
||||
import type {
|
||||
ActionParams,
|
||||
ActionResult,
|
||||
@@ -17,8 +18,14 @@ import type {
|
||||
GetMediaParams,
|
||||
JsonObject,
|
||||
JsonValue,
|
||||
MediaSource,
|
||||
OutgoingMessage,
|
||||
RequestOptions,
|
||||
SendFileOptions,
|
||||
SendGroupFileOptions,
|
||||
SendImageOptions,
|
||||
SendRecordOptions,
|
||||
SendVideoOptions,
|
||||
SendMsgParams,
|
||||
SetGroupReactionParams,
|
||||
SnowLumaAction,
|
||||
@@ -156,6 +163,132 @@ export abstract class SnowLumaApiClient {
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes, then sends an image message using the server's file path. */
|
||||
sendGroupImage(groupId: number, source: MediaSource, options: SendImageOptions = {}) {
|
||||
const { signal, timeoutMs, echo } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.sendGroupMessage(
|
||||
groupId,
|
||||
{ type: 'image', data: { ...options.image, file: upload.file_path } },
|
||||
{
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes, then sends a record message using the server's file path. */
|
||||
sendGroupRecord(groupId: number, source: MediaSource, options: SendRecordOptions = {}) {
|
||||
const { signal, timeoutMs, echo } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.sendGroupMessage(
|
||||
groupId,
|
||||
{ type: 'record', data: { ...options.record, file: upload.file_path } },
|
||||
{
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes, then sends a video message using the server's file path. */
|
||||
sendGroupVideo(groupId: number, source: MediaSource, options: SendVideoOptions = {}) {
|
||||
const { signal, timeoutMs, echo } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.sendGroupMessage(
|
||||
groupId,
|
||||
{ type: 'video', data: { ...options.video, file: upload.file_path } },
|
||||
{
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes, then sends an image message using the server's file path. */
|
||||
sendPrivateImage(userId: number, source: MediaSource, options: SendImageOptions = {}) {
|
||||
const { signal, timeoutMs, echo } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.sendPrivateMessage(
|
||||
userId,
|
||||
{ type: 'image', data: { ...options.image, file: upload.file_path } },
|
||||
{
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes, then sends a record message using the server's file path. */
|
||||
sendPrivateRecord(userId: number, source: MediaSource, options: SendRecordOptions = {}) {
|
||||
const { signal, timeoutMs, echo } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.sendPrivateMessage(
|
||||
userId,
|
||||
{ type: 'record', data: { ...options.record, file: upload.file_path } },
|
||||
{
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes, then sends a video message using the server's file path. */
|
||||
sendPrivateVideo(userId: number, source: MediaSource, options: SendVideoOptions = {}) {
|
||||
const { signal, timeoutMs, echo } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.sendPrivateMessage(
|
||||
userId,
|
||||
{ type: 'video', data: { ...options.video, file: upload.file_path } },
|
||||
{
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes and publishes a file in the group. */
|
||||
sendGroupFile(groupId: number, source: MediaSource, options: SendGroupFileOptions = {}) {
|
||||
const { signal, timeoutMs, echo, folder, folderId } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.uploadGroupFile(groupId, upload.file_path, {
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
folder,
|
||||
folderId,
|
||||
name: options.name ?? upload.file_name,
|
||||
uploadFile: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Uploads local bytes and sends the file to a private conversation. */
|
||||
sendPrivateFile(userId: number, source: MediaSource, options: SendFileOptions = {}) {
|
||||
const { signal, timeoutMs, echo } = options;
|
||||
return sendUploadedMedia(this, source, options, (upload) =>
|
||||
this.uploadPrivateFile(userId, upload.file_path, {
|
||||
signal,
|
||||
timeoutMs,
|
||||
echo,
|
||||
name: options.name ?? upload.file_name,
|
||||
uploadFile: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
getMessage(messageId: number, options?: RequestOptions) {
|
||||
return this.call('get_msg', { message_id: messageId }, options);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-clie
|
||||
|
||||
export type { SnowLumaHttpClientOptions } from './http-client.js';
|
||||
export type {
|
||||
EventWaitOptions,
|
||||
ReconnectOptions,
|
||||
SnowLumaWebSocketClientOptions,
|
||||
SnowLumaWebSocketEvents,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { SnowLumaMediaSendError } from '../errors.js';
|
||||
import { throwIfAborted } from '../internal/abort.js';
|
||||
import type {
|
||||
MediaSource,
|
||||
UploadFileStreamComplete,
|
||||
UploadFileStreamOptions,
|
||||
} from '../types/index.js';
|
||||
import type { SnowLumaApiClient } from './api-client.js';
|
||||
|
||||
/** Upload and send are separate operations; never retry a possibly completed send. */
|
||||
export async function sendUploadedMedia<TResult>(
|
||||
client: SnowLumaApiClient,
|
||||
input: MediaSource,
|
||||
options: UploadFileStreamOptions,
|
||||
send: (upload: UploadFileStreamComplete) => Promise<TResult>,
|
||||
): Promise<TResult> {
|
||||
let upload: UploadFileStreamComplete;
|
||||
|
||||
try {
|
||||
throwIfAborted(options.signal);
|
||||
|
||||
if (typeof input !== 'object' || input === null) {
|
||||
throw new TypeError('Media source must contain bytes; use localFile() for local paths');
|
||||
}
|
||||
|
||||
const source = 'source' in input ? input.source : input;
|
||||
const filename =
|
||||
'source' in input
|
||||
? input.filename
|
||||
: source instanceof Blob && 'name' in source && typeof source.name === 'string'
|
||||
? source.name
|
||||
: undefined;
|
||||
upload = await client.uploadFileStream(source, {
|
||||
...options,
|
||||
filename: options.filename ?? filename,
|
||||
});
|
||||
} catch (cause) {
|
||||
throw new SnowLumaMediaSendError('upload', cause);
|
||||
}
|
||||
|
||||
try {
|
||||
// Cancellation can arrive with the final upload ACK, before dispatching the send.
|
||||
throwIfAborted(options.signal);
|
||||
return await send(upload);
|
||||
} catch (cause) {
|
||||
throw new SnowLumaMediaSendError('send', cause, upload);
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,12 @@ import {
|
||||
matchCommand,
|
||||
noticeType,
|
||||
requestType,
|
||||
type CommandHandler,
|
||||
type CommandHandler as BaseCommandHandler,
|
||||
type CommandOptions,
|
||||
type EventHandler,
|
||||
type EventMiddleware,
|
||||
type EventHandler as BaseEventHandler,
|
||||
type EventMiddleware as BaseEventMiddleware,
|
||||
type EventPredicate,
|
||||
type SnowLumaEventContextWithQuote,
|
||||
} from '../events/index.js';
|
||||
import { SnowLumaApiClient, toJsonObject } from './api-client.js';
|
||||
import { createRequestAbortState, raceWithAbort, throwIfAborted } from '../internal/abort.js';
|
||||
@@ -68,6 +69,7 @@ import type {
|
||||
WsRole,
|
||||
} from '../types/index.js';
|
||||
import type {
|
||||
EventWaitOptions,
|
||||
ReconnectOptions,
|
||||
SnowLumaWebSocketClientOptions,
|
||||
SnowLumaWebSocketEvents,
|
||||
@@ -76,6 +78,7 @@ import type {
|
||||
} from './websocket-types.js';
|
||||
|
||||
export type {
|
||||
EventWaitOptions,
|
||||
ReconnectOptions,
|
||||
SnowLumaWebSocketClientOptions,
|
||||
SnowLumaWebSocketEvents,
|
||||
@@ -95,6 +98,16 @@ interface PendingRequest {
|
||||
reject(error: Error): void;
|
||||
}
|
||||
|
||||
type EventHandler<TEvent extends SnowLumaEvent = SnowLumaEvent> = BaseEventHandler<
|
||||
TEvent,
|
||||
SnowLumaEventContextWithQuote<TEvent>
|
||||
>;
|
||||
type EventMiddleware = BaseEventMiddleware<SnowLumaEventContextWithQuote>;
|
||||
type CommandHandler = BaseCommandHandler<
|
||||
OneBotMessageEvent,
|
||||
SnowLumaEventContextWithQuote<OneBotMessageEvent>
|
||||
>;
|
||||
|
||||
/** OneBot WebSocket client for SnowLuma APIs and realtime events. */
|
||||
export class SnowLumaWebSocketClient extends SnowLumaApiClient {
|
||||
readonly url: string;
|
||||
@@ -107,6 +120,7 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
|
||||
private readonly reconnect: ReconnectOptions | null;
|
||||
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
|
||||
private readonly pending = new Map<string, PendingRequest>();
|
||||
private readonly eventWaits = new Set<(error: Error) => void>();
|
||||
private readonly middlewares: EventMiddleware[] = [];
|
||||
private connection: SocketConnection | null = null;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -163,6 +177,129 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
|
||||
return this.on('event', listener);
|
||||
}
|
||||
|
||||
/** Waits for a future public event after middleware, without connecting or replaying events. */
|
||||
waitForEvent<TEvent extends SnowLumaEvent>(
|
||||
predicate: EventPredicate<TEvent>,
|
||||
options?: EventWaitOptions,
|
||||
): Promise<TEvent>;
|
||||
waitForEvent(
|
||||
predicate: ((event: SnowLumaEvent) => boolean) | undefined,
|
||||
options?: EventWaitOptions,
|
||||
): Promise<SnowLumaEvent>;
|
||||
waitForEvent(options?: EventWaitOptions): Promise<SnowLumaEvent>;
|
||||
waitForEvent(
|
||||
predicateOrOptions?: ((event: SnowLumaEvent) => boolean) | EventWaitOptions,
|
||||
requestedOptions?: EventWaitOptions,
|
||||
): Promise<SnowLumaEvent> {
|
||||
const predicate = typeof predicateOrOptions === 'function' ? predicateOrOptions : undefined;
|
||||
const options =
|
||||
typeof predicateOrOptions === 'function'
|
||||
? requestedOptions
|
||||
: (predicateOrOptions ?? requestedOptions);
|
||||
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
throwIfAborted(options?.signal, 'SnowLuma event wait aborted');
|
||||
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) {
|
||||
throw new RangeError('Event wait timeoutMs must be between 0 and 2147483647');
|
||||
}
|
||||
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const cleanup = (): void => {
|
||||
off();
|
||||
this.eventWaits.delete(fail);
|
||||
clearTimeout(timer);
|
||||
options?.signal?.removeEventListener('abort', onAbort);
|
||||
};
|
||||
|
||||
const fail = (error: unknown): void => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
cleanup();
|
||||
reject(error);
|
||||
};
|
||||
|
||||
const onAbort = (): void => {
|
||||
fail(
|
||||
new SnowLumaAbortError('SnowLuma event wait aborted', {
|
||||
cause: options?.signal?.reason,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const off = this.onEvent((event) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const matched = predicate ? predicate(event) : true;
|
||||
|
||||
if (typeof matched !== 'boolean') {
|
||||
throw new TypeError(
|
||||
'Event wait predicates must return a boolean synchronously',
|
||||
);
|
||||
}
|
||||
|
||||
if (matched && !settled) {
|
||||
settled = true;
|
||||
cleanup();
|
||||
resolve(event);
|
||||
}
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
}
|
||||
});
|
||||
|
||||
this.eventWaits.add(fail);
|
||||
options?.signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
if (timeoutMs > 0) {
|
||||
timer = setTimeout(() => {
|
||||
fail(
|
||||
new SnowLumaTimeoutError(
|
||||
`SnowLuma event wait timed out after ${timeoutMs}ms`,
|
||||
timeoutMs,
|
||||
),
|
||||
);
|
||||
}, timeoutMs);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Waits for a future message or message_sent event that passes the optional predicate. */
|
||||
waitForMessage<TEvent extends OneBotMessageEvent>(
|
||||
predicate: (event: OneBotMessageEvent) => event is TEvent,
|
||||
options?: EventWaitOptions,
|
||||
): Promise<TEvent>;
|
||||
waitForMessage(
|
||||
predicate: ((event: OneBotMessageEvent) => boolean) | undefined,
|
||||
options?: EventWaitOptions,
|
||||
): Promise<OneBotMessageEvent>;
|
||||
waitForMessage(options?: EventWaitOptions): Promise<OneBotMessageEvent>;
|
||||
waitForMessage(
|
||||
predicateOrOptions?: ((event: OneBotMessageEvent) => boolean) | EventWaitOptions,
|
||||
requestedOptions?: EventWaitOptions,
|
||||
): Promise<OneBotMessageEvent> {
|
||||
const predicate = typeof predicateOrOptions === 'function' ? predicateOrOptions : undefined;
|
||||
const options =
|
||||
typeof predicateOrOptions === 'function'
|
||||
? requestedOptions
|
||||
: (predicateOrOptions ?? requestedOptions);
|
||||
|
||||
return this.waitForEvent(
|
||||
(event): event is OneBotMessageEvent =>
|
||||
isMessageEvent(event) && (predicate ? predicate(event) : true),
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/** Adds event middleware to the dispatch pipeline. */
|
||||
use(middleware: EventMiddleware): () => void {
|
||||
this.middlewares.push(middleware);
|
||||
@@ -341,6 +478,7 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
|
||||
this.connection = null;
|
||||
connection?.dispose(error);
|
||||
this.rejectPending(error);
|
||||
this.rejectEventWaits(error);
|
||||
|
||||
if (connection && connection.socket.readyState !== WEBSOCKET_CLOSED) {
|
||||
const off = addSocketListener(connection.socket, 'close', (...args) => {
|
||||
@@ -642,7 +780,9 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
|
||||
|
||||
private handleClose(args: unknown[]): void {
|
||||
const info = closeInfo(args);
|
||||
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
|
||||
const error = new SnowLumaConnectionError('SnowLuma WebSocket closed');
|
||||
this.rejectPending(error);
|
||||
this.rejectEventWaits(error);
|
||||
this.emitter.emit('close', info);
|
||||
|
||||
if (!this.closedByUser && this.reconnect) {
|
||||
@@ -688,6 +828,12 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
|
||||
pending.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
private rejectEventWaits(error: Error): void {
|
||||
for (const fail of this.eventWaits) {
|
||||
fail(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createWebSocketClient(
|
||||
|
||||
@@ -40,6 +40,14 @@ export interface SnowLumaWebSocketClientOptions extends SnowLumaClientOptions {
|
||||
reconnect?: boolean | ReconnectOptions;
|
||||
}
|
||||
|
||||
/** Controls one wait for a future event, without opening a connection. */
|
||||
export interface EventWaitOptions {
|
||||
/** Defaults to the client's requestTimeoutMs. Set to 0 to wait without a deadline. */
|
||||
timeoutMs?: number;
|
||||
/** Cancels the wait without closing the connection. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface WebSocketCloseInfo {
|
||||
code?: number;
|
||||
reason?: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApiResponse } from './types/index.js';
|
||||
import type { ApiResponse, UploadFileStreamComplete } from './types/index.js';
|
||||
|
||||
/** Base error for every exception intentionally thrown by the SnowLuma SDK. */
|
||||
export class SnowLumaError extends Error {
|
||||
@@ -8,6 +8,22 @@ export class SnowLumaError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** A one-step media operation failed. The original error is preserved as cause. */
|
||||
export class SnowLumaMediaSendError extends SnowLumaError {
|
||||
readonly stage: 'upload' | 'send';
|
||||
/** Present after a completed upload, even when sending fails or is cancelled. */
|
||||
readonly upload?: UploadFileStreamComplete;
|
||||
|
||||
constructor(stage: 'upload' | 'send', cause: unknown, upload?: UploadFileStreamComplete) {
|
||||
super(`Media ${stage} failed${cause instanceof Error ? `: ${cause.message}` : ''}`, {
|
||||
cause,
|
||||
});
|
||||
this.name = 'SnowLumaMediaSendError';
|
||||
this.stage = stage;
|
||||
this.upload = upload;
|
||||
}
|
||||
}
|
||||
|
||||
/** Transport-layer failures before a valid OneBot API response is available. */
|
||||
export class SnowLumaTransportError extends SnowLumaError {
|
||||
constructor(message: string, options?: ErrorOptions) {
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import type { SnowLumaApiClient } from '../client/api-client.js';
|
||||
import type { SnowLumaEvent } from '../types/index.js';
|
||||
import { quoteMessage } from '../messages/quote.js';
|
||||
import { isGroupMessageEvent, isPrivateMessageEvent, isRequestEvent } from './guards.js';
|
||||
import type { SnowLumaEventContext } from './types.js';
|
||||
import type { SnowLumaEventContextWithQuote } from './types.js';
|
||||
|
||||
export function createEventContext<TEvent extends SnowLumaEvent>(
|
||||
event: TEvent,
|
||||
client: SnowLumaApiClient,
|
||||
): SnowLumaEventContext<TEvent> {
|
||||
): SnowLumaEventContextWithQuote<TEvent> {
|
||||
let stopped = false;
|
||||
|
||||
const context: SnowLumaEventContext<TEvent> = {
|
||||
const context: SnowLumaEventContextWithQuote<TEvent> = {
|
||||
event,
|
||||
client,
|
||||
get stopped() {
|
||||
@@ -29,6 +30,25 @@ export function createEventContext<TEvent extends SnowLumaEvent>(
|
||||
|
||||
throw new Error('reply() is only available for message events');
|
||||
},
|
||||
async quote(message, options) {
|
||||
if (isGroupMessageEvent(event)) {
|
||||
return client.sendGroupMessage(
|
||||
event.group_id,
|
||||
quoteMessage(event.message_id, message, options),
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
if (isPrivateMessageEvent(event)) {
|
||||
return client.sendPrivateMessage(
|
||||
event.user_id,
|
||||
quoteMessage(event.message_id, message, options),
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error('quote() is only available for message events');
|
||||
},
|
||||
async approve(options) {
|
||||
if (!isRequestEvent(event)) {
|
||||
throw new Error('approve() is only available for request events');
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
OneBotMessageEvent,
|
||||
OutgoingMessage,
|
||||
RequestOptions,
|
||||
SendMessageResult,
|
||||
SnowLumaEvent,
|
||||
} from '../types/index.js';
|
||||
|
||||
@@ -14,14 +15,14 @@ export type EventPredicate<TEvent extends SnowLumaEvent = SnowLumaEvent> = (
|
||||
event: SnowLumaEvent,
|
||||
) => event is TEvent;
|
||||
|
||||
export type EventHandler<TEvent extends SnowLumaEvent = SnowLumaEvent> = (
|
||||
event: TEvent,
|
||||
context: SnowLumaEventContext<TEvent>,
|
||||
) => MaybePromise;
|
||||
export type EventHandler<
|
||||
TEvent extends SnowLumaEvent = SnowLumaEvent,
|
||||
TContext extends SnowLumaEventContext<TEvent> = SnowLumaEventContext<TEvent>,
|
||||
> = (event: TEvent, context: TContext) => MaybePromise;
|
||||
|
||||
export type EventMiddleware = (
|
||||
export type EventMiddleware<TContext extends SnowLumaEventContext = SnowLumaEventContext> = (
|
||||
event: SnowLumaEvent,
|
||||
context: SnowLumaEventContext,
|
||||
context: TContext,
|
||||
next: EventNext,
|
||||
) => MaybePromise;
|
||||
|
||||
@@ -44,6 +45,17 @@ export interface SnowLumaEventContext<TEvent extends SnowLumaEvent = SnowLumaEve
|
||||
quickOperation(operation: JsonObject, options?: RequestOptions): Promise<unknown>;
|
||||
}
|
||||
|
||||
/** Contexts supplied by the SDK include explicit quoted replies. */
|
||||
export interface SnowLumaEventContextWithQuote<
|
||||
TEvent extends SnowLumaEvent = SnowLumaEvent,
|
||||
> extends SnowLumaEventContext<TEvent> {
|
||||
/** Quotes this message and sends the body to the same group or private conversation. */
|
||||
quote(
|
||||
message: OutgoingMessage,
|
||||
options?: RequestOptions & { autoEscape?: boolean },
|
||||
): Promise<SendMessageResult>;
|
||||
}
|
||||
|
||||
export interface CommandOptions {
|
||||
prefixes?: string | string[];
|
||||
trim?: boolean;
|
||||
@@ -59,8 +71,11 @@ export interface CommandMatch {
|
||||
match: RegExpMatchArray | null;
|
||||
}
|
||||
|
||||
export type CommandHandler<TEvent extends OneBotMessageEvent = OneBotMessageEvent> = (
|
||||
export type CommandHandler<
|
||||
TEvent extends OneBotMessageEvent = OneBotMessageEvent,
|
||||
TContext extends SnowLumaEventContext<TEvent> = SnowLumaEventContext<TEvent>,
|
||||
> = (
|
||||
event: TEvent,
|
||||
context: SnowLumaEventContext<TEvent> & { command: CommandMatch },
|
||||
context: TContext & { command: CommandMatch },
|
||||
match: CommandMatch,
|
||||
) => MaybePromise;
|
||||
@@ -11,6 +11,7 @@ export {
|
||||
SnowLumaAuthError,
|
||||
SnowLumaConnectionError,
|
||||
SnowLumaError,
|
||||
SnowLumaMediaSendError,
|
||||
SnowLumaParseError,
|
||||
SnowLumaTimeoutError,
|
||||
SnowLumaTransportError,
|
||||
@@ -49,6 +50,7 @@ export {
|
||||
normalizeMessage,
|
||||
parseSegments,
|
||||
poke,
|
||||
quoteMessage,
|
||||
raw,
|
||||
record,
|
||||
reply,
|
||||
@@ -60,6 +62,7 @@ export {
|
||||
} from './messages/index.js';
|
||||
|
||||
export type {
|
||||
EventWaitOptions,
|
||||
ReconnectOptions,
|
||||
SnowLumaWebSocketClientOptions,
|
||||
SnowLumaWebSocketEvents,
|
||||
@@ -78,6 +81,7 @@ export type {
|
||||
MaybePromise,
|
||||
RequestDecisionOptions,
|
||||
SnowLumaEventContext,
|
||||
SnowLumaEventContextWithQuote,
|
||||
} from './events/index.js';
|
||||
|
||||
export type * from './types/index.js';
|
||||
@@ -26,6 +26,7 @@ export {
|
||||
} from './chain.js';
|
||||
export { escapeCqParam, escapeCqText } from './cq-format.js';
|
||||
export { fromCQString, parseSegments, toCQString } from './cq.js';
|
||||
export { quoteMessage } from './quote.js';
|
||||
export { segments };
|
||||
|
||||
export const message = {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { AnyMessageSegment, OutgoingMessage } from '../types/index.js';
|
||||
import { normalizeMessage } from './chain.js';
|
||||
import { parseSegments } from './cq.js';
|
||||
import { segments } from './segments.js';
|
||||
|
||||
/** Adds an existing message's ID as the quote without changing the supplied body. */
|
||||
export function quoteMessage(
|
||||
messageId: number,
|
||||
message: OutgoingMessage,
|
||||
options: { autoEscape?: boolean } = {},
|
||||
): string | AnyMessageSegment[] {
|
||||
if (
|
||||
!Number.isInteger(messageId) ||
|
||||
messageId === 0 ||
|
||||
messageId < -2147483648 ||
|
||||
messageId > 2147483647
|
||||
) {
|
||||
throw new TypeError('quoteMessage() requires a non-zero signed 32-bit message ID');
|
||||
}
|
||||
|
||||
const normalized = normalizeMessage(message);
|
||||
const quote = segments.reply(messageId);
|
||||
|
||||
if (typeof normalized === 'string') {
|
||||
if (options.autoEscape) {
|
||||
return [quote, segments.text(normalized)];
|
||||
}
|
||||
|
||||
assertNoReply(parseSegments(normalized));
|
||||
// Keep the original CQ body so extension fields are not lost in conversion.
|
||||
return `[CQ:reply,id=${messageId}]${normalized}`;
|
||||
}
|
||||
|
||||
assertNoReply(normalized);
|
||||
return [quote, ...normalized];
|
||||
}
|
||||
|
||||
function assertNoReply(message: AnyMessageSegment[]): void {
|
||||
if (message.some((segment) => segment.type === 'reply')) {
|
||||
throw new TypeError('quoteMessage() cannot add a quote to a message containing a reply');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { openAsBlob } from 'node:fs';
|
||||
import { stat } from 'node:fs/promises';
|
||||
import { basename, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import type { NamedMediaSource } from '../types/index.js';
|
||||
|
||||
/** Opens a file-backed source without buffering the entire file in memory.
|
||||
* Keep the file unchanged until the send finishes; read failures are propagated. */
|
||||
export async function localFile(path: string | URL): Promise<NamedMediaSource> {
|
||||
const absolutePath = path instanceof URL ? fileURLToPath(path) : resolve(path);
|
||||
const info = await stat(absolutePath);
|
||||
|
||||
if (!info.isFile()) {
|
||||
throw new TypeError('localFile() requires a regular file');
|
||||
}
|
||||
|
||||
return { source: await openAsBlob(absolutePath), filename: basename(absolutePath) };
|
||||
}
|
||||
@@ -5,3 +5,4 @@ export * from './params.js';
|
||||
export * from './actions.js';
|
||||
export * from './events.js';
|
||||
export * from './streaming.js';
|
||||
export * from './media.js';
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { ImageSegment, RecordSegment, VideoSegment } from './messages.js';
|
||||
import type { UploadFileSource, UploadFileStreamOptions } from './streaming.js';
|
||||
|
||||
/** A byte source with a filename, including files opened by @snowluma/sdk/node. */
|
||||
export interface NamedMediaSource {
|
||||
readonly source: UploadFileSource;
|
||||
readonly filename: string;
|
||||
}
|
||||
|
||||
/** Strings are deliberately excluded: existing string paths refer to the server. */
|
||||
export type MediaSource = UploadFileSource | NamedMediaSource;
|
||||
|
||||
export interface SendImageOptions extends UploadFileStreamOptions {
|
||||
image?: Omit<ImageSegment['data'], 'file'>;
|
||||
}
|
||||
|
||||
export interface SendRecordOptions extends UploadFileStreamOptions {
|
||||
record?: Omit<RecordSegment['data'], 'file'>;
|
||||
}
|
||||
|
||||
export interface SendVideoOptions extends UploadFileStreamOptions {
|
||||
/** A thumbnail path, if supplied, still refers to the server. */
|
||||
video?: Omit<VideoSegment['data'], 'file'>;
|
||||
}
|
||||
|
||||
export interface SendFileOptions extends UploadFileStreamOptions {
|
||||
/** Display name in QQ; defaults to the uploaded file's name. */
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface SendGroupFileOptions extends SendFileOptions {
|
||||
folder?: string;
|
||||
folderId?: string;
|
||||
}
|
||||
Reference in new issue
Block a user