@grammyjs/auto-chat-action
Version:
A plugin for automatic sending a chat action
74 lines (73 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.chatAction = exports.autoChatAction = void 0;
const chat_actions_controller_js_1 = require("./chat-actions-controller.js");
const extract_chat_actions_js_1 = require("./extract-chat-actions.js");
function autoChatAction(api) {
return async (ctx, next) => {
const isPluginInstalled = Object.hasOwn(ctx, "chatAction");
if (isPluginInstalled) {
return next();
}
const chatActionsController = (0, chat_actions_controller_js_1.createChatActionsController)(api ?? ctx.api);
ctx.api.config.use(async (prev, method, payload, signal) => {
if (!("chat_id" in payload) ||
typeof payload.chat_id === "undefined") {
return prev(method, payload, signal);
}
const [hasActions, actions] = (0, extract_chat_actions_js_1.getChatActionsForRequest)(method, payload);
if (!hasActions) {
return prev(method, payload, signal);
}
const messageThreadId = "message_thread_id" in payload
? payload.message_thread_id
: undefined;
chatActionsController.startSending(payload.chat_id, actions, messageThreadId, signal);
try {
return await prev(method, payload, signal);
}
finally {
chatActionsController.stopSending(payload.chat_id, messageThreadId);
currentAction = null;
}
});
let currentAction = null;
Object.defineProperty(ctx, "chatAction", {
get() {
return currentAction;
},
set(newAction) {
if (typeof ctx.chat?.id === "undefined") {
return;
}
currentAction = newAction;
if (typeof currentAction !== "string") {
chatActionsController.stopSending(ctx.chat.id, ctx.msg?.message_thread_id);
}
else {
chatActionsController.startSending(ctx.chat.id, [currentAction], ctx.msg?.message_thread_id);
}
},
});
try {
await next();
}
finally {
if (typeof ctx.chat?.id === "number") {
chatActionsController.stopSending(ctx.chat.id, ctx.msg?.message_thread_id);
}
}
};
}
exports.autoChatAction = autoChatAction;
function chatAction(action) {
return (ctx, next) => {
const isPluginNotInstalled = Object.hasOwn(ctx, "chatAction") === false;
if (isPluginNotInstalled) {
throw new Error("Please first install the auto-chat-action plugin to set a chat action.");
}
ctx.chatAction = action;
return next();
};
}
exports.chatAction = chatAction;