Skip to content

Commit

Permalink
slightly change structure for status grid, add 2x2 activity info, reo…
Browse files Browse the repository at this point in the history
…rder fields

Signed-off-by: Miezhiko <Miezhiko@gmail.com>
  • Loading branch information
Miezhiko committed Apr 22, 2022
1 parent 6adbfa6 commit 4e664c1
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 51 deletions.
2 changes: 1 addition & 1 deletion Amadeus/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "amadeus"
version = "9.1.9"
version = "9.1.10"
authors = [ "Miezhiko" ]
repository = "https://github.com/Miezhiko/Amadeus"
readme = "README.md"
Expand Down
45 changes: 25 additions & 20 deletions Amadeus/src/commands/w3c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -712,36 +712,34 @@ async fn vs(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
Ok(())
}

#[command]
#[description("Show popular hours on W3C")]
async fn popularhours(ctx: &Context, msg: &Message) -> CommandResult {
pub async fn generate_popularhours(ctx: &Context) -> anyhow::Result<Option<String>> {
let rqcl = {
set!{ data = ctx.data.read().await
, rqcl = data.get::<ReqwestClient>().unwrap() };
rqcl.clone()
};
let mut popular_games_image: Option<String> = None;
if let Ok(res3) = rqcl.get(format!("{W3C_API}/w3c-stats/play-hours")).send().await {
if let Ok(ph_modes) = res3.json::<Vec<PopularHours>>().await {
info!("got popular hours structure");
for ph in ph_modes {
if ph.gameMode == 2 {
let max_games = ph.playTimePerHour.iter().fold(0, |a, b| b.games.max(a));
let fname_popular_hours = format!("popular_hours_{}.png", ph.day);
let mut popular_games_image: Option<String> = None;
{ // because of Rc < > in BitMapBackend I need own scope here
let root_area = BitMapBackend::new(&fname_popular_hours, (1024, 768)).into_drawing_area();
let root_area = BitMapBackend::new(&fname_popular_hours, (1024, 384)).into_drawing_area();
root_area.fill(&RGBColor(47, 49, 54))?;
let mut cc = ChartBuilder::on(&root_area)
.margin(5)
.set_all_label_area_size(50)
.build_cartesian_2d(0.0..24 as f64, 0.0..max_games as f64)?;
.build_cartesian_2d(0.0..24_f64, 0.0..max_games as f64)?;
cc.configure_mesh()
.label_style(("monospace", 16).into_font().color(&RGBColor(150, 150, 150)))
.y_labels(10)
.axis_style(&RGBColor(80, 80, 80))
.draw()?;
let color = RGBColor(100, 20, 250);
let style = ShapeStyle::from(color);
let color = RGBColor(180, 120, 255);
let style: ShapeStyle = ShapeStyle::from(color);
let plx = ph.playTimePerHour.iter().map(|p| {
(p.hours as f64 + (p.minutes as f64 / 64f64), p.games as f64)
}).collect::<Vec<(f64, f64)>>();
Expand All @@ -766,16 +764,6 @@ async fn popularhours(ctx: &Context, msg: &Message) -> CommandResult {
error!("Failed to download and post stream img {why}");
}
};
if let Some(img) = popular_games_image {
let footer = format!("Requested by {}", msg.author.name);
msg.channel_id.send_message(ctx, |m| m.content("")
.embed(|e|
e.color((40, 20, 200))
.title("2x2 popular hours")
.image(img)
.footer(|f| f.text(&footer))
)).await?;
}
}
}
} else {
Expand All @@ -784,8 +772,25 @@ async fn popularhours(ctx: &Context, msg: &Message) -> CommandResult {
} else {
error!("no rsponse from w3c");
}
if let Err(why) = msg.delete(&ctx).await {
error!("Error deleting original command, {why}");
Ok(popular_games_image)
}

#[command]
#[description("Show popular hours on W3C")]
async fn popularhours(ctx: &Context, msg: &Message) -> CommandResult {
let popular_games_image = generate_popularhours(ctx).await;
if let Some(img) = popular_games_image? {
let footer = format!("Requested by {}", msg.author.name);
msg.channel_id.send_message(ctx, |m| m.content("")
.embed(|e|
e.color((40, 20, 200))
.title("2x2 popular hours")
.image(img)
.footer(|f| f.text(&footer))
)).await?;
if let Err(why) = msg.delete(&ctx).await {
error!("Error deleting original command, {why}");
}
}
Ok(())
}
2 changes: 1 addition & 1 deletion Amadeus/src/steins/warcraft/poller/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ pub async fn check<'a>( ctx: &Context
GameMode::Team2 => false,
GameMode::Team4 => false
};
if let Err(why) = add_to_weekly(pws, *is_win, is_solo).await {
if let Err(why) = add_to_weekly(ctx, pws, *is_win, is_solo).await {
error!("Failed to add daily stats: {why}");
}
if *is_win {
Expand Down
63 changes: 35 additions & 28 deletions Amadeus/src/steins/warcraft/status.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::{
types::tracking::{ W3CStats, GameMode },
common::constants::{ W3C_STATS_ROOM, W3C_STATS_MSG },
steins::warcraft::poller::GAMES
steins::warcraft::poller::GAMES,
commands::w3c::generate_popularhours
};

use chrono::{
Expand All @@ -26,20 +27,21 @@ type WeeklyStats = BTreeMap<String, WeeklyWinLoses>;
pub struct Weekly {
pub reset_week: u32,
pub statistics: WeeklyStats,
pub statistics2: WeeklyStats
pub statistics2: WeeklyStats,
pub popular_hours: String
}

pub async fn get_weekly() -> anyhow::Result<Weekly> {
pub async fn get_weekly(ctx: &Context) -> anyhow::Result<Weekly> {
if !std::path::Path::new(WEEKLY_STATS_FNAME).exists() {
clear_weekly(chrono::Utc::now().iso_week().week()).await?;
clear_weekly(ctx, chrono::Utc::now().iso_week().week()).await?;
}
let contents = fs::read_to_string(WEEKLY_STATS_FNAME).await?;
let yml = serde_yaml::from_str(&contents)?;
Ok(yml)
}

pub async fn add_to_weekly(p: &str, win: bool, solo: bool) -> anyhow::Result<()> {
let mut current_weekly = get_weekly().await?;
pub async fn add_to_weekly(ctx: &Context, p: &str, win: bool, solo: bool) -> anyhow::Result<()> {
let mut current_weekly = get_weekly(ctx).await?;
let weekly_stats: &mut WeeklyStats =
if solo { &mut current_weekly.statistics }
else { &mut current_weekly.statistics2 };
Expand All @@ -61,11 +63,18 @@ pub async fn add_to_weekly(p: &str, win: bool, solo: bool) -> anyhow::Result<()>
Ok(())
}

async fn clear_weekly(week: u32) -> anyhow::Result<()> {
async fn clear_weekly(ctx: &Context, week: u32) -> anyhow::Result<()> {
let poplar_hours =
if let Some(generated_image) = generate_popularhours(ctx).await? {
generated_image
} else {
"https://vignette.wikia.nocookie.net/steins-gate/images/8/83/Kurisu_profile.png".to_string()
};
let init = Weekly {
reset_week: week,
statistics: BTreeMap::new(),
statistics2: BTreeMap::new()
statistics2: BTreeMap::new(),
popular_hours: poplar_hours
};
let yml = serde_yaml::to_string(&init)?;
fs::write(WEEKLY_STATS_FNAME, yml).await?;
Expand All @@ -74,13 +83,13 @@ async fn clear_weekly(week: u32) -> anyhow::Result<()> {

pub async fn status_update(ctx: &Context, stats: &W3CStats) -> anyhow::Result<()> {
if let Ok(mut statusmsg) = W3C_STATS_ROOM.message(ctx, W3C_STATS_MSG).await {
let weekly = get_weekly().await?;
let weekly = get_weekly(ctx).await?;
let now = chrono::Utc::now();
// only check on midnight (just because)
if now.hour() == 0 {
let now_week = now.iso_week().week();
if now_week != weekly.reset_week {
clear_weekly(now_week).await?;
clear_weekly(ctx, now_week).await?;
}
}

Expand All @@ -98,7 +107,7 @@ pub async fn status_update(ctx: &Context, stats: &W3CStats) -> anyhow::Result<()
GameMode::Team4 => "4x4"
};
tracking_info.push(
format!("{} playing {} game for {} minutes"
format!("{} play {} for {} mins"
, name
, game_mode_str
, game.passed_time)
Expand All @@ -124,7 +133,7 @@ pub async fn status_update(ctx: &Context, stats: &W3CStats) -> anyhow::Result<()
.collect::<Vec<&str>>()[0];
let winrate = ( (d.wins as f32 / (d.wins + d.losses) as f32) * 100.0).round();
weekly_vec.push(
format!( "{}: {} wins, {} losses, {}%"
format!( "{}: {}W, {}L, {}%"
, name
, d.wins
, d.losses
Expand All @@ -137,40 +146,38 @@ pub async fn status_update(ctx: &Context, stats: &W3CStats) -> anyhow::Result<()
}
let stats_str = format!(
"
__**weekly solo:**__
```
{}
```
__**weekly team games:**__
```
{}
```
__**currently running:**__
```
SOLO GAMES: {}
2x2 GAMES: {}
4x4 GAMES: {}
```
__**currently playing:**__
```
{}
```
__**weekly solo:**__
```
{}
```
__**weekly team games:**__
```
{}
```"
__**2x2 popular hours:**__"
, weekly_str[0]
, weekly_str[1]
, stats.games_solo
, stats.games_2x2
, stats.games_4x4
, tracking_str
, weekly_str[0]
, weekly_str[1]);
, tracking_str);
statusmsg.edit(ctx, |m| m.content("")
.embed(|e|
e.color((255, 20, 7))
.title("☥ Status Grid")
.title("Warcraft III Activity ☥ Status Grid")
.description(stats_str)
.thumbnail("https://vignette.wikia.nocookie.net/steins-gate/images/0/07/Amadeuslogo.png")
/*.image("https://vignette.wikia.nocookie.net/steins-gate/images/8/83/Kurisu_profile.png")*/
.image(weekly.popular_hours)
.timestamp(now.to_rfc3339())
)).await?;
}
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions aka.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"DeMiGoD#2105": DeMiGoD
"DeXmXz#2768": ~
"Debaser#1788": Debaser
"Deornoth#1779": ~
"DesTrr0#2165": ~
"Despot#21177": Despot
"Destroyer#111986": DestroyeR
Expand Down Expand Up @@ -98,6 +99,7 @@
"MagicMango#21559": ~
"Manquepierda#2654": ~
"Maxxiko#2671": ~
"Meda#1778": Rudan
"MediK#21818": ~
"Melkach#2717": Melkach
"MightyWonka#2298": ~
Expand Down

0 comments on commit 4e664c1

Please sign in to comment.