///|
/// Short names that keep `Command::Messages` on one line: formatters before
/// and after MoonBit 0.10.20 disagree on a trailing comma after a long one.
using @model {type ChannelId, type GuildId, type MessageId}
///|
priv enum Command {
Me
Guilds
Channels(GuildId)
Messages(ChannelId, limit~ : Int32, before~ : MessageId?, after~ : MessageId?)
Send(ChannelId, content~ : String?, reply_to~ : MessageId?)
Api(@dhttp.Route, Json?)
}
///|
fn validate_content(content : String) -> String raise UsageError {
if content.trim(chars=" \n\r\t") == "" {
raise UsageError("refusing to send an empty message")
}
content
}
///|
fn stdin_content(data : Bytes) -> String raise UsageError {
validate_content(
@utf8.decode(data) catch {
_ => raise UsageError("stdin is not valid UTF-8")
},
)
}
///|
fn[T : ToJson] to_json_array(items : Array[T]) -> Json {
Json::array(items.map(item => item.to_json()))
}
///|
async fn run(client : @dhttp.Client, command : Command) -> Json {
match command {
Me => client.get_current_user().to_json()
Guilds => {
let pages = client.paginate_current_user_guilds(
page_size=200,
with_counts=true,
)
let guilds = []
while pages.next_page() is Some(page) {
guilds.append(page)
}
to_json_array(guilds)
}
Channels(id) => to_json_array(client.guild_ref(id).channels())
Messages(id, limit~, before~, after~) => {
let messages = client
.channel_ref(id)
.messages(before?, after?, page_size=limit.min(MAX_PAGE_SIZE))
.collect(max=limit)
messages.sort_by((a, b) => Compare::compare(b.id, a.id))
to_json_array(messages)
}
Send(id, content~, reply_to~) => {
let content = match content {
Some(text) => text
None => stdin_content(@stdio.stdin.read_all())
}
client.channel_ref(id).send(content~, reply_to?).to_json()
}
Api(route, body) => client.request(route, body?)
}
}