Compare commits

...

2 commits

7 changed files with 113 additions and 19 deletions

View file

@ -1 +1,2 @@
pub mod moove;
pub mod say;

17
src/commands/say.rs Normal file
View file

@ -0,0 +1,17 @@
use poise;
// use super::super::types::Data;
type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, (), Error>;
#[poise::command(
slash_command,
description_localized("en-US", "Make me say something!")
)]
pub async fn say(ctx: Context<'_>,
#[description = "What will you make me say this time? 🙃"]
message: String
) -> Result<(), Error> {
ctx.say(message).await?;
Ok(())
}

View file

@ -1,8 +1,9 @@
use poise::samples::{register_globally, register_in_guild};
use serenity::async_trait;
use serenity::prelude::GatewayIntents;
use serenity::client::Context;
use serenity::model::gateway::Ready;
use serenity::all::{Message, EventHandler};
use serenity::all::{EventHandler, GuildId, Message};
use serenity::Client;
use tokio_cron_scheduler::{JobScheduler, Job};
@ -13,6 +14,8 @@ use message_handler::handle;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
mod commands;
mod util;
@ -20,8 +23,27 @@ mod util;
mod other;
use other::notice;
mod types;
struct Handler;
use commands::say::say;
use types::Error;
async fn on_error(error: poise::FrameworkError<'_, (), Error>) {
match error {
poise::FrameworkError::Setup { error, .. } => panic!("Failed to start bot: {:?}", error),
poise::FrameworkError::Command { error, ctx, .. } => {
println!("Error in command `{}`: {:?}", ctx.command().name, error,);
}
error => {
if let Err(e) = poise::builtins::on_error(error).await {
println!("Error while handling error: {}", e)
}
}
}
}
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
@ -54,6 +76,39 @@ impl EventHandler for Handler {
async fn main() -> anyhow::Result<()> {
use anyhow::Context;
// create poise framework for registering commands
let options = poise::FrameworkOptions {
commands: vec![say()],
prefix_options: poise::PrefixFrameworkOptions {
prefix: Some("/".into()),
edit_tracker: Some(Arc::new(poise::EditTracker::for_timespan(
Duration::from_secs(3600),
))),
..Default::default()
},
on_error: |err| Box::pin(on_error(err)),
command_check: Some(|ctx| {
Box::pin(async move {
return Ok(!ctx.author().bot)
})
}),
..Default::default()
};
let debug_guild_id = dotenv_var("DEBUG_GUILD_ID")
.context("DEBUG_GUILD_ID not found in env")?
.parse::<u64>().unwrap();
let framework = poise::Framework::builder()
.setup(move |ctx, _ready, framework| {
Box::pin(async move {
register_in_guild(ctx, &framework.options().commands, GuildId::new(debug_guild_id)).await?;
Ok(())
})
})
.options(options)
.build();
let token_str = "TOKEN";
#[cfg(feature="DEBUG")]
@ -65,6 +120,7 @@ async fn main() -> anyhow::Result<()> {
let mut client = Client::builder(&token, intents)
.event_handler(Handler)
.framework(framework)
.await
.context("Failed to build client")?;

View file

@ -41,7 +41,10 @@ pub async fn handle(ctx: Context, msg: Message) {
let new_content = format!("Sent by {}\n{}", msg.clone().author, lower_case_content.replace(site, fix));
match utilities::replace_msg(ctx.http.clone(), msg.clone(), new_content).await {
Ok(_) => {},
Err(e) => send_error(ctx.http.clone(), e.to_string()).await
Err(e) => {
let _ = send_error(ctx.http.clone(), e.to_string()).await;
return;
}
};
}
}
@ -50,7 +53,10 @@ pub async fn handle(ctx: Context, msg: Message) {
if random::<u16>() % 10000 == 666 {
match msg.reply(ctx.http(), "Povedz loď").await {
Ok(_) => {},
Err(e) => send_error(ctx.http.clone(), e.to_string()).await
Err(e) => {
let _ = send_error(ctx.http.clone(), e.to_string()).await;
return;
}
}
}
@ -78,7 +84,7 @@ async fn response(http: Arc<Http>, msg: Message) -> bool {
match msg.reply(http.clone(), RESPONSES[num]).await {
Ok(_) => { return true }
Err(e) => {
send_error(http, e.to_string()).await;
let _ = send_error(http, e.to_string()).await;
return false
}
};
@ -94,7 +100,7 @@ async fn henlo(http: Arc<Http>, msg: Message) -> bool {
match msg.reply(http.clone(), response).await {
Ok(_) => { return true }
Err(e) => {
send_error(http, e.to_string()).await;
let _ = send_error(http, e.to_string()).await;
return false
}
};

View file

@ -18,7 +18,7 @@ use tenorv2::{tenor, tenor_builder::Tenor, tenor_types::{ContentFilter, MediaFil
pub async fn notice_wrapper(ctx: Context) {
match notice(ctx.http.clone()).await {
Err(e) => {
send_error(ctx.http.clone(), e.to_string()).await;
let _ = send_error(ctx.http.clone(), e.to_string()).await;
return;
},
Result::Ok(_) => return
@ -63,7 +63,7 @@ async fn celebrate_birthday(guild_id: GuildId, user_id: UserId, nick: &str, http
let gif_url = match tenor::get_gif_url(MediaFilter::gif, tenor_response) {
Ok(urls) => Some(urls),
Err(e) => {
send_error(http.clone(), e.to_string()).await;
let _ = send_error(http.clone(), e.to_string()).await;
None
}
};

5
src/types.rs Normal file
View file

@ -0,0 +1,5 @@
// pub struct Data {}
pub type Error = Box<dyn std::error::Error + Send + Sync>;
// replace () with Data if you ever need to store some additional data
// pub type Context<'a> = poise::Context<'a, (), Error>;

View file

@ -2,25 +2,31 @@ use std::sync::Arc;
use serenity::http::Http;
pub async fn send_error(_http: Arc<Http>, msg: String) {
pub async fn send_error(_http: Arc<Http>, msg: String) -> anyhow::Result<()> {
println!("ERROR: {msg}");
#[cfg(feature="RELEASE")] {
use serenity::all::ChannelId;
use serenity::all::CreateMessage;
use std::process::exit;
use super::security::dotenv_var;
use anyhow::Context;
match ChannelId::new(1199495008416440491)
.send_message(_http, CreateMessage::new().content(msg)).await {
Ok(_) => { return; }
let channel_id: String = dotenv_var("DEBUG_CHANNEL_ID").context("DEBUG_CHANNEL_ID not found in env file")?;
match ChannelId::new(channel_id.parse::<u64>().unwrap())
.say(_http, msg).await {
Ok(_) => { return Ok(()); }
Err(_) => { exit(-1) }
};
}
Ok(())
}
#[cfg(feature="RELEASE")]
pub async fn hello(http: Arc<Http>) {
pub async fn hello(http: Arc<Http>) -> anyhow::Result<()> {
use serenity::all::ChannelId;
use anyhow::Context;
use super::security::dotenv_var;
let messages = [
"AAAAAAAAAAAAAAAAAAAA",
@ -35,8 +41,11 @@ pub async fn hello(http: Arc<Http>) {
let num = rand::random::<usize>() % messages.len();
let channel = ChannelId::new(780439236867653635);
let channel_id: String = dotenv_var("DEBUG_CHANNEL_ID").context("DEBUG_CHANNEL_ID not found in env file")?;
let channel = ChannelId::new(channel_id.parse::<u64>().unwrap());
if let Err(why) = channel.say(http, messages[num]).await {
print!("Error sending message: {:?}", why);
};
Ok(())
}