Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add more errors to limit unwraps #137

Merged
merged 1 commit into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ edition = "2021"
twilight-gateway = "0.14.0"
twilight-http = "0.14.0"
twilight-model = "0.14.0"
twilight-validate = "0.14.0"
twilight-util = { version = "0.14.0", features = ["builder", "snowflake"] }
twilight-interactions = "0.14.0"
twilight-mention = "0.14.0"
Expand Down
10 changes: 5 additions & 5 deletions src/cache/cache_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ impl Cache {
});

if must_fetch {
let channel = bot.http.channel(channel_id).await?.model().await.unwrap();
let channel = bot.http.channel(channel_id).await?.model().await?;
current_channel_id = channel.parent_id;
}
}
Expand All @@ -180,7 +180,7 @@ impl Cache {
if !self.users.contains_key(&user_id) {
let user_get = bot.http.user(user_id).await;
let user = match user_get {
Ok(user) => Some(Arc::new(user.model().await.unwrap().into())),
Ok(user) => Some(Arc::new(user.model().await?.into())),
Err(why) => {
if get_status(&why) == Some(404) {
None
Expand Down Expand Up @@ -220,7 +220,7 @@ impl Cache {
}
}
Ok(wh) => {
let wh = Arc::new(wh.model().await.unwrap());
let wh = Arc::new(wh.model().await?);
self.webhooks.insert(webhook_id, wh.clone());
Some(wh)
}
Expand Down Expand Up @@ -248,7 +248,7 @@ impl Cache {
return Err(why.into());
}
}
Ok(msg) => Some(Arc::new(msg.model().await.unwrap().into())),
Ok(msg) => Some(Arc::new(msg.model().await?.into())),
};

self.messages.insert(message_id, msg, 1).await;
Expand Down Expand Up @@ -276,7 +276,7 @@ impl Cache {
}
}
};
Ok(Some(channel.model().await.unwrap()))
Ok(Some(channel.model().await?))
}

let Some(channel) = get_channel(bot, channel_id).await? else {
Expand Down
14 changes: 8 additions & 6 deletions src/client/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,14 @@ impl StarboardBot {

eprintln!("{msg}");
if let Some(chid) = self.config.error_channel {
let _ = self
.http
.create_message(chid.into_id())
.content(msg)
.unwrap()
.await;
let ret = self.http.create_message(chid.into_id()).content(msg);
let ret = match ret {
Ok(ret) => ret,
Err(why) => return eprintln!("{why}"),
};
if let Err(why) = ret.await {
eprintln!("{why}");
}
}
}
}
2 changes: 1 addition & 1 deletion src/core/autostar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub async fn handle(bot: &StarboardBot, event: &MessageCreate) -> StarboardResul
event.channel_id
) + &reasons.join("\n - ")
};
notify::notify(bot, event.author.id, &message).await;
notify::notify(bot, event.author.id, &message).await?;
}

continue;
Expand Down
36 changes: 12 additions & 24 deletions src/core/embedder/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,9 @@ impl Embedder<'_, '_> {
let ret = bot
.http
.execute_webhook(wh.id, wh.token.as_ref().unwrap())
.content(&built.top_content)
.unwrap()
.embeds(&built.embeds)
.unwrap()
.attachments(&attachments)
.unwrap()
.content(&built.top_content)?
.embeds(&built.embeds)?
.attachments(&attachments)?
.wait()
.await;

Expand All @@ -76,12 +73,9 @@ impl Embedder<'_, '_> {

bot.http
.create_message(self.config.starboard.channel_id.into_id())
.content(&built.top_content)
.unwrap()
.embeds(&built.embeds)
.unwrap()
.attachments(&attachments)
.unwrap()
.content(&built.top_content)?
.embeds(&built.embeds)?
.attachments(&attachments)?
.await
.map_err(|e| e.into())
}
Expand Down Expand Up @@ -113,33 +107,27 @@ impl Embedder<'_, '_> {
if let Some(wh) = wh {
bot.http
.update_webhook_message(wh.id, wh.token.as_ref().unwrap(), message_id)
.content(Some(&built.top_content))
.unwrap()
.embeds(Some(&built.embeds))
.unwrap()
.content(Some(&built.top_content))?
.embeds(Some(&built.embeds))?
.await?;
} else {
bot.http
.update_message(sb_channel_id, message_id)
.content(Some(&built.top_content))
.unwrap()
.embeds(Some(&built.embeds))
.unwrap()
.content(Some(&built.top_content))?
.embeds(Some(&built.embeds))?
.await?;
}
}
BuiltStarboardEmbed::Partial(built) => {
if let Some(wh) = wh {
bot.http
.update_webhook_message(wh.id, wh.token.as_ref().unwrap(), message_id)
.content(Some(&built.top_content))
.unwrap()
.content(Some(&built.top_content))?
.await?;
} else {
bot.http
.update_message(sb_channel_id, message_id)
.content(Some(&built.top_content))
.unwrap()
.content(Some(&built.top_content))?
.await?;
}
}
Expand Down
13 changes: 3 additions & 10 deletions src/core/starboard/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,13 @@ impl RefreshMessage<'_> {
self.configs.replace(Arc::new(configs));
}

async fn get_configs(&mut self) -> sqlx::Result<Arc<Vec<StarboardConfig>>> {
async fn get_configs(&mut self) -> StarboardResult<Arc<Vec<StarboardConfig>>> {
if self.configs.is_none() {
let msg = self.get_sql_message().await?;
let guild_id = msg.guild_id.into_id();
let channel_id = msg.channel_id.into_id();

let configs = StarboardConfig::list_for_channel(self.bot, guild_id, channel_id)
.await
.unwrap();
let configs = StarboardConfig::list_for_channel(self.bot, guild_id, channel_id).await?;
self.set_configs(configs);
}

Expand Down Expand Up @@ -262,12 +260,7 @@ impl<'this, 'bot> RefreshStarboard<'this, 'bot> {
return Ok(false);
}

let msg = embedder
.send(self.refresh.bot)
.await?
.model()
.await
.unwrap();
let msg = embedder.send(self.refresh.bot).await?.model().await?;
StarboardMessage::create(
&self.refresh.bot.pool,
orig.message_id,
Expand Down
5 changes: 2 additions & 3 deletions src/core/starboard/webhooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ pub async fn get_valid_webhook(

let mut wh = bot
.http
.create_webhook(starboard.channel_id.into_id(), "Starboard")
.unwrap();
.create_webhook(starboard.channel_id.into_id(), "Starboard")?;

let bot_user = bot
.cache
Expand All @@ -44,7 +43,7 @@ pub async fn get_valid_webhook(
let Ok(wh) = wh.await else {
return Ok(None);
};
let wh = Arc::new(wh.model().await.unwrap());
let wh = Arc::new(wh.model().await?);

bot.cache.webhooks.insert(wh.id, wh.clone());

Expand Down
12 changes: 7 additions & 5 deletions src/database/models/autostar_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,13 @@ impl AutoStarChannel {
.push_bind(self.guild_id)
.push(" RETURNING *");

builder
.build()
.fetch_optional(pool)
.await
.map(|r| r.map(|r| AutoStarChannel::from_row(&r).unwrap()))
let ret = builder.build().fetch_optional(pool).await?;

if let Some(ret) = ret {
Ok(Some(AutoStarChannel::from_row(&ret)?))
} else {
Ok(None)
}
}

pub async fn rename(
Expand Down
6 changes: 6 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ pub enum StarboardError {
#[error(transparent)]
TwilightHttp(#[from] twilight_http::Error),
#[error(transparent)]
MessageValidationError(#[from] twilight_validate::message::MessageValidationError),
#[error(transparent)]
ValidationError(#[from] twilight_validate::request::ValidationError),
#[error(transparent)]
DeserializeBodyError(#[from] twilight_http::response::DeserializeBodyError),
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
#[error(transparent)]
InteractionParseError(#[from] twilight_interactions::error::ParseError),
Expand Down
3 changes: 1 addition & 2 deletions src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ async fn match_events(shard_id: u64, event: Event, bot: Arc<StarboardBot>) -> St
"See `/help` for more information on Starboard. If you don't see ",
"slash commands, try reinviting me using the \"Add to Server\" ",
"button on my profile.",
))
.unwrap()
))?
.reply(event.id)
.await;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl EditRequirements {
let starboard = Starboard::get(&ctx.bot.pool, ov.starboard_id)
.await?
.unwrap();
let mut resolved = StarboardConfig::new(starboard, vec![ov]).unwrap();
let mut resolved = StarboardConfig::new(starboard, vec![ov])?;

(resolved.overrides.remove(0), resolved.resolved)
};
Expand Down
2 changes: 1 addition & 1 deletion src/interactions/commands/chat/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async fn get_config(
) -> StarboardResult<StarboardConfig> {
let overrides =
StarboardOverride::list_by_starboard_and_channels(&bot.pool, sb.id, &[channel_id]).await?;
Ok(StarboardConfig::new(sb, overrides).unwrap())
Ok(StarboardConfig::new(sb, overrides)?)
}

async fn get_embedder<'config, 'bot>(
Expand Down
18 changes: 10 additions & 8 deletions src/interactions/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use twilight_model::{
};
use twilight_util::builder::InteractionResponseDataBuilder;

use crate::client::bot::StarboardBot;
use crate::{client::bot::StarboardBot, errors::StarboardResult};

pub type CommandCtx = Ctx<CommandData>;
pub type ComponentCtx = Ctx<MessageComponentInteractionData>;
Expand All @@ -25,7 +25,7 @@ pub struct Ctx<T> {
responded: bool,
}

type TwResult = Result<Response<Message>, twilight_http::Error>;
type TwResult = StarboardResult<Response<Message>>;

impl<T> Ctx<T> {
pub fn new(shard_id: u64, bot: Arc<StarboardBot>, interaction: Interaction, data: T) -> Self {
Expand Down Expand Up @@ -60,16 +60,16 @@ impl<T> Ctx<T> {
followup = followup.allowed_mentions(Some(mentions));
}
if let Some(attachments) = &data.attachments {
followup = followup.attachments(attachments).unwrap();
followup = followup.attachments(attachments)?;
}
if let Some(components) = &data.components {
followup = followup.components(components).unwrap();
followup = followup.components(components)?;
}
if let Some(content) = &data.content {
followup = followup.content(content).unwrap();
followup = followup.content(content)?;
}
if let Some(embeds) = &data.embeds {
followup = followup.embeds(embeds).unwrap();
followup = followup.embeds(embeds)?;
}
if let Some(flags) = data.flags {
followup = followup.flags(flags);
Expand All @@ -78,7 +78,7 @@ impl<T> Ctx<T> {
followup = followup.tts(tts);
}

followup.await
followup.await.map_err(|e| e.into())
} else {
i.create_response(
self.interaction.id,
Expand All @@ -89,7 +89,9 @@ impl<T> Ctx<T> {

self.responded = true;

i.response(&self.interaction.token).await
i.response(&self.interaction.token)
.await
.map_err(|e| e.into())
}
}

Expand Down
9 changes: 3 additions & 6 deletions src/owner/commands/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ pub async fn run_sql(
let ret = bot
.http
.update_message(channel_id, to_edit)
.content(Some(&final_result))
.unwrap()
.content(Some(&final_result))?
.await;

if ret.is_ok() {
Expand All @@ -117,13 +116,11 @@ pub async fn run_sql(
let msg = bot
.http
.create_message(channel_id)
.content(&final_result)
.unwrap()
.content(&final_result)?
.reply(message_id)
.await?
.model()
.await
.unwrap();
.await?;

bot.cache.responses.insert(message_id, msg.id, 1).await;
bot.cache.responses.wait().await.unwrap();
Expand Down
3 changes: 1 addition & 2 deletions src/owner/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ pub async fn handle_message(
if let Err(err) = ret {
bot.http
.create_message(channel_id)
.content(&err.to_string())
.unwrap()
.content(&err.to_string())?
.await?;
}

Expand Down
10 changes: 3 additions & 7 deletions src/utils/dm.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
use twilight_http::request::channel::message::CreateMessage;
use twilight_model::id::{marker::UserMarker, Id};

use crate::client::bot::StarboardBot;
use crate::{client::bot::StarboardBot, errors::StarboardResult};

pub async fn dm(
bot: &StarboardBot,
user_id: Id<UserMarker>,
) -> Result<CreateMessage, twilight_http::Error> {
pub async fn dm(bot: &StarboardBot, user_id: Id<UserMarker>) -> StarboardResult<CreateMessage> {
let dm_channel = bot
.http
.create_private_channel(user_id)
.await?
.model()
.await
.unwrap()
.await?
.id;
Ok(bot.http.create_message(dm_channel))
}
Loading