46 lines
1.9 KiB
TypeScript
46 lines
1.9 KiB
TypeScript
|
|
import { IContent, MatrixClient, Method } from 'matrix-js-sdk';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Schedule a message via MSC4140 (delayed messages).
|
||
|
|
* @param mx - Matrix client instance
|
||
|
|
* @param roomId - The room to send the message in
|
||
|
|
* @param content - The message event content
|
||
|
|
* @param sendAtMs - Unix timestamp (ms) when the message should be sent
|
||
|
|
* @returns The delay_id returned by the server (use to cancel/restart)
|
||
|
|
*/
|
||
|
|
export async function scheduleMessage(
|
||
|
|
mx: MatrixClient,
|
||
|
|
roomId: string,
|
||
|
|
content: IContent,
|
||
|
|
sendAtMs: number,
|
||
|
|
): Promise<string> {
|
||
|
|
const delayMs = sendAtMs - Date.now();
|
||
|
|
const txnId = `sched_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
||
|
|
const path = `/_matrix/client/unstable/org.matrix.msc4140/rooms/${encodeURIComponent(roomId)}/send/m.room.message/${txnId}?delay=${Math.max(1000, Math.round(delayMs))}`;
|
||
|
|
const res = (await mx.http.authedRequest(Method.Put, path, undefined, content, {
|
||
|
|
prefix: '',
|
||
|
|
})) as { delay_id: string };
|
||
|
|
return res.delay_id;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Cancel a scheduled message via MSC4140.
|
||
|
|
* @param mx - Matrix client instance
|
||
|
|
* @param delayId - The delay_id from scheduleMessage
|
||
|
|
*/
|
||
|
|
export async function cancelScheduledMessage(mx: MatrixClient, delayId: string): Promise<void> {
|
||
|
|
const path = `/_matrix/client/unstable/org.matrix.msc4140/delayed_events/${encodeURIComponent(delayId)}`;
|
||
|
|
await mx.http.authedRequest(Method.Post, path, undefined, { action: 'cancel' }, { prefix: '' });
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Restart (refresh heartbeat) a scheduled message via MSC4140.
|
||
|
|
* Resets the delay timer from now.
|
||
|
|
* @param mx - Matrix client instance
|
||
|
|
* @param delayId - The delay_id from scheduleMessage
|
||
|
|
*/
|
||
|
|
export async function restartScheduledMessage(mx: MatrixClient, delayId: string): Promise<void> {
|
||
|
|
const path = `/_matrix/client/unstable/org.matrix.msc4140/delayed_events/${encodeURIComponent(delayId)}`;
|
||
|
|
await mx.http.authedRequest(Method.Post, path, undefined, { action: 'restart' }, { prefix: '' });
|
||
|
|
}
|