Recipe: a poll from a modal
/quickpoll opens a small form for the question and up to four answers, posts the poll with one button per answer, and counts votes live. Commands, modals, components and message updates in one bot.
What it needs
- Intents: none (interactions need no intent).
- Permissions: View channels and Send messages where it is used.
The code
import { actionRow, button, ButtonStyle, Client, modal, textInput, TextInputStyle } from '@mnema-xyz/bot-sdk'
const client = new Client({
baseUrl: process.env.MNEMA_URL ?? 'https://talk.example.org',
token: process.env.MNEMA_TOKEN ?? '',
intents: 0,
})
const votes = new Map<string, Map<string, number>>() // message id -> member id -> answer index
client.on('ready', () => client.commands.set([{ name: 'quickpoll', description: 'Ask the channel a question' }]))
function render(question: string, answers: string[], tally: number[]) {
return {
content: `**${question}**`,
components: [
actionRow(
...answers.map((a, n) =>
button({ customId: `vote:${n}`, label: `${a} · ${tally[n] ?? 0}`, style: ButtonStyle.Secondary }),
),
),
],
}
}
client.on('interactionCreate', async (i) => {
if (i.isCommand() && i.commandName === 'quickpoll') {
await i.showModal(
modal({
customId: 'quickpoll',
title: 'New poll',
components: [
textInput({ customId: 'question', label: 'Question', maxLength: 200 }),
textInput({ customId: 'answers', label: 'Answers, one per line (2 to 4)', style: TextInputStyle.Paragraph }),
],
}),
)
} else if (i.isModalSubmit() && i.customId === 'quickpoll') {
const answers = (i.fields.get('answers') ?? '').split('\n').map((s) => s.trim()).filter(Boolean).slice(0, 4)
if (answers.length < 2) return i.reply({ content: 'A poll needs at least two answers.', ephemeral: true })
await i.reply(render(i.fields.get('question') ?? '', answers, answers.map(() => 0)))
} else if (i.isButton() && i.customId.startsWith('vote:') && i.message) {
const byMember = votes.get(i.message.id) ?? new Map<string, number>()
byMember.set(i.user.id, Number(i.customId.slice(5)))
votes.set(i.message.id, byMember)
const buttons = i.message.components?.[0]?.components ?? []
const answers = buttons.map((b) => ('label' in b ? String(b.label).replace(/ · \d+$/, '') : ''))
const tally = answers.map((_, n) => [...byMember.values()].filter((v) => v === n).length)
await i.update(render((i.message.content ?? '').replace(/\*\*/g, ''), answers, tally))
}
})
client.on('error', (err) => console.error(err))
await client.connect()
Notes
- A modal opens as the answer to a command or a click (callback
9), never to another modal. It can be submitted once, within 15 minutes. i.fields.get()reads a text input by itscustom_id; the server already checked lengths and required inputs.- One vote per member: the map is keyed by member id, so a second click changes the vote.