Skip to content

Commit

Permalink
chore: bump deps; implement chombo ranking limit
Browse files Browse the repository at this point in the history
  • Loading branch information
m4tx committed Jan 14, 2024
1 parent 1f8c1f5 commit 6b3d4de
Show file tree
Hide file tree
Showing 14 changed files with 746 additions and 591 deletions.
1,167 changes: 652 additions & 515 deletions Cargo.lock

Large diffs are not rendered by default.

28 changes: 14 additions & 14 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@ codegen-units = 1
lto = true

[workspace.dependencies]
anyhow = "1.0.75"
async-trait = "0.1.74"
chrono = { version = "0.4.28", features = ["serde"] }
image = { version = "0.24.7", default-features = false, features = ["png"] }
reqwest = "0.11.22"
riichi_hand = "0.6.0"
scraper = "0.17.1"
serde = "1.0.190"
tokio = { version = "1.33.0", features = ["macros", "rt-multi-thread"] }
slug = "0.1.4"
clap = { version = "4.4.7", features = ["derive", "env"] }
env_logger = "0.10.0"
anyhow = "1.0.79"
async-trait = "0.1.77"
chrono = { version = "0.4.31", features = ["serde"] }
image = { version = "0.24.8", default-features = false, features = ["png"] }
reqwest = { version = "0.11.23", features = ["json"] }
riichi_hand = "0.6.1"
scraper = "0.18.1"
serde = "1.0.195"
tokio = { version = "1.35.1", features = ["macros", "rt-multi-thread"] }
slug = "0.1.5"
clap = { version = "4.4.16", features = ["derive", "env"] }
env_logger = "0.10.1"
log = "0.4.20"
num-bigint = "0.4.4"
itertools = "0.11.0"
poise = "0.5.7"
itertools = "0.12.0"
poise = "0.6.1"
1 change: 1 addition & 0 deletions chombot-common/src/data.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub const DISCORD_MESSAGE_SIZE_LIMIT: usize = 2000;
pub const DISCORD_EMBED_FIELD_LIMIT: usize = 25;
8 changes: 5 additions & 3 deletions chombot-common/src/discord_utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use poise::serenity_prelude::{ChannelId, Context, Error as SerenityError};
use poise::serenity_prelude::{ChannelId, Context, CreateMessage, Error as SerenityError};

use crate::data::DISCORD_MESSAGE_SIZE_LIMIT;

