Reduce hits to the imgur api

+ Cache all album states locally
+ State is periodically updated
+ Also can be updated via command
+ Clippy + fmt
This commit is contained in:
2022-12-10 18:43:47 -07:00
parent 73be6b1d9f
commit 357c1f069a
7 changed files with 151 additions and 85 deletions
+22
View File
@@ -0,0 +1,22 @@
use crate::{command, group, GlobalData};
use serenity::client::Context;
use serenity::framework::standard::{Args, CommandResult};
use serenity::model::channel::Message;
#[group]
#[commands(reload)]
pub struct ADMIN;
#[command]
#[owners_only]
#[only_in(guilds)]
async fn reload(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
let mut data = ctx.data.write().await;
let global_data = data.get_mut::<GlobalData>().unwrap();
global_data.reload().await?;
msg.reply(&ctx.http, "Reload done ;)").await?;
Ok(())
}
+26 -31
View File
@@ -1,6 +1,6 @@
use crate::config::AlbumConfig;
use crate::error::Error;
use crate::{command, group, imgur, GlobalData};
use crate::{command, group, GlobalData};
use serenity::client::Context;
use serenity::framework::standard::{Args, CommandResult};
use serenity::model::channel::Message;
@@ -38,19 +38,29 @@ async fn add_album(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul
let global_data = data.get_mut::<GlobalData>().unwrap();
let old_config = global_data.cfg.clone();
global_data.cfg.albums.push(AlbumConfig {
album_id,
name: album_name.clone(),
});
global_data
.cfg
.save(&global_data.args.cfg_path)
.await
.unwrap();
global_data.cfg.save(&global_data.args.cfg_path).await?;
msg.reply(&ctx.http, format!("{} album added!", album_name))
if global_data.reload().await.is_err() {
global_data.cfg = old_config;
global_data.cfg.save(&global_data.args.cfg_path).await?;
msg.reply(
&ctx.http,
"Error adding album, check your link and try again",
)
.await?;
} else {
msg.reply(&ctx.http, format!("{} album added!", album_name))
.await?;
}
Ok(())
}
@@ -72,11 +82,9 @@ async fn remove_album(ctx: &Context, msg: &Message, args: Args) -> CommandResult
.albums
.retain(|album| !album.name.eq_ignore_ascii_case(&album_name));
global_data
.cfg
.save(&global_data.args.cfg_path)
.await
.unwrap();
global_data.cfg.save(&global_data.args.cfg_path).await?;
global_data.reload().await?;
msg.reply(&ctx.http, format!("{} album removed!", album_name))
.await?;
@@ -123,25 +131,12 @@ pub async fn parse_album(
let data = ctx.data.read().await;
let global_data = data.get::<GlobalData>().unwrap();
let album = global_data
.cfg
.albums
.iter()
.find(|album| album.name.to_lowercase() == album_name);
if let Some(album) = album {
match imgur::get_image(album, global_data, tags).await {
Ok(image) => {
if let Some(image) = image {
msg.reply(&ctx.http, &image.link).await?;
} else {
msg.reply(&ctx.http, "No image found ;(").await?;
}
}
Err(_) => {
msg.reply(&ctx.http, "Unable to get album, try again later.")
.await?;
}
match global_data.bot_state.get_image(album_name, tags) {
Some(image) => {
msg.reply(&ctx.http, &image.link).await?;
}
None => {
msg.reply(&ctx.http, "No image ;(").await?;
}
};
+1 -2
View File
@@ -1,5 +1,4 @@
use crate::error::Error;
use crate::imgur::get_image;
use crate::{command, group, GlobalData};
use rand::prelude::IteratorRandom;
use rand::thread_rng;
@@ -55,7 +54,7 @@ impl FortuneCtx {
let mut random_image: HashMap<String, String> = HashMap::new();
for album in &global_data.cfg.albums {
let image = get_image(album, global_data, Vec::new()).await?;
let image = global_data.bot_state.get_image(&album.name, Vec::new());
if let Some(image) = image {
random_image.insert(album.name.clone(), image.link);
+18 -1
View File
@@ -1,3 +1,4 @@
pub mod admin;
pub mod album;
pub mod celeryman;
pub mod color;
@@ -11,9 +12,10 @@ use serenity::framework::standard::{
};
use serenity::model::channel::Message;
use serenity::model::id::UserId;
use serenity::model::prelude::Ready;
use serenity::model::prelude::{GuildId, Ready};
use serenity::prelude::EventHandler;
use std::collections::HashSet;
use std::time::Duration;
pub struct Handler;
@@ -23,6 +25,21 @@ static ERROR_MSG: &str =
#[async_trait]
impl EventHandler for Handler {
async fn cache_ready(&self, ctx: Context, _guilds: Vec<GuildId>) {
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(60 * 60)).await;
{
println!("Reloading config...");
let mut data = ctx.data.write().await;
let global_data = data.get_mut::<GlobalData>().unwrap();
global_data.reload().await.unwrap();
}
}
});
}
async fn message(&self, ctx: Context, new_message: Message) {
if new_message.author.bot {
return;