Poll with buttons
/poll <question> posts a yes/no poll as an embed with two buttons. Clicking a button updates the counts on the same message.
Source in zaun-bot: examples/ts/poll-buttons (TypeScript) and examples/rust/poll-buttons (Rust).
The code
Section titled “The code”// `/poll question` posts a yes/no poll; buttons update the counts in place.// Votes live in the instance (lost on restart); a real bot would use `bot.storage`.import { ActionRowBuilder, Bot, ButtonBuilder, ButtonStyle, EmbedBuilder, SlashCommandBuilder } from '@zaun/bot';
const bot = new Bot();/** Voters per question. */const votes = new Map<string, { yes: Set<string>; no: Set<string> }>();
function render(question: string) { const v = votes.get(question) ?? { yes: new Set<string>(), no: new Set<string>() }; return { embeds: [new EmbedBuilder().setTitle(question).addFields( { name: 'Yes', value: String(v.yes.size), inline: true }, { name: 'No', value: String(v.no.size), inline: true }, )], components: [new ActionRowBuilder().addComponents( new ButtonBuilder().setCustomId(`yes:${question}`).setLabel('Yes').setEmoji('👍').setStyle(ButtonStyle.Success), new ButtonBuilder().setCustomId(`no:${question}`).setLabel('No').setEmoji('👎').setStyle(ButtonStyle.Danger), )], };}
bot.command( new SlashCommandBuilder().setName('poll').setDescription('Start a yes/no poll') .addStringOption((o) => o.setName('question').setDescription('What to ask').setRequired(true).setMinLength(1).setMaxLength(80)), (interaction) => { if (!interaction.isChatInputCommand()) return; const question = interaction.options.getString('question', true); votes.set(question, { yes: new Set(), no: new Set() }); interaction.reply(render(question)); },);
bot.component((id) => id.startsWith('yes:') || id.startsWith('no:'), (interaction) => { const [choice, ...rest] = interaction.customId.split(':'); const question = rest.join(':'); const v = votes.get(question) ?? { yes: new Set<string>(), no: new Set<string>() }; v.yes.delete(interaction.userId); v.no.delete(interaction.userId); (choice === 'yes' ? v.yes : v.no).add(interaction.userId); votes.set(question, v); interaction.update(render(question));});
export const { init, onEvent, onInteraction, onAutocomplete, onTimer, onVoiceEvent } = bot.exports();//! `/poll question` posts a yes/no poll; buttons update the counts in place.//!//! Votes live in the instance (lost on restart); a real bot would use `zaun_bot::storage`.
use std::collections::HashMap;
use zaun_bot::prelude::*;use zaun_bot::types::OptionKind;
#[derive(Default)]struct Poll { /// Keyed by the poll's question: `(yes, no)` voters. votes: HashMap<String, (Vec<String>, Vec<String>)>,}
fn render(question: &str, yes: usize, no: usize) -> Reply { Reply::new() .embed( EmbedBuilder::new() .title(question) .field("Yes", yes.to_string(), true) .field("No", no.to_string(), true), ) .row(ActionRow::buttons([ Button::success(format!("yes:{question}"), "Yes").emoji("👍"), Button::danger(format!("no:{question}"), "No").emoji("👎"), ]))}
impl Bot for Poll { fn commands(&mut self, _: &Config) -> Vec<ApplicationCommand> { let question = CommandOptionBuilder::new(OptionKind::String, "question", "What to ask") .required() .length(1, 80); vec![ SlashCommand::new("poll", "Start a yes/no poll") .option(question) .build(), ] }
fn on_command(&mut self, ctx: Context, command: CommandData) { let Some(question) = command.str("question") else { return; }; self.votes.entry(question.to_owned()).or_default(); let _ = ctx.reply(render(question, 0, 0)); }
fn on_component(&mut self, ctx: Context, component: ComponentData) { let Some((choice, question)) = component.custom_id.split_once(':') else { return; }; let (yes, no) = self.votes.entry(question.to_owned()).or_default(); let voter = ctx.member.member_id.clone(); yes.retain(|m| *m != voter); no.retain(|m| *m != voter); if choice == "yes" { yes.push(voter) } else { no.push(voter) } let (y, n) = (yes.len(), no.len()); let _ = ctx.update_message(render(question, y, n)); }}
export_bot!(Poll);The manifest
Section titled “The manifest”app_id = "org.zaun.examples.ts-poll"version = "0.1.0"name = "Poll"description = "Yes/no polls with buttons."permissions = ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"]
[capabilities]app_id = "org.zaun.examples.poll"version = "0.1.0"name = "Poll"description = "Yes/no polls with buttons."permissions = ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"]
[capabilities]How it works
Section titled “How it works”- The poll is an embed plus one action row of a success and a danger button.
- Each button’s custom id carries the vote and the question (
yes:<question>), so the bot knows which poll a click belongs to. - The component handler records the voter (moving their vote if they change their mind) and answers with an update of the clicked message (
interaction.update(..),ctx.update_message(..)). - Votes live in the instance and are lost on restart. A real bot would keep them in storage.
Run it
Section titled “Run it”git clone https://github.com/zaunchat/zaun-bot && cd zaun-bot/examples/ts/poll-buttonsnpm installzbot build && zbot pack --unsignedzaun-host bot install --community <ID> *.zbot # on a host with allow_unsigned = truegit clone https://github.com/zaunchat/zaun-bot && cd zaun-bot/examples/rust/poll-buttonszbot build && zbot pack --unsignedzaun-host bot install --community <ID> *.zbot # on a host with allow_unsigned = true