UNPKG

@grammyjs/auto-chat-action

Version:

A plugin for automatic sending a chat action

37 lines (36 loc) 1.46 kB
import { createCycleGenerator } from "./utils.js"; export function createChatActionsController(api) { const sendings = new Map(); const getSendingId = (chatId, threadId) => typeof threadId === "undefined" ? chatId.toString() : `${chatId}:${threadId}`; return { startSending(chatId, actions, messageThreadId, signal) { const chatActions = createCycleGenerator(actions); const sendChatAction = async () => { const action = chatActions.next().value; try { await api.sendChatAction(chatId, action, { ...(typeof messageThreadId !== "undefined" ? { message_thread_id: messageThreadId } : {}), }, signal); } catch { this.stopSending(chatId); } }; const sendingId = getSendingId(chatId, messageThreadId); if (sendings.has(sendingId)) { this.stopSending(chatId, messageThreadId); } sendings.set(sendingId, setInterval(sendChatAction, 5000)); sendChatAction(); }, stopSending(chatId, messageThreadId) { const sendingId = getSendingId(chatId, messageThreadId); clearInterval(sendings.get(sendingId)); sendings.delete(sendingId); }, }; }