Expand All @@ -11,7 +11,7 @@ pub async fn send_with_overflow(
for line in text.lines() {
if message.len() + line.len() + "\n".len() > DISCORD_MESSAGE_SIZE_LIMIT {
channel_id
.send_message(ctx, |m| m.content(&message))
.send_message(ctx, CreateMessage::new().content(&message))
.await?;
message.clear();
}
Expand All @@ -20,7 +20,9 @@ pub async fn send_with_overflow(
message.push('\n');
}
if !message.is_empty() {
channel_id.send_message(ctx, |m| m.content(message)).await?;
channel_id
.send_message(ctx, CreateMessage::new().content(&message))
.await?;
}

Ok(())
Expand Down
6 changes: 3 additions & 3 deletions chombot-common/src/slash_commands/hand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::io::Cursor;

use anyhow::Result;
use image::DynamicImage;
use poise::serenity_prelude::AttachmentType;
use poise::serenity_prelude::{CreateAttachment, CreateMessage};
use poise::ChoiceParameter;

use crate::chombot::{ChombotBase, TileStyle};
Expand Down Expand Up @@ -50,9 +50,9 @@ pub async fn hand<T: ChombotPoiseUserData>(
DynamicImage::ImageRgba8(image)
.write_to(&mut Cursor::new(&mut buf), image::ImageOutputFormat::Png)?;

let files: Vec<AttachmentType> = vec![(buf.as_slice(), "hand.png").into()];
let files: Vec<CreateAttachment> = vec![CreateAttachment::bytes(buf.as_slice(), "hand.png")];
ctx.channel_id()
.send_files(&ctx.http(), files, |m| m)
.send_files(&ctx.http(), files, CreateMessage::new())
.await?;

ctx.say("<:Ichiwink:591396074141515776>").await?;
Expand Down
9 changes: 4 additions & 5 deletions chombot-common/src/slash_commands/score.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use anyhow::Result;
use log::info;
use num_bigint::BigInt;
use poise::serenity_prelude::{Color, CreateEmbed};
use poise::ChoiceParameter;
use poise::{ChoiceParameter, CreateReply};
use riichi_hand::points::{Fu, Han, Honbas, PointsCalculationMode, PointsCustom};

use crate::{ChombotPoiseContext, ChombotPoiseUserData};
Expand Down Expand Up @@ -58,20 +58,19 @@ pub async fn score<T: ChombotPoiseUserData>(
let points = Points::from_calculated(points_calculation_mode, han, fu, honbas)?;
let fields = create_points_embed_fields(&points);

ctx.send(|reply| reply.embed(move |embed| create_points_embed(embed, han, fu, honbas, fields)))
ctx.send(CreateReply::default().embed(create_points_embed(han, fu, honbas, fields)))
.await?;

Ok(())
}

fn create_points_embed(
embed: &mut CreateEmbed,
han: Han,
fu: Fu,
honbas: Honbas,
fields: impl Iterator<Item = (&'static str, String, bool)>,
) -> &mut CreateEmbed {
embed
) -> CreateEmbed {
CreateEmbed::new()
.title(format!("**{han} {fu} {honbas}**"))
.color(Color::DARK_GREEN)
.fields(fields)
Expand Down
24 changes: 15 additions & 9 deletions chombot-kcc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ use chombot_common::slash_commands::score::score;
use chombot_common::{start_tournaments_watcher, ChombotPoiseUserData};
use clap::Parser;
use log::{error, info, LevelFilter};
use poise::serenity_prelude::{ChannelId, Context as SerenityContext, GatewayIntents};
use poise::{BoxFuture, Command, Context, Event, Framework, FrameworkContext, FrameworkOptions};
use poise::serenity_prelude::{
ChannelId, ClientBuilder, Context as SerenityContext, FullEvent, GatewayIntents,
};
use poise::{BoxFuture, Command, Context, Framework, FrameworkContext, FrameworkOptions};

use crate::args::Arguments;
use crate::chombot::Chombot;
Expand Down Expand Up @@ -49,7 +51,7 @@ fn start_ranking_watcher(ranking_watcher_channel_id: Option<u64>, ctx: SerenityC
let ranking_watcher_channel_id = ranking_watcher_channel_id
.expect("Ranking watcher feature enabled but no channel ID provided");
let notifier = ChannelMessageNotifier::new(
ChannelId(ranking_watcher_channel_id),
ChannelId::new(ranking_watcher_channel_id),
String::from("https://ranking.cvgo.re/ ranking update"),
);
tokio::spawn(async move {
Expand All @@ -74,11 +76,11 @@ fn get_kcc3_client(args: &Arguments) -> Kcc3ClientResult<Option<kcc3::Kcc3Client

fn event_handler<'a>(
ctx: &'a SerenityContext,
event: &'a Event<'a>,
event: &'a FullEvent,
_framework_ctx: FrameworkContext<'a, PoiseUserData, Error>,
_user_data: &'a PoiseUserData,
) -> BoxFuture<'a, anyhow::Result<()>> {
if let Event::Message { new_message } = event {
if let FullEvent::Message { new_message } = event {
return Box::pin(async move {
if !new_message.mention_everyone {
return Ok(());
Expand Down Expand Up @@ -133,8 +135,6 @@ async fn main() {
event_handler,
..Default::default()
})
.token(&args.discord_token)
.intents(GatewayIntents::non_privileged())
.setup(move |ctx, ready, framework| {
Box::pin(async move {
if args.feature_ranking_watcher {
Expand All @@ -154,9 +154,15 @@ async fn main() {
kcc_chombot,
})
})
});
})
.build();

let mut client = ClientBuilder::new(&args.discord_token, GatewayIntents::non_privileged())
.framework(framework)
.await
.expect("Could not create client");

if let Err(why) = framework.run().await {
if let Err(why) = client.start().await {
error!("Client error: {why:?}");
}
}
2 changes: 1 addition & 1 deletion chombot-kcc/src/ranking_watcher/notifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ mod tests {

#[test]
fn test_channel_message_notifier_build_message() {
let notifier = ChannelMessageNotifier::new(ChannelId(123), "TEST_MESSAGE".into());
let notifier = ChannelMessageNotifier::new(ChannelId::new(123), "TEST_MESSAGE".into());
let ranking = Ranking(vec![
RankingEntry {
pos: 1,
Expand Down
35 changes: 17 additions & 18 deletions chombot-kcc/src/slash_commands/chombo.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use anyhow::Result;
use chombot_common::data::DISCORD_MESSAGE_SIZE_LIMIT;
use poise::serenity_prelude::{Color, CreateEmbed, User};
use chombot_common::data::{DISCORD_EMBED_FIELD_LIMIT, DISCORD_MESSAGE_SIZE_LIMIT};
use poise::serenity_prelude::{Color, CreateAllowedMentions, CreateEmbed, User};
use poise::CreateReply;
use slug::slugify;

use crate::chombot::Chombot;
Expand All @@ -18,7 +19,7 @@ pub async fn chombo(_: PoiseContext<'_>) -> Result<()> {
async fn ranking(ctx: PoiseContext<'_>) -> Result<()> {
let entries = get_chombos_embed_entries(&ctx.data().kcc_chombot).await?;

ctx.send(|response| response.embed(|embed| create_chombos_embed(embed, entries)))
ctx.send(CreateReply::default().embed(create_chombos_embed(entries)))
.await?;

Ok(())
Expand All @@ -29,11 +30,11 @@ async fn ranking(ctx: PoiseContext<'_>) -> Result<()> {
async fn list(ctx: PoiseContext<'_>) -> Result<()> {
let chombos = create_chombos_list(&ctx.data().kcc_chombot).await?;

ctx.send(|response| {
response
ctx.send(
CreateReply::default()
.content(chombos)
.allowed_mentions(|mentions| mentions.empty_parse())
})
.allowed_mentions(CreateAllowedMentions::new().empty_users().empty_roles()),
)
.await?;

Ok(())
Expand Down Expand Up @@ -64,30 +65,28 @@ async fn add(
let message_content = format_add_message(&user, &description);
let entries = get_chombos_embed_entries(chombot).await?;

ctx.send(|response| {
response
ctx.send(
CreateReply::default()
.content(message_content)
.embed(|embed| create_chombos_embed(embed, entries))
})
.embed(create_chombos_embed(entries)),
)
.await?;

Ok(())
}

async fn get_chombos_embed_entries(
chombot: &Chombot,
) -> Result<impl Iterator<Item = (String, usize, bool)>> {
) -> Result<impl Iterator<Item = (String, String, bool)>> {
let chombo_ranking = chombot.create_chombo_ranking().await?;
Ok(chombo_ranking
.into_iter()
.map(|(player, num)| (player.short_name(), num, true)))
.take(DISCORD_EMBED_FIELD_LIMIT)
.map(|(player, num)| (player.short_name(), num.to_string(), true)))
}

fn create_chombos_embed(
embed: &mut CreateEmbed,
entries: impl Iterator<Item = (String, usize, bool)>,
) -> &mut CreateEmbed {
embed
fn create_chombos_embed(entries: impl Iterator<Item = (String, String, bool)>) -> CreateEmbed {
CreateEmbed::new()
.title("**CHOMBO COUNTER**")
.color(Color::RED)
.thumbnail("https://cdn.discordapp.com/attachments/591385176685281293/597292309792686090/1562356453777.png")
Expand Down
4 changes: 2 additions & 2 deletions chombot-kcc/src/slash_commands/pasta/command.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::Result;
use chombot_common::data::DISCORD_MESSAGE_SIZE_LIMIT;
use poise::serenity_prelude::CacheHttp;
use poise::serenity_prelude::{CacheHttp, CreateMessage};
use poise::ChoiceParameter;

use crate::PoiseContext;
Expand Down Expand Up @@ -64,7 +64,7 @@ async fn send_pasta_slice(ctx: &PoiseContext<'_>, message: &str, first: &mut boo
ctx.say(message).await?;
} else {
ctx.channel_id()
.send_message(&ctx.http(), |m| m.content(message))
.send_message(&ctx.http(), CreateMessage::new().content(message))
.await?;
}

Expand Down
4 changes: 2 additions & 2 deletions chombot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ env_logger.workspace = true
num-bigint.workspace = true
itertools.workspace = true
poise.workspace = true
toml = "0.8.6"
toml = "0.8.8"
chombot-common = { path = "../chombot-common" }

[dev-dependencies]
tempfile = "3.8.1"
tempfile = "3.9.0"
20 changes: 10 additions & 10 deletions chombot/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,15 +133,15 @@ mod tests {
let config = Config {
guilds: HashMap::from([
(
GuildId(69),
GuildId::new(69),
GuildConfig {
tournaments_watcher_channel_id: Some(ChannelId(2137)),
tournaments_watcher_channel_id: Some(ChannelId::new(2137)),
},
),
(
GuildId(420),
GuildId::new(420),
GuildConfig {
tournaments_watcher_channel_id: Some(ChannelId(69)),
tournaments_watcher_channel_id: Some(ChannelId::new(69)),
},
),
]),
Expand All @@ -168,24 +168,24 @@ mod tests {
let config = Config {
guilds: HashMap::from([
(
GuildId(69),
GuildId::new(69),
GuildConfig {
tournaments_watcher_channel_id: Some(ChannelId(2137)),
tournaments_watcher_channel_id: Some(ChannelId::new(2137)),
},
),
(
GuildId(420),
GuildId::new(420),
GuildConfig {
tournaments_watcher_channel_id: Some(ChannelId(69)),
tournaments_watcher_channel_id: Some(ChannelId::new(69)),
},
),
]),
};

let channel_ids: Vec<ChannelId> = vec![ChannelId(69), ChannelId(2137)];
let channel_ids: Vec<ChannelId> = vec![ChannelId::new(69), ChannelId::new(2137)];

{
let chombot_config = ChombotConfig::new(path.to_path_buf(), config.clone());
let chombot_config = ChombotConfig::new(path.to_path_buf(), config);
let mut ids = tokio::runtime::Builder::new_current_thread()
.build()?
.block_on(async { chombot_config.tournament_watcher_channels().await });
Expand Down
14 changes: 9 additions & 5 deletions chombot/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use chombot_common::slash_commands::score::score;
use chombot_common::{start_tournaments_watcher, ChombotPoiseUserData};
use clap::Parser;
use log::{error, info, LevelFilter};
use poise::serenity_prelude::GatewayIntents;
use poise::serenity_prelude::{ClientBuilder, GatewayIntents};
use poise::{Command, Context, Framework, FrameworkOptions};
use tokio::sync::RwLock;

Expand Down Expand Up @@ -61,8 +61,6 @@ async fn main() {
commands: get_command_list(),
..Default::default()
})
.token(&args.discord_token)
.intents(GatewayIntents::non_privileged())
.setup(move |ctx, ready, framework| {
Box::pin(async move {
start_tournaments_watcher(config_ref.clone(), ctx.clone());
Expand All @@ -73,9 +71,15 @@ async fn main() {
config: config_ref,
})
})
});
})
.build();

let mut client = ClientBuilder::new(&args.discord_token, GatewayIntents::non_privileged())
.framework(framework)
.await
.expect("Could not create client");

if let Err(why) = framework.run().await {
if let Err(why) = client.start().await {
error!("Client error: {why:?}");
}
}
Loading

0 comments on commit 6b3d4de

Please sign in to comment.