From d0f4c5c0af0b60bccbe1618c0fab0fec0f0d4140 Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Thu, 18 Jun 2020 01:38:33 +0200 Subject: properly pass on error from post_link This makes discord::post_link return any Error (or well, Result) that is produced by the ready event handler. --- src/discord.rs | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/discord.rs b/src/discord.rs index 1ad60d5..4f946bc 100644 --- a/src/discord.rs +++ b/src/discord.rs @@ -19,6 +19,12 @@ impl TypeMapKey for ShardManagerContainer { type Value = Arc>; } +struct PostLinkResult; + +impl TypeMapKey for PostLinkResult { + type Value = Result<()>; +} + #[derive(Debug, Clone)] struct Handler { channel_id: u64, @@ -26,28 +32,36 @@ struct Handler { link: String, } -impl EventHandler for Handler { - fn ready(&self, ctx: Context, _ready: serenity::model::gateway::Ready) { - info!("Discord client is ready"); - let mut messages = ChannelId(self.channel_id) - .messages(&ctx, |r| r.limit(25)) - .unwrap(); +impl Handler { + fn do_link_update(&self, ctx: &Context) -> Result<()> { + let mut messages = ChannelId(self.channel_id).messages(&ctx, |r| r.limit(25))?; messages.sort_by_key(|m| m.timestamp); messages.retain(|m| { - m.is_own(&ctx) + m.is_own(ctx) && Utc::now().signed_duration_since(m.timestamp) < chrono::Duration::hours(MAX_HOURS) }); if let Some(mut m) = messages.pop() { let new_text = insert_link(&m.content, &self.log, &self.link); - m.edit(&ctx, |m| m.content(new_text)).unwrap(); + m.edit(ctx, |m| m.content(new_text))?; } else { let new_text = insert_link("", &self.log, &self.link); - ChannelId(self.channel_id).say(&ctx, new_text).unwrap(); + ChannelId(self.channel_id).say(ctx, new_text)?; } - let data = ctx.data.read(); + Ok(()) + } +} + +impl EventHandler for Handler { + fn ready(&self, ctx: Context, _ready: serenity::model::gateway::Ready) { + info!("Discord client is ready"); + + let result = self.do_link_update(&ctx); + + let mut data = ctx.data.write(); + data.insert::(result); if let Some(manager) = data.get::() { manager.lock().shutdown_all(); } @@ -68,7 +82,9 @@ pub fn post_link(discord_token: &str, channel_id: u64, log: Log, link: String) - data.insert::(Arc::clone(&client.shard_manager)); } client.start()?; - Ok(()) + + let mut data = client.data.write(); + data.remove::().unwrap_or(Ok(())) } fn find_insertion(text: &str, category: &str) -> Option { -- cgit v1.2.3