send command

This commit is contained in:
Vilmos Zsombor TANCZOS 2025-04-30 19:49:14 +02:00
parent 08d9a337cc
commit 0488ce4b9b
6 changed files with 259 additions and 2 deletions

0
src/checks.rs Normal file
View file

32
src/commands.rs Normal file
View file

@ -0,0 +1,32 @@
use crate::prelude::*;
mod send;
use poise::Command;
pub use send::SendTarget;
pub fn get() -> Vec<Command<KBotData, Error>> {
vec![send()]
}
#[poise::command(prefix_command)]
async fn send(
ctx: Context<'_>,
#[description = "Send target"] target: SendTarget,
#[rest]
#[description = "Message to send"]
content: String,
) -> CommandResult {
match target {
SendTarget::Channel(channel) => {
channel.say(ctx, content).await?;
}
SendTarget::User(user) => {
user.create_dm_channel(ctx).await?.say(ctx, content).await?;
}
SendTarget::Message(message) => {
message.reply(ctx, content).await?;
}
}
Ok(())
}

60
src/commands/send.rs Normal file
View file

@ -0,0 +1,60 @@
use crate::prelude::*;
use serenity::{GuildChannelParseError, MessageParseError, async_trait};
pub enum SendTarget {
Channel(Box<serenity::GuildChannel>),
User(Box<serenity::User>),
Message(Box<serenity::Message>),
}
#[derive(thiserror::Error, Debug)]
pub enum SendTargetParseError {
#[error("error during parsing as channel")]
ChannelError(#[from] GuildChannelParseError),
#[error("error during parsing as message")]
MessageError(#[from] MessageParseError),
#[error("failed to parse target")]
Malformed,
}
#[async_trait]
impl serenity::ArgumentConvert for SendTarget {
type Err = SendTargetParseError;
async fn convert(
ctx: impl serenity::CacheHttp,
guild_id: Option<serenity::GuildId>,
channel_id: Option<serenity::ChannelId>,
s: &str,
) -> serenity::Result<Self, Self::Err> {
let user_result = serenity::User::convert(&ctx, guild_id, channel_id, s).await;
if let Ok(user) = user_result {
return Ok(Self::User(Box::new(user)));
}
let message_result = serenity::Message::convert(&ctx, guild_id, channel_id, s).await;
match message_result {
Ok(message) => return Ok(Self::Message(Box::new(message))),
Err(ref e) => match e {
MessageParseError::Http(_) | MessageParseError::HttpNotAvailable => {
message_result?;
}
_ => {}
},
}
let channel_result = serenity::GuildChannel::convert(&ctx, guild_id, channel_id, s).await;
match channel_result {
Ok(channel) => return Ok(Self::Channel(Box::new(channel))),
Err(ref e) => {
tracing::error!("{:?}", e);
if let GuildChannelParseError::Http(_) = e {
channel_result?;
}
}
}
Err(Self::Err::Malformed)
}
}

View file

@ -1,3 +1,75 @@
fn main() {
println!("Hello, world!");
use poise::PrefixFrameworkOptions;
use tracing::{error, info};
mod checks;
mod commands;
pub mod prelude {
pub use poise::serenity_prelude as serenity;
pub struct KBotData {}
pub type Error = Box<dyn std::error::Error + Send + Sync>;
pub type Context<'a> = poise::Context<'a, KBotData, Error>;
pub type CommandResult = Result<(), Error>;
}
use prelude::*;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
dotenv::dotenv().ok();
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let intents =
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;
let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: commands::get(),
prefix_options: PrefixFrameworkOptions {
prefix: Some(",".into()),
..Default::default()
},
on_error: |error| Box::pin(on_error(error)),
..Default::default()
})
.setup(|ctx, ready, framework| {
Box::pin(async move {
info!("Logged in as {}", ready.user.name);
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(KBotData {})
})
})
.build();
let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;
client.unwrap().start().await.unwrap();
}
async fn on_error(error: poise::FrameworkError<'_, KBotData, Error>) {
match error {
poise::FrameworkError::Command { error, ctx, .. } => {
let error = error;
error!("Error in command `{}`: {}", ctx.command().name, error,);
let _ = ctx.say("Failed to run command.".to_string()).await;
}
// poise::FrameworkError::ArgumentParse {
// error, input, ctx, ..
// } => {
// debug!(
// "Failed to parse argument `{:?}` for command `{}`: {}",
// input,
// ctx.command().name,
// error
// );
// }
error => {
if let Err(e) = poise::builtins::on_error(error).await {
error!("Error while handling error: {}", e);
}
}
}
}