Referência
API Lua
Entenda para que serve a referência Lua gerada.
A API Lua é a lista das coisas que a Macchi deixa os scripts usarem. Se macchi.reply
envia uma mensagem, ctx.user mostra quem acionou o script e um construtor de mensagens
cria botões, a referência da API é onde esses nomes ficam registrados.
Você não precisa desta página para escrever o primeiro script. Comece por
Scripting se quiser uma explicação mais tranquila. Volte para cá quando
estiver pensando: “eu sei o que quero fazer, mas qual é o nome exato disso?”
Por Que Esta Página Existe
A API de scripting da Macchi é gerada a partir do código do host usando PopLua. Isso
ajuda a referência a ficar perto do que o bot realmente expõe, em vez de virar um texto
manual que pode ficar desatualizado.
A referência gerada é mais técnica do que o resto do wiki. Isso é esperado. Ela serve
para conferir propriedades, métodos, builders e módulos sem precisar abrir o código
fonte.
Como Ler
Leia como uma prateleira, não como um livro. Procure a coisa que quer fazer: responder,
montar uma mensagem, ver quem acionou o script ou usar o contexto. Se um nome parecer
útil, teste em um script pequeno antes de montar um fluxo inteiro em cima dele.
Por exemplo, a página de scripting mostra:
macchi.reply("Olá " .. ctx.user.username)
A referência da API é onde você vai quando quiser saber o que mais macchi ou
ctx.user conseguem fazer.
Mutação Atual De Membro
ctx.member:changeNick("Novo apelido") está disponível somente para o membro confiável
já fornecido pelo gatilho. A Macchi verifica novamente permissões e hierarquia atuais do
Discord antes da requisição, registra a operação sem guardar o apelido e nunca aceita um
ID de usuário vindo do Lua. Veja a referência canônica da API
Lua para o contrato completo.
ctx.member:dm("Mensagem") envia uma DM atribuída para esse mesmo membro confiável. A
operação auditada member.dm.send usa cotas por destinatário, menções permitidas vazias
e propriedade de saída sem servidor. Invocação de membro e Automação do servidor
elegível podem usá-la. O conteúdo da DM não é guardado na auditoria da operação.
Eventos Usam A Mesma API
Scripts acionados por Eventos usam a mesma superfície geral de
scripting. O que muda é o momento em que o script começa, não uma linguagem separada. Um
script de menção e um script de comando podem responder; eles só rodam em situações
diferentes.
Espera Dentro Da Execução
Use next.secs(seconds) para uma pausa curta e não bloqueante:
next.secs(1)
macchi.reply("Passou um segundo.")
A espera máxima é de 10 segundos e uma execução pode pedir 5 esperas. A pausa não gasta
o limite de 2 segundos de trabalho ativo, mas gasta o tempo total de 30 segundos e
termina rapidamente quando a execução é cancelada. Ela não agenda trabalho futuro e não
sobrevive a uma reinicialização.
Para um fluxo interativo curto, espere pela mesma pessoa no mesmo canal:
local resposta = next.message(10, "sim")
local reacao = next.reaction(10, "<:kitalua:1497600179472302180>")
As esperas de eventos duram no máximo 15 segundos e continuam consumindo o tempo total
da execução. Elas não observam outros servidores, canais, usuários ou execuções.
Alterações seguras de reação
A Macchi pode adicionar ou remover somente a própria reação em uma mensagem já fornecida
pelo contexto confiável:
if ctx.message ~= nil then
ctx.message:addReaction("<:kitalua:1497600179472302180>")
-- ctx.message:removeOwnReaction("<:kitalua:1497600179472302180>")
end
Logo antes da chamada ao Discord, a Macchi verifica novamente o membro, as permissões do
bot, o canal, a mensagem e o emoji. A operação recebe auditoria durável sem guardar o
conteúdo da mensagem. IDs arbitrários e remoção das reações de outras pessoas não estão
disponíveis.
A Macchi define a autoridade antes de expor os dados do evento. Em eventos automáticos
do servidor, ctx.member pode ser a pessoa afetada; sua presença não a transforma em
agente de autorização. A automação ainda exige capacidades, permissões atuais do bot,
escopo, cotas e auditoria.
Um envio confirmado retorna uma saída opaca pertencente ao script:
local sent = macchi.reply("Processando...")
sent:edit(message.new():text("Concluído"))
-- sent:delete()
Somente o mesmo script e autor pode alterá-la. Edições recriam a atribuição e as menções
permitidas, sem guardar o conteúdo na auditoria.
Adicionar/remover um cargo confiável e definir/limpar timeout estão disponíveis somente
com capacidades efetivas explícitas, autoridade elegível de Membro ou Automação do
servidor, permissão e hierarquia atuais do Discord, cotas por alvo e auditoria durável
sem conteúdo. Threads públicas criadas pela Macchi podem ser criadas, renomeadas e
arquivadas por um identificador opaco. Kick, ban, IDs arbitrários, administração ampla
de canais e mutação de threads de
terceiros continuam indisponíveis.
Downloads E Ajuda No Editor
Se quiser arquivos para autocomplete, referência local ou ferramentas, visite Downloads
da API Lua. O arquivo mais útil para muitos editores Lua é
poplua.d.lua, porque ele pode ajudar o editor a entender nomes específicos da Macchi.
Se o artefato gerado existir, ele aparece abaixo. Se ainda não tiver sido gerado, a
Macchi mostra apenas uma mensagem curta de placeholder.
PopLua Lua API
Schema poplua.lua-api v2, PopLua 1.0.0-rc.2.
Generated from C# PopLua binding declarations.
Contents
- Modules
- Userdata
-
Descriptors
ask_add_optionsask_install_optionsask_target_optionsask_update_optionsban_optionsban_targetbulk_ban_optionsbulk_ban_resultchannel_edit_optionsdelete_messages_optionsdeletion_resultkick_optionsmoderation_optionsmoderation_resultpurge_authorpurge_optionsstorage_batch_itemstorage_batch_optionsstorage_result
Modules
Module components
Convenience constructors for message component objects.
Component objects are inert until they are added to a message and sent. Macchi does not store durable Lua callbacks; interactive components route to named Lua entry functions in a fresh execution.
Capability: macchi.components
Functions
components.button(entry: string, label: string): Button
Creates an interactive button that can be added to a message.
Parameters:
-
entry— Lua function entry to invoke when clicked. -
label— Visible button label.
Returns:
- A Button object. The button is not sent until a message containing it is sent.
components.channelSelect(entry: string, placeholder?: string | nil): EntitySelect
Creates a routed channel select.
Examples:
local select = components.channelSelect("picked", "Choose a channel")
components.gallery(): MediaGallery
Creates an inert Components V2 media gallery.
Returns:
- An empty gallery. Add one to ten items before adding it to a message.
components.linkButton(label: string, url: string): Button
Creates a link button that opens a URL instead of routing to Lua.
Parameters:
-
label— Visible button label. -
url— Absolute http(s) URL.
Returns:
- A link Button object.
components.mentionableSelect(entry: string, placeholder?: string | nil): EntitySelect
Creates a routed user-or-role select.
Examples:
local select = components.mentionableSelect("picked", "Choose a target")
components.modal(title: string, entry: string, label?: string | nil): Modal
Creates a durable modal opened by a button in an owned message.
Examples:
local form = components.modal("Feedback", "submitFeedback")
form:paragraph("message", "Message")
components.option(label: string, value: string, description?: string | nil): SelectOption
Creates an option for a select menu.
components.roleSelect(entry: string, placeholder?: string | nil): EntitySelect
Creates a routed role select.
Examples:
local select = components.roleSelect("picked", "Choose a role")
components.select(entry: string, placeholder?: string | nil): Select
Creates a select menu that can be added to a message.
Parameters:
-
entry— Lua function entry to invoke when a value is selected. -
placeholder— Placeholder shown before selection.
Returns:
- A Select object. The menu is not sent until a message containing it is sent.
components.userSelect(entry: string, placeholder?: string | nil): EntitySelect
Creates a routed user select.
Examples:
local select = components.userSelect("picked", "Choose a user")
Module ctx
Runtime context exposed to Lua as the generated ctx module.
The context is valid only for the current ephemeral script execution. It contains sanitized host data and never exposes raw Discord objects.
Capability: macchi.context
Values
-
ctx.actor:User | nilread-only — Authorization-bearing user for intentional invocations, or nil for server events. -
ctx.args:stringread-only — Raw arguments supplied by the user or event host. -
ctx.attachment:Attachment | nilread-only — First attachment from the bounded message snapshot, or nil. -
ctx.authority:stringread-only — Trusted authority kind assigned by the host. Missing member data never increases it. -
ctx.channel:Channel | nilread-only — Channel where the execution happened, or nil when unavailable. -
ctx.component:Component | nilread-only — Component interaction data, or nil outside component executions. -
ctx.componentName:stringread-only — Name of the component interaction being handled, or an empty string. -
ctx.entry:stringread-only — Internal entry id, such as u123/help@42:run. -
ctx.executionReference:stringread-only — Opaque public execution reference, or an empty string when durable evidence is unavailable. -
ctx.guild:Guild | nilread-only — Guild/server where the execution happened, or nil in DMs. -
ctx.isDm:booleanread-only — Whether this execution is running without a guild/server context. -
ctx.isGuild:booleanread-only — Whether this execution has a guild/server context. -
ctx.member:Member | nilread-only — Guild member data for the triggering user, or nil when unavailable. -
ctx.message:MessageContext | nilread-only — Message that triggered the execution, or nil when unavailable. -
ctx.ownedMessage:OwnedMessage | nilread-only — Owned Macchi output associated with this trusted interaction, or nil. -
ctx.permissionMode:stringread-only — Trusted trigger permission behavior; Lua cannot change it. -
ctx.prefix:stringread-only — Current user prefix resolved by the host. -
ctx.reaction:Reaction | nilread-only — Reaction event data, or nil outside reaction executions. -
ctx.script:stringread-only — Public draft reference without an entry suffix, such as u123/help@0. -
ctx.scriptName:stringread-only — Current script name. -
ctx.scriptType:stringread-only — Current script type. -
ctx.scripts:Scriptsread-only — Bounded script metadata captured once for this execution. -
ctx.source:stringread-only — Event source that started this execution. -
ctx.subject:User | nilread-only — Affected event user for automatic server events, or nil for intentional invocations. -
ctx.user:Userread-only — Discord user identity that triggered the current execution.
Module emoji
Creates emoji tokens that can be attached to texts and buttons.
Capability: macchi.components
Functions
emoji.new(name: string): string
Creates an emoji token for usages like Button:emoji(…).
Parameters:
-
name— A custom emoji token or known Macchi emoji name such as kitalua.
Returns:
- An emoji token accepted by button builders.
Module log
Host logging functions available to Lua scripts.
Log messages are routed through the current Macchi host and do not send Discord messages.
Capability: macchi.log
Functions
log.error(message: string)
Writes an error log message.
Parameters:
-
message— Message to log.
log.info(message: string)
Writes an informational log message.
Parameters:
-
message— Message to log.
log.warn(message: string)
Writes a warning log message.
Parameters:
-
message— Message to log.
Module macchi
Discord/chat output functions available to Macchi scripts.
Methods are async and perform host actions during the current execution. They do not queue responses for a later flush.
Capability: macchi.discord
Values
-
macchi.ask:Askread-only — Platform-owned, proposal-only script management actions. -
macchi.prefix:stringread-only — Current user prefix resolved by the host for this execution. -
macchi.storage:Storageread-only — Shared persistent storage and host-local best-effort cache.
Functions
macchi.dm(text: string)
Sends an audited direct message to the trusted member in the current execution context.
Async: yes
Parameters:
-
text— Message text to send privately. Its content is not retained in operation audit.
macchi.reply(text: string): OwnedMessage
Sends a reply in the current runtime surface.
Async: yes
Parameters:
-
text— Message text to send.
macchi.replyMessage(message: MessageBuilder): OwnedMessage
Sends a message object built with message.new().
Async: yes
Parameters:
-
message— Message object to send.
macchi.send(channelId: string, text: string): OwnedMessage
Sends a message to a channel in the current guild.
Async: yes
Parameters:
-
channelId— Target channel id. The host only resolves channels inside the current guild. -
text— Message text to send.
Module message
Creates message builders that can be sent with Discord Components V2 controls.
Capability: macchi.discord
Functions
message.new(): MessageBuilder
Creates an empty message builder. The message is not sent until :send() is called.
Returns:
- A new MessageBuilder.
Module next
Bounded delays inside the current ephemeral execution.
Delays pause PopLua active-time accounting while suspended, but wall-time and cancellation continue to apply. This module is not a durable scheduler.
Functions
next.message(seconds: number, contentPrefix: string): MessageContext
Waits for the triggering actor’s next message in the current channel.
Async: yes
next.reaction(seconds: number, emoji: string): Reaction
Waits for the triggering actor’s next reaction on the triggering message.
Async: yes
next.secs(seconds: number)
Suspends this execution for a bounded number of seconds.
Async: yes
Parameters:
-
seconds— Delay in seconds, from zero through the configured maximum.
Exceptions:
-
ArgumentOutOfRangeException— Thrown when the duration is not finite or is outside the allowed range.
Module threads
Creates bounded Macchi-owned threads from trusted channel context.
Capability: macchi.discord
Functions
threads.create(parent: Channel, title: string): OwnedThread
Creates one owned public thread under a trusted current channel.
Examples:
local thread = threads.create(ctx.channel, "Discussion")
Async: yes
Userdata
Userdata Ask
Creates transport-neutral proposals. Macchi revalidates and applies an accepted action.
Methods
Ask:forAdd(options: ask_add_options)
Proposes a new mutable draft from a strict options table.
Async: yes
Ask:forCapabilities(options: ask_target_options)
Proposes opening the canonical capability manager for a mutable script.
Async: yes
Ask:forDelete(options: ask_target_options)
Proposes deleting one manageable mutable script.
Async: yes
Ask:forDisable(options: ask_target_options)
Proposes disabling one manageable mutable script.
Async: yes
Ask:forEnable(options: ask_target_options)
Proposes enabling one manageable mutable script.
Async: yes
Ask:forInstall(options: ask_install_options)
Proposes installing one exact immutable publication without copying its source.
Async: yes
Ask:forPublish(options: ask_target_options)
Proposes publishing an immutable next revision of a mutable script.
Async: yes
Ask:forUninstall(options: ask_target_options)
Proposes removing an installation after checking its dependents.
Async: yes
Ask:forUpdate(options: ask_update_options)
Proposes changing one manageable mutable script.
Async: yes
Userdata Attachment
Bounded read-only Discord attachment metadata; content is never downloaded.
Properties
-
Attachment.contentType:stringread-only -
Attachment.ephemeral:booleanread-only -
Attachment.filename:stringread-only -
Attachment.height:integerread-only -
Attachment.id:stringread-only -
Attachment.size:integerread-only -
Attachment.url:stringread-only -
Attachment.width:integerread-only
Userdata Button
Discord button object that can be added to a message and routed back to a Lua entry function.
Properties
-
Button.entry:stringread-only — Lua entry function name invoked when the button is clicked. -
Button.label:stringread-only — Visible button label. -
Button.url:stringread-only — URL for link buttons. Empty for interactive buttons.
Methods
Button:disabled(disabled: boolean): Button
Marks the button disabled or enabled.
Parameters:
-
disabled— Whether the button should be disabled.
Returns:
- The same button object for chaining.
Button:emoji(emoji: string): Button
Attaches an emoji token to the button.
Parameters:
-
emoji— Emoji text or custom Discord emoji token.
Returns:
- The same button object for chaining.
Button:style(style: string): Button
Changes the button style.
Parameters:
-
style— primary, secondary, success, danger, or link.
Returns:
- The same button object for chaining.
Userdata Channel
Discord channel context for the current execution.
Properties
-
Channel.id:stringread-only — Discord channel id as a string. -
Channel.isNsfw:booleanread-only -
Channel.isThread:booleanread-only -
Channel.mention:stringread-only — Discord channel mention text. -
Channel.name:stringread-only — Channel display name. -
Channel.parentId:stringread-only -
Channel.position:integerread-only -
Channel.topic:stringread-only -
Channel.type:stringread-only
Methods
Channel:delete(options: moderation_options)
Deletes the current trusted channel after live Manage Channels checks.
Capability: macchi.discord
Async: yes
Channel:edit(options: channel_edit_options)
Edits the current trusted channel after live Manage Channels checks.
Capability: macchi.discord
Async: yes
Channel:purge(options: purge_options): deletion_result
Deletes a bounded set of messages matching all selected filter categories.
Capability: macchi.discord
Async: yes
Userdata Component
Component interaction context for the current execution.
Properties
-
Component.id:stringread-only — Component route id/name. -
Component.name:stringread-only — Component entry name. -
Component.value:stringread-only — Selected value or modal value, when available. -
Component.valueCount:integerread-only — Number of selected dropdown values or submitted fields. -
Component.values:stringread-only — Selected dropdown values or submitted field values joined by newlines.
Methods
Component:field(key: string): string
Returns a submitted modal field by its schema key.
Component:fieldAt(key: string, index: integer): string
Returns one value from a multi-value modal field by 1-based index.
Parameters:
-
key— Modal schema key. -
index— One-based value index.
Returns:
- The selected value or uploaded file URL, or an empty string when absent.
Component:fieldCount(key: string): integer
Returns how many scalar values a submitted modal field contains.
Parameters:
-
key— Modal schema key.
Returns:
- The number of values submitted for that field.
Component:valueAt(index: integer): string
Returns a selected value by 1-based index.
Userdata EntitySelect
Discord typed entity select whose selected values are handler targets, never authorization principals.
Properties
-
EntitySelect.entry:stringread-only -
EntitySelect.placeholder:stringread-only
Methods
EntitySelect:disabled(disabled: boolean): EntitySelect
Userdata Guild
Discord guild/server context for the current execution.
Properties
-
Guild.bannerUrl:stringread-only — Guild banner URL. -
Guild.channelCount:integerread-only — Number of channels in the guild. -
Guild.description:stringread-only — Guild description, if any. -
Guild.iconUrl:stringread-only — Guild icon URL. -
Guild.id:stringread-only — Discord guild id as a string. -
Guild.memberCount:integerread-only — Number of members in the guild. -
Guild.name:stringread-only — Guild display name. -
Guild.ownerId:stringread-only — Guild owner id as a string. -
Guild.preferredLocale:stringread-only — Guild preferred locale. -
Guild.roleCount:integerread-only — Number of roles in the guild.
Methods
Guild:ban(target: User, options: ban_options): moderation_result
Bans one trusted user with an optional native previous-message deletion window.
Capability: macchi.discord
Async: yes
Guild:banMany(options: bulk_ban_options): bulk_ban_result
Bans a bounded set of trusted users without hiding partial failures.
Capability: macchi.discord
Async: yes
Guild:purgeMessages(options: purge_options): deletion_result
Deletes matching messages across a bounded set of visible authorized channels.
Capability: macchi.discord
Async: yes
Guild:unban(target: User, options: ban_options): moderation_result
Removes a ban for one trusted user.
Capability: macchi.discord
Async: yes
Userdata MediaGallery
An inert Components V2 media gallery assembled before a message is sent.
Methods
MediaGallery:item(url: string, description?: string | nil, spoiler?: boolean): MediaGallery
Adds remote image or video media with optional accessible alt text.
Parameters:
-
url— Direct absolute HTTP or HTTPS media URL. -
description— Optional accessible description, up to 1024 characters. -
spoiler— Whether Discord should hide the media behind a spoiler.
Returns:
- The same gallery for chaining.
Userdata Member
Guild-specific member data with tightly scoped audited actions.
Properties
-
Member.displayName:stringread-only — Display name for this user inside the guild. -
Member.guildAvatarUrl:stringread-only -
Member.id:stringread-only -
Member.isOwner:booleanread-only -
Member.joinedAt:stringread-only — ISO timestamp for when this member joined the guild, or an empty string. -
Member.nickname:stringread-only -
Member.roleCount:integerread-only -
Member.timedOutUntil:stringread-only — ISO timestamp for the active Discord timeout, or an empty string. -
Member.user:Userread-only — Discord user identity for this member.
Methods
Member:addRole(role: Role)
Adds one trusted same-guild role after live permission and hierarchy checks.
Capability: macchi.discord
Async: yes
Member:changeNick(nickname: string)
Changes this trusted member’s nickname through live host checks.
Capability: macchi.discord
Async: yes
Member:clearTimeout()
Clears the current timeout from this trusted member.
Examples:
ctx.member:clearTimeout()
Capability: macchi.discord
Async: yes
Member:disconnectVoice(options: moderation_options): moderation_result
Disconnects this trusted member from voice.
Capability: macchi.discord
Async: yes
Member:dm(text: string): OwnedMessage
Sends an audited direct message to this trusted guild member.
Examples:
local sent = ctx.member:dm("Your request was received.")
Capability: macchi.discord
Async: yes
Member:hasPermission(name: string): boolean
Checks one documented permission in this event snapshot.
Member:hasRole(role: Role): boolean
Checks whether this member’s bounded snapshot contains a role.
Member:kick(options: kick_options): moderation_result
Kicks this trusted member after current permission and hierarchy checks.
Capability: macchi.discord
Async: yes
Member:moveVoice(channel: Channel, options: moderation_options): moderation_result
Moves this trusted member to a trusted voice channel.
Capability: macchi.discord
Async: yes
Member:removeRole(role: Role)
Removes one trusted same-guild role after live permission and hierarchy checks.
Examples:
local role = ctx.member:roleAt(1)
if role ~= nil then ctx.member:removeRole(role) end
Capability: macchi.discord
Async: yes
Member:roleAt(index: integer): Role | nil
Returns a role from the bounded event snapshot by 1-based index.
Member:roleNameAt(index: integer): string
Returns a role name from the bounded event snapshot by 1-based index.
Member:setServerDeaf(enabled: boolean, options: moderation_options): moderation_result
Sets or clears this trusted member’s server deaf state.
Capability: macchi.discord
Async: yes
Member:setServerMute(enabled: boolean, options: moderation_options): moderation_result
Sets or clears this trusted member’s server mute.
Capability: macchi.discord
Async: yes
Member:setTimeout(seconds: integer)
Applies a bounded timeout duration in seconds to this trusted member.
Capability: macchi.discord
Async: yes
Userdata MessageBuilder
Message builder that can collect text and interactive Components V2 controls before it is sent.
Message builders are inert until message:send() is called. They do not edit or send Discord messages while they are being built.
Methods
MessageBuilder:accent(hex: string): MessageBuilder
Sets the Components V2 container accent using a hexadecimal RGB value.
Parameters:
-
hex— Six hexadecimal digits, optionally prefixed with #.
Returns:
- The same message object for chaining.
MessageBuilder:addButton(button: Button): MessageBuilder
Adds an existing button object to the message.
Parameters:
-
button— Button object created by components.button.
Returns:
- The same message object for chaining.
MessageBuilder:addEntitySelect(select: EntitySelect): MessageBuilder
Adds a typed Discord entity select routed through the message’s durable ownership record.
Examples:
local select = components.userSelect("choose", "Choose a user")
message.new():addEntitySelect(select):send()
MessageBuilder:addGallery(gallery: MediaGallery): MessageBuilder
Adds an existing Components V2 media gallery.
Parameters:
-
gallery— Gallery created by components.gallery().
Returns:
- The same message object for chaining.
MessageBuilder:addModal(modal: Modal): MessageBuilder
Adds a button that opens a durable, single-use modal.
MessageBuilder:addSelect(select: Select): MessageBuilder
Adds an existing select menu object to the message.
Parameters:
-
select— Select object created by select.new or components.select.
Returns:
- The same message object for chaining.
MessageBuilder:allowRole(role: Role): MessageBuilder
Allows one current-context role mention to notify its target.
Parameters:
-
role— The role to mention.
Returns:
- The same message object for chaining.
MessageBuilder:allowUser(user: User): MessageBuilder
Allows one context-related user mention to notify its target.
Parameters:
-
user— The user to mention.
Returns:
- The same message object for chaining.
MessageBuilder:button(entry: string, label: string): MessageBuilder
Adds a button by entry name and label.
Parameters:
-
entry— Lua function entry to call when clicked. -
label— Button label.
Returns:
- The same message object for chaining.
MessageBuilder:display(text: string): MessageBuilder
Adds one inert typed Text Display to the message body.
MessageBuilder:section(text: string, thumbnailUrl?: string | nil, description?: string | nil): MessageBuilder
Adds a text section with a thumbnail accessory.
Parameters:
-
text— Section text, up to 1000 characters. -
thumbnailUrl— Optional absolute HTTP or HTTPS image URL. -
description— Optional thumbnail alt text, up to 256 characters.
Returns:
- The same message object for chaining.
MessageBuilder:sectionButton(text: string, button: Button): MessageBuilder
Adds a text section with a button accessory.
Parameters:
-
text— Section text, up to 1000 characters. -
button— Routed or link button displayed beside the text.
Returns:
- The same message object for chaining.
MessageBuilder:select(entry: string, placeholder?: string | nil): Select
Adds a select menu by entry name and placeholder.
Parameters:
-
entry— Lua function entry to call when a value is selected. -
placeholder— Placeholder shown before the user selects an option.
Returns:
- A select builder that was also added to this message.
MessageBuilder:send(): OwnedMessage
Sends the built message through the current host.
Capability: macchi.discord
Async: yes
MessageBuilder:separator(divider?: boolean, spacing?: string): MessageBuilder
Adds a Components V2 visual separator.
Parameters:
-
divider— Whether Discord draws a visible line. -
spacing— Either small or large vertical spacing.
Returns:
- The same message object for chaining.
MessageBuilder:spoiler(spoiler?: boolean): MessageBuilder
Controls whether Discord hides the whole Components V2 container as a spoiler.
Parameters:
-
spoiler— Whether the container is spoilered.
Returns:
- The same message object for chaining.
MessageBuilder:text(text: string): MessageBuilder
Adds or replaces the main text body for this message.
Parameters:
-
text— Text to show in the Discord Components V2 message.
Returns:
- The same message object for chaining.
MessageBuilder:title(title: string): MessageBuilder
Adds a title line to the message.
Parameters:
-
title— Title text.
Returns:
- The same message object for chaining.
Userdata MessageContext
Message event context with context-bound reaction actions.
Properties
-
MessageContext.attachmentCount:integerread-only -
MessageContext.author:User | nilread-only -
MessageContext.channelId:stringread-only -
MessageContext.channelMentionCount:integerread-only -
MessageContext.createdAt:stringread-only -
MessageContext.editedAt:stringread-only -
MessageContext.guildId:stringread-only -
MessageContext.id:stringread-only — Discord message id as a string. -
MessageContext.isReply:booleanread-only -
MessageContext.mentionedUserCount:integerread-only — Number of users mentioned by this message. -
MessageContext.mentionsBot:booleanread-only — Whether this message mentioned the current Macchi bot account. -
MessageContext.roleMentionCount:integerread-only -
MessageContext.text:stringread-only — Message text visible to the bot.
Methods
MessageContext:addReaction(emoji: string)
Adds one audited reaction to this context-bound message.
Capability: macchi.discord
Async: yes
MessageContext:channelMentionAt(index: integer): string
MessageContext:delete(reason?: string): deletion_result
Deletes this trusted message after current channel permission checks.
Capability: macchi.discord
Async: yes
MessageContext:mentionedUserAt(index: integer): User | nil
Returns a mentioned user by 1-based index, or nil outside the list.
MessageContext:removeOwnReaction(emoji: string)
Removes only Macchi’s own audited reaction from this context-bound message.
Capability: macchi.discord
Async: yes
MessageContext:roleMentionAt(index: integer): string
Userdata Modal
A bounded modal schema routed to a named Lua entry.
Properties
-
Modal.entry:stringread-only -
Modal.label:stringread-only -
Modal.title:stringread-only
Methods
Modal:actor(policy: string): Modal
Sets who may open the modal: invoker or any_member.
Modal:channels(key: string, label: string, description?: string | nil, required?: boolean, min?: integer, max?: integer): Modal
Adds a channel picker to the modal.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether at least one channel must be selected. -
min— Minimum selected channels. -
max— Maximum selected channels.
Returns:
- The same modal for chaining.
Modal:check(key: string, label: string, description?: string | nil, selected?: boolean): Modal
Adds a single yes/no checkbox.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
selected— Whether the checkbox starts selected.
Returns:
- The same modal for chaining.
Modal:checks(key: string, label: string, description?: string | nil, required?: boolean, min?: integer, max?: integer): ModalChoices
Adds a multi-choice checkbox group and returns its option builder.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether a selection is required. -
min— Minimum selected checkboxes. -
max— Maximum selected checkboxes.
Returns:
- The option builder for this checkbox group.
Modal:display(text: string): Modal
Adds non-interactive Markdown help text to the modal.
Parameters:
-
text— Markdown text displayed between fields.
Returns:
- The same modal for chaining.
Modal:mentionables(key: string, label: string, description?: string | nil, required?: boolean, min?: integer, max?: integer): Modal
Adds a user-or-role picker to the modal.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether at least one target must be selected. -
min— Minimum selected targets. -
max— Maximum selected targets.
Returns:
- The same modal for chaining.
Modal:paragraph(key: string, label: string, placeholder?: string, required?: boolean, min?: integer, max?: integer, description?: string | nil): Modal
Adds a paragraph text field.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
placeholder— Optional input hint. -
required— Whether a value is required. -
min— Minimum text length. -
max— Maximum text length. -
description— Optional field help.
Returns:
- The same modal for chaining.
Modal:radio(key: string, label: string, description?: string | nil, required?: boolean): ModalChoices
Adds a single-choice radio group and returns its option builder.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether one option must be selected.
Returns:
- The option builder for this radio group.
Modal:roles(key: string, label: string, description?: string | nil, required?: boolean, min?: integer, max?: integer): Modal
Adds a role picker to the modal.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether at least one role must be selected. -
min— Minimum selected roles. -
max— Maximum selected roles.
Returns:
- The same modal for chaining.
Modal:select(key: string, label: string, description?: string | nil, required?: boolean, min?: integer, max?: integer): ModalChoices
Adds a string select and returns its option builder.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether a selection is required. -
min— Minimum selected options. -
max— Maximum selected options.
Returns:
- The option builder for this select.
Modal:text(key: string, label: string, placeholder?: string, required?: boolean, min?: integer, max?: integer, description?: string | nil): Modal
Adds a one-line text field.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
placeholder— Optional input hint. -
required— Whether a value is required. -
min— Minimum text length. -
max— Maximum text length. -
description— Optional field help.
Returns:
- The same modal for chaining.
Modal:upload(key: string, label: string, description?: string | nil, required?: boolean, min?: integer, max?: integer): Modal
Adds a Discord file upload. Submitted file URLs are exposed as newline-separated scalars.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether an upload is required. -
min— Minimum uploaded files. -
max— Maximum uploaded files.
Returns:
- The same modal for chaining.
Modal:users(key: string, label: string, description?: string | nil, required?: boolean, min?: integer, max?: integer): Modal
Adds a user picker to the modal.
Parameters:
-
key— Stable schema key. -
label— User-facing label. -
description— Optional field help. -
required— Whether at least one user must be selected. -
min— Minimum selected users. -
max— Maximum selected users.
Returns:
- The same modal for chaining.
Userdata ModalChoices
Options for a string select, radio group, or checkbox group in a modal.
Methods
ModalChoices:done(): Modal
Returns to the owning modal so more fields can be added.
Returns:
- The modal that owns this choice group.
ModalChoices:option(label: string, value: string, description?: string | nil, selected?: boolean): ModalChoices
Adds one choice.
Parameters:
-
label— User-facing choice label. -
value— Stable scalar returned to the Lua handler. -
description— Optional help text for the choice. -
selected— Whether the choice starts selected.
Returns:
- The same choices object for chaining.
Userdata OwnedMessage
A host-created reference to one confirmed Macchi Discord output.
Properties
-
OwnedMessage.channelId:stringread-only -
OwnedMessage.createdAt:stringread-only -
OwnedMessage.guildId:stringread-only -
OwnedMessage.id:stringread-only -
OwnedMessage.isDeleted:booleanread-only
Methods
OwnedMessage:delete()
Deletes this owned output while preserving its audit evidence.
Capability: macchi.discord
Async: yes
OwnedMessage:edit(message: MessageBuilder)
Replaces this owned output through Macchi’s trusted renderer.
Capability: macchi.discord
Async: yes
Userdata OwnedThread
Opaque handle for a thread created and durably owned by Macchi.
Properties
-
OwnedThread.state:stringread-only
Methods
OwnedThread:archive()
Archives this exact Macchi-owned thread.
Examples:
thread:archive()
Capability: macchi.discord
Async: yes
OwnedThread:rename(title: string)
Renames this exact Macchi-owned thread.
Examples:
thread:rename("Reviewed discussion")
Capability: macchi.discord
Async: yes
OwnedThread:reopen()
Reopens this exact Macchi-owned thread when it is archived.
Examples:
thread:reopen()
Capability: macchi.discord
Async: yes
OwnedThread:send(text: string): OwnedMessage
Sends one attributed owned message through this exact thread.
Examples:
local message = thread:send("Update")
Capability: macchi.discord
Async: yes
Userdata Reaction
Reaction event context for the current execution.
Properties
-
Reaction.added:booleanread-only -
Reaction.channelId:stringread-only — Channel id the reaction belongs to. -
Reaction.emoji:stringread-only — Emoji text supplied by Discord for the reaction. -
Reaction.emojiId:stringread-only -
Reaction.emojiName:stringread-only -
Reaction.guildId:stringread-only -
Reaction.isCustom:booleanread-only -
Reaction.messageId:stringread-only — Message id the reaction belongs to. -
Reaction.user:Userread-only — User who added or removed the reaction.
Userdata Role
Bounded read-only role metadata.
Properties
-
Role.color:stringread-only -
Role.everyone:booleanread-only -
Role.id:stringread-only -
Role.managed:booleanread-only -
Role.mention:stringread-only -
Role.name:stringread-only -
Role.position:integerread-only
Userdata Script
Read-only script metadata with an opaque execution-bound target handle.
Properties
-
Script.active:booleanread-only -
Script.available:booleanread-only -
Script.capabilityUrl:stringread-only -
Script.dependencies:StringListread-only -
Script.description:stringread-only -
Script.effectiveCapabilities:StringListread-only -
Script.executable:booleanread-only -
Script.grantedCapabilities:StringListread-only -
Script.kind:stringread-only -
Script.manageable:booleanread-only -
Script.managementUrl:stringread-only -
Script.name:stringread-only -
Script.ownerKind:stringread-only -
Script.reference:stringread-only -
Script.requestedCapabilities:StringListread-only -
Script.scope:stringread-only -
Script.source:stringread-only -
Script.sourceReadable:booleanread-only -
Script.visible:booleanread-only
Userdata ScriptList
An indexable, bounded script list.
Properties
-
ScriptList.count:integerread-only
Methods
ScriptList:at(index: integer): Script | nil
Returns one item by one-based index, or nil.
Userdata Scripts
A stable, bounded script snapshot for this execution.
Properties
-
Scripts.count:integerread-only -
Scripts.truncated:booleanread-only
Methods
Scripts:all(): ScriptList
Returns all items in deterministic snapshot order.
Scripts:at(index: integer): Script | nil
Returns one item by one-based index, or nil.
Scripts:channel(): ScriptList
Returns channel-owned items visible in the current channel.
Scripts:find(name: string): Script | nil
Finds the first deterministically ordered script with this name.
Scripts:findRef(reference: string): Script | nil
Finds an exact canonical script reference.
Scripts:installations(): ScriptList
Returns immutable publication installations visible in this execution.
Scripts:server(): ScriptList
Returns server-owned items visible in the current guild.
Scripts:user(): ScriptList
Returns user-owned items visible to this execution.
Userdata Select
Discord select menu object that can be added to a message and routed back to a Lua entry function.
Properties
-
Select.entry:stringread-only — Lua entry function name invoked when a value is selected. -
Select.placeholder:stringread-only — Placeholder shown before a value is selected.
Methods
Select:addOption(option: SelectOption): Select
Adds an existing option object to this select menu.
Select:disabled(disabled: boolean): Select
Marks the select menu disabled or enabled.
Select:option(label: string, value: string, description?: string | nil): Select
Adds an option to this select menu.
Parameters:
-
label— Visible option label. -
value— Value delivered to ctx.component.value when selected. -
description— Optional short description.
Returns:
- The same select object for chaining.
Userdata SelectOption
Discord select menu option object.
Properties
-
SelectOption.description:stringread-only -
SelectOption.label:stringread-only -
SelectOption.value:stringread-only
Methods
SelectOption:default(selected?: boolean): SelectOption
SelectOption:emoji(emoji: string): SelectOption
Userdata Storage
Methods
Storage:cache(scope: string): Store
Storage:open(scope: string): Store
Userdata Store
Properties
-
Store.persistent:booleanread-only -
Store.scope:stringread-only
Methods
Store:batch(options: storage_batch_options): storage_result[]
Applies 1-20 same-scope actions atomically for persistent storage.
Async: yes
Store:compareDelete(key: string, expected: string): storage_result
Async: yes
Store:compareSet(key: string, expected: string, value: string, ttlSeconds?: integer): storage_result
Async: yes
Store:delete(key: string): storage_result
Async: yes
Store:get(key: string): storage_result
Async: yes
Store:increment(key: string, delta?: integer): storage_result
Async: yes
Store:set(key: string, value: string, ttlSeconds?: integer): storage_result
Async: yes
Userdata StringList
An indexable, bounded string list.
Properties
-
StringList.count:integerread-only
Methods
StringList:at(index: integer): string | nil
StringList:contains(value: string): boolean
Userdata User
Discord user identity that triggered a script execution.
Properties
-
User.avatarUrl:stringread-only — Current event-snapshot avatar URL, or an empty string. -
User.createdAt:stringread-only — ISO timestamp derived from the Discord snowflake. -
User.displayName:stringread-only — Display name for the user. -
User.id:stringread-only — Discord user id as a string. -
User.isBot:booleanread-only — Whether the user is a bot account. -
User.isSystem:booleanread-only — Whether Discord marks this as a system account. -
User.mention:stringread-only — Discord mention text for the user. -
User.username:stringread-only — Best available username for display.
Descriptors
Descriptor ask_add_options
| Field | Type | Description |
|---|---|---|
capabilities |
string[] |
|
dependencies |
string[] |
|
description |
string |
|
enable |
boolean |
|
name |
string |
|
scope |
string |
|
source |
string |
|
trigger |
string |
Descriptor ask_install_options
| Field | Type | Description |
|---|---|---|
capabilities |
string[] |
|
enable |
boolean |
|
scope |
string |
|
script |
string |
Descriptor ask_target_options
| Field | Type | Description |
|---|---|---|
script |
Script |
Descriptor ask_update_options
| Field | Type | Description |
|---|---|---|
capabilities |
string[] |
|
dependencies |
string[] |
|
description |
`string | nil` |
script |
Script |
|
source |
string |
Descriptor ban_options
| Field | Type | Description |
|---|---|---|
deleteMessages |
`delete_messages_options | nil` |
reason |
string |
Descriptor ban_target
| Field | Type | Description |
|---|---|---|
user |
User |
Descriptor bulk_ban_options
| Field | Type | Description |
|---|---|---|
deleteMessages |
`delete_messages_options | nil` |
reason |
string |
|
targets |
ban_target[] |
Descriptor bulk_ban_result
Describes the applied and failed targets of one bulk ban operation.
| Field | Type | Description |
|---|---|---|
actionId |
string |
|
appliedAt |
string |
|
appliedCount |
integer |
Gets the number of targets that were banned. |
appliedTargets |
string[] |
|
deletion |
deletion_result |
|
failedCount |
integer |
Gets the number of targets that failed. |
failedTargets |
string[] |
Descriptor channel_edit_options
| Field | Type | Description |
|---|---|---|
name |
`string | nil` |
nsfw |
`boolean | nil` |
reason |
string |
|
slowmodeSeconds |
`integer | nil` |
topic |
`string | nil` |
Descriptor delete_messages_options
| Field | Type | Description |
|---|---|---|
channels |
string |
|
ignorePinned |
boolean |
|
onFailure |
string |
|
withinSeconds |
integer |
Descriptor deletion_result
Summarizes one bounded message deletion operation.
| Field | Type | Description |
|---|---|---|
bulkDeleted |
integer |
|
channels |
integer |
|
deleted |
integer |
|
dryRun |
boolean |
|
effectiveSeconds |
integer |
|
failed |
integer |
|
individuallyDeleted |
integer |
|
matched |
integer |
|
mode |
string |
|
requestedSeconds |
integer |
|
scanned |
integer |
|
skippedPinned |
integer |
|
skippedTooOld |
integer |
|
threads |
integer |
|
truncated |
boolean |
Descriptor kick_options
| Field | Type | Description |
|---|---|---|
deleteMessages |
`delete_messages_options | nil` |
reason |
string |
Descriptor moderation_options
| Field | Type | Description |
|---|---|---|
reason |
string |
Descriptor moderation_result
Describes the outcome of one moderation action.
| Field | Type | Description |
|---|---|---|
actionId |
string |
|
applied |
boolean |
|
appliedAt |
string |
|
deletion |
`deletion_result | nil` |
targetId |
string |
Descriptor purge_author
| Field | Type | Description |
|---|---|---|
user |
User |
Descriptor purge_options
| Field | Type | Description |
|---|---|---|
after |
`MessageContext | nil` |
author |
`User | nil` |
authorType |
string |
|
authors |
purge_author[] |
|
before |
`MessageContext | nil` |
channelLimit |
integer |
|
contains |
string |
|
deleteOldIndividually |
boolean |
|
dryRun |
boolean |
|
endsWith |
string |
|
hasAttachments |
`boolean | nil` |
hasEmbeds |
`boolean | nil` |
hasLinks |
`boolean | nil` |
hasMentions |
`boolean | nil` |
hasReactions |
`boolean | nil` |
includeThreads |
boolean |
|
limit |
integer |
|
messageTypes |
string[] |
|
pinned |
string |
|
reason |
string |
|
scanLimit |
integer |
|
startsWith |
string |
|
withinSeconds |
integer |
Descriptor storage_batch_item
| Field | Type | Description |
|---|---|---|
delta |
integer |
|
expected |
`string | nil` |
key |
string |
|
operation |
string |
|
value |
`string | nil` |
Descriptor storage_batch_options
| Field | Type | Description |
|---|---|---|
items |
storage_batch_item[] |
|
ttlSeconds |
integer |
Descriptor storage_result
Describes the outcome of one storage operation.
| Field | Type | Description |
|---|---|---|
applied |
boolean |
|
found |
boolean |
|
value |
string |
Gets the Lua-visible value, or an empty string when the key was not found. |
version |
integer |