telegram-mcp/cli/src/commands/message/poll.ts
2026-11-05 14:26:28 +03:00

165 lines
5.6 KiB
TypeScript

import type { Command } from 'commander';
import { Api } from 'teleproto';
import bigInt from 'big-integer';
import { generateRandomLong } from 'teleproto/Helpers.js';
import { outputSuccess, outputError } from '../../lib/output.js';
import { translateTelegramError } from '../../lib/errors.js';
import { resolveEntity } from '../../lib/peer.js';
import { serializeMessage } from '../../lib/serialize.js';
import { withAuth } from '../../lib/with-auth.js';
import { ErrorCode } from '../../lib/error-codes.js';
import type { GlobalOptions } from '../../lib/types.js';
import { parseIntegerOption } from '../../lib/validate.js';
/**
* Options for the poll subcommand.
*/
interface PollOpts {
question: string;
option: string[];
quiz?: boolean;
correct?: string;
solution?: string;
multiple?: boolean;
public?: boolean;
closeIn?: string;
}
/**
* Validate poll options before sending to Telegram API.
* Returns null if valid, or { error, code } describing the first validation failure.
*
* Fail-fast: reports first error found.
*/
export function validatePollOpts(opts: Pick<PollOpts, 'question' | 'option' | 'quiz' | 'correct' | 'solution' | 'multiple' | 'closeIn'>): { error: string; code: string } | null {
// Question validation
if (!opts.question || opts.question.trim().length === 0) {
return { error: 'Poll question cannot be empty', code: ErrorCode.EMPTY_QUESTION };
}
if (opts.question.length > 300) {
return { error: 'Question too long (max 300 chars)', code: ErrorCode.QUESTION_TOO_LONG };
}
// Options count validation
if (opts.option.length < 2) {
return { error: 'Poll requires 2-10 options', code: ErrorCode.TOO_FEW_OPTIONS };
}
if (opts.option.length > 10) {
return { error: 'Poll requires 2-10 options', code: ErrorCode.TOO_MANY_OPTIONS };
}
// Individual option validation
for (const opt of opts.option) {
if (!opt || opt.trim().length === 0) {
return { error: 'Poll option cannot be empty', code: ErrorCode.EMPTY_OPTION };
}
if (opt.length > 100) {
return { error: 'Option too long (max 100 chars)', code: ErrorCode.OPTION_TOO_LONG };
}
}
// Duplicate detection
const seen = new Set<string>();
for (const opt of opts.option) {
if (seen.has(opt)) {
return { error: `Duplicate option text: '${opt}'`, code: ErrorCode.DUPLICATE_OPTION };
}
seen.add(opt);
}
// Quiz constraints
if (opts.quiz && !opts.correct) {
return { error: 'Quiz mode requires --correct <index>', code: ErrorCode.QUIZ_MISSING_CORRECT };
}
if (opts.solution && !opts.quiz) {
return { error: '--solution requires --quiz mode', code: ErrorCode.SOLUTION_WITHOUT_QUIZ };
}
if (opts.quiz && opts.multiple) {
return { error: 'Quiz mode cannot use --multiple', code: ErrorCode.QUIZ_MULTIPLE_CONFLICT };
}
// --correct range validation
if (opts.correct !== undefined) {
try {
parseIntegerOption(opts.correct, 'Correct index', { min: 1, max: opts.option.length });
} catch {
return { error: `Correct index must be 1-${opts.option.length}`, code: ErrorCode.INVALID_CORRECT_INDEX };
}
}
// --close-in validation
if (opts.closeIn !== undefined) {
try {
parseIntegerOption(opts.closeIn, 'Close-in seconds', { min: 1 });
} catch {
return { error: 'Close-in seconds must be > 0', code: ErrorCode.INVALID_CLOSE_IN };
}
}
return null;
}
/**
* Action handler for `tg message poll <chat>`.
*
* Sends a poll to a chat with full configuration support:
* basic polls, quiz mode, multiple choice, anonymous/public, auto-close timer.
*
* Validates all options client-side before making the API call.
* Returns serialized MessageItem via outputSuccess on success.
*/
export async function messagePollAction(this: Command, chat: string): Promise<void> {
const opts = this.optsWithGlobals() as GlobalOptions & PollOpts;
// Client-side validation
const validation = validatePollOpts(opts);
if (validation) {
outputError(validation.error, validation.code);
return;
}
await withAuth(opts, async (client) => {
const entity = await resolveEntity(client, chat);
try {
// Build poll answers
const answers = opts.option.map((text) => new Api.InputPollAnswer({
text: new Api.TextWithEntities({ text, entities: [] }),
}));
const closeInSeconds = opts.closeIn !== undefined ? Number(opts.closeIn.trim()) : undefined;
const poll = new Api.Poll({
id: generateRandomLong(),
hash: bigInt.zero,
question: new Api.TextWithEntities({ text: opts.question, entities: [] }),
answers,
quiz: opts.quiz || undefined,
publicVoters: opts.public || undefined,
multipleChoice: opts.multiple || undefined,
closePeriod: closeInSeconds || undefined,
});
const correctIdx = opts.correct !== undefined ? Number(opts.correct.trim()) - 1 : undefined;
const inputMedia = new Api.InputMediaPoll({
poll,
correctAnswers: opts.quiz && correctIdx !== undefined
? [correctIdx]
: undefined,
solution: opts.solution || undefined,
solutionEntities: opts.solution ? [] : undefined,
});
const sentMsg = await client.sendFile(entity, { file: inputMedia });
if (!sentMsg) {
outputError('Telegram did not return the sent poll result; retrying may create a duplicate.', ErrorCode.MESSAGE_RESULT_UNAVAILABLE);
return;
}
const serialized = serializeMessage(sentMsg as any);
outputSuccess(serialized);
} catch (err: unknown) {
const { message, code } = translateTelegramError(err);
outputError(message, code);
}
});
}