Compare commits

..

4 Commits

10 changed files with 1070 additions and 214 deletions

3
.env.example Normal file
View File

@ -0,0 +1,3 @@
DISCORD_TOKEN=
LASTFM_API_KEY=
DATABASE_URL=sqlite:watcat.db

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
/target /target
/.env /.env
/watcat.db*

4
.gitmodules vendored Normal file
View File

@ -0,0 +1,4 @@
[submodule "magick-rust"]
path = magick-rust
url = https://git.starbit.dev/seoxi/magick-rust
branch = sr

926
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,18 @@ edition = "2024"
[dependencies] [dependencies]
serenity = "0.12" serenity = "0.12"
tokio = { version = "1.21.2", features = ["macros", "rt-multi-thread"] }
dotenv = "0.15.0"
lastfm = "0.10.0" lastfm = "0.10.0"
magick_rust = "1.0.0" #{ path = "../magick-rust" }
[dependencies.magick_rust]
path = "./magick-rust"
[dependencies.dotenvy]
version = "0.15.7"
[dependencies.tokio]
version = "1.21.2"
features = ["macros", "rt-multi-thread"]
[dependencies.sqlx]
version = "0.8.5"
features = ["sqlite", "runtime-tokio"]

View File

@ -8,9 +8,19 @@ why?
cosmo relies on [imagetext-py](https://github.com/nathanielfernandes/imagetext-py), which either does not have a freebsd wheel or else uv cannot find it cosmo relies on [imagetext-py](https://github.com/nathanielfernandes/imagetext-py), which either does not have a freebsd wheel or else uv cannot find it
also I'm a rust shill and python hater and just needed an excuse ~~also I'm a rust shill and python hater and just needed an excuse~~
but your code sucks but your code sucks
------------------- -------------------
I'm trying, okay? I'm trying, okay?
running
-------
populate .env with necessary values. a template .env.example is given
create the database ``sqlx database create``
(note: make sure you have sqlx installed first)
init the database ``sqlx migrate run``

1
magick-rust Submodule

Submodule magick-rust added at 5fbc506983

BIN
mask.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1008 B

View File

@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS users
(
discord_userid INTEGER PRIMARY KEY NOT NULL,
lastfm_username TEXT NOT NULL
) STRICT;

View File

@ -1,33 +1,37 @@
extern crate dotenvy;
extern crate lastfm; extern crate lastfm;
use dotenv::dotenv;
use serenity::async_trait; use serenity::async_trait;
use serenity::model::channel::Message;
use serenity::prelude::*;
use serenity::builder::{CreateAttachment, CreateMessage}; use serenity::builder::{CreateAttachment, CreateMessage};
use serenity::model::channel::Message;
use serenity::model::id::UserId;
use serenity::prelude::*;
extern crate magick_rust; extern crate magick_rust;
use magick_rust::{magick_wand_genesis, MagickWand, PixelWand, CompositeOperator, ColorspaceType}; use magick_rust::{ColorspaceType, CompositeOperator, MagickWand, PixelWand, magick_wand_genesis};
use std::env; use std::env;
use std::sync::Once; use std::sync::Once;
extern crate sqlx;
use sqlx::sqlite::SqlitePool;
static START: Once = Once::new(); static START: Once = Once::new();
struct Handler; struct Handler;
enum Reply { enum Reply {
Image(Vec<u8>), Image(Vec<u8>),
Text(String) Text(String),
} }
macro_rules! handle_magick_result { macro_rules! handle_magick_result {
($a: expr, $b: literal) => { ($a: expr, $b: literal) => {
match $a { match $a {
Ok(_) => {}, Ok(_) => {}
Err(e) => return Reply::Text(format!("Error: {} {}", $b, e)), Err(e) => return Reply::Text(format!("Error: {} {}", $b, e)),
} }
} };
} }
macro_rules! handle_magick_option { macro_rules! handle_magick_option {
@ -36,55 +40,125 @@ macro_rules! handle_magick_option {
Some(res) => res, Some(res) => res,
None => return Reply::Text($b.to_string()), None => return Reply::Text($b.to_string()),
} }
} };
} }
async fn fmi(_arg: &str) -> Reply { #[allow(unused)]
let client = lastfm::Client::<String, &str>::from_env("seoxi"); async fn fmi(ctx: &Context, arg: &str, id: UserId) -> Reply {
let lastfm_user = match arg {
"" => get_lastfm_username(ctx, id).await,
_ => Some(arg.to_string()),
};
let client = match lastfm_user {
Some(s) => lastfm::Client::<String, String>::from_env(s),
None => return Reply::Text("No last.fm username set.".to_string()),
};
let now_playing = match client.now_playing().await { let now_playing = match client.now_playing().await {
Ok(np) => np, Ok(np) => np,
Err(e) => return Reply::Text(format!("Error: grabbing last.fm user data failed {e}")), Err(e) => return Reply::Text(format!("Error: grabbing last.fm user data failed {e}")),
}; };
if let Some(track) = now_playing { let track = match now_playing {
Some(track) => track,
None => return Reply::Text("Nothing playing.".to_string()),
};
let image_uri = match track.image.extralarge { let image_uri = match track.image.extralarge {
Some(iu) => iu, Some(iu) => iu,
None => return Reply::Text("Error: getting image uri failed".to_string()), None => return Reply::Text("Error: getting image uri failed".to_string()),
}; };
let mut base_color = PixelWand::new(); let mut base_color = PixelWand::new();
#[allow(unused_mut)] let mut white = PixelWand::new();
let mut main_wand = MagickWand::new(); let mut main_wand = MagickWand::new();
#[allow(unused_mut)]
let mut art_wand = MagickWand::new(); let mut art_wand = MagickWand::new();
//#[allow(unused_mut)]
let mut art_wand_cluster = MagickWand::new(); let mut art_wand_cluster = MagickWand::new();
let mut mask_wand = MagickWand::new();
handle_magick_result!(base_color.set_color("#7f7f7f"), "Failed to set base color"); handle_magick_result!(
handle_magick_result!(art_wand.read_image(image_uri.as_str()), "Failed to read image from uri"); base_color.set_color("#7f7f7f"),
handle_magick_result!(art_wand.transform_image_colorspace(ColorspaceType::Lab), "Failed to set art colorspace"); "Failed to set init base color"
);
handle_magick_result!(
art_wand.read_image(image_uri.as_str()),
"Failed to read image from uri"
);
handle_magick_result!(
art_wand.transform_image_colorspace(ColorspaceType::Lab),
"Failed to set art colorspace"
);
let (art_width, art_height) = (art_wand.get_image_width(), art_wand.get_image_height()); let (art_width, art_height) = (art_wand.get_image_width(), art_wand.get_image_height());
handle_magick_result!(art_wand_cluster.new_image(art_width, art_height, &base_color), "Failed to init cluster image"); handle_magick_result!(
handle_magick_result!(art_wand_cluster.compose_images(&art_wand, CompositeOperator::SrcOver, true, 0, 0), "Failed to copy onto cluster image"); art_wand_cluster.new_image(art_width, art_height, &base_color),
"Failed to init cluster image"
);
handle_magick_result!(
art_wand_cluster.compose_images(&art_wand, CompositeOperator::SrcOver, true, 0, 0),
"Failed to copy onto cluster image"
);
// least stupid way I could figure out to do this, since it seems that MagickWand::new_from_wand() doesn't work // least stupid way I could figure out to do this, since it seems that MagickWand::new_from_wand() doesn't work
handle_magick_result!(art_wand_cluster.set_image_colorspace(ColorspaceType::Lab), "Failed to set cluster colorspace"); handle_magick_result!(
handle_magick_result!(art_wand_cluster.kmeans(5, 200, 0.001), "Failed to run kmeans"); art_wand_cluster.set_image_colorspace(ColorspaceType::Lab),
let mut colors = handle_magick_option!(art_wand_cluster.get_image_histogram(), "Failed to get color histogram"); "Failed to set cluster colorspace"
println!("{}", colors.len()); );
handle_magick_result!(
art_wand_cluster.kmeans(5, 200, 0.001),
"Failed to run kmeans"
);
let mut colors = handle_magick_option!(
art_wand_cluster.get_image_histogram(),
"Failed to get color histogram"
);
colors.sort_by_cached_key(|color| -(color.get_color_count() as isize)); colors.sort_by_cached_key(|color| -(color.get_color_count() as isize));
let mut accent_color = match colors.len() {
1 => &colors[0],
_ => &colors[1],
};
handle_magick_result!(main_wand.new_image(548, 147, &colors[0]), "Failed to create wand"); handle_magick_result!(white.set_color("#ffffff"), "Failed to set init white");
handle_magick_result!(main_wand.transform_image_colorspace(ColorspaceType::Lab), "Failed to set main colorspace"); handle_magick_result!(mask_wand.read_image("mask.png"), "Failed to load mask");
handle_magick_result!(art_wand.adaptive_resize_image(124, 124), "Failed to resize art"); handle_magick_result!(
handle_magick_result!(art_wand_cluster.adaptive_resize_image(124, 124), "Failed to resize art_cluster"); mask_wand.opaque_paint_image(&white, accent_color, 0.0, false),
handle_magick_result!(main_wand.compose_images(&art_wand, CompositeOperator::SrcOver, false, 12, 12), "Failed to combine images"); "Failed to paint mask"
handle_magick_result!(main_wand.compose_images(&art_wand_cluster, CompositeOperator::SrcOver, false, 160, 12), "Failed to combine images"); );
handle_magick_result!(
main_wand.new_image(548, 147, &colors[0]),
"Failed to create wand"
);
handle_magick_result!(
main_wand.transform_image_colorspace(ColorspaceType::Lab),
"Failed to set main colorspace"
);
handle_magick_result!(
art_wand.adaptive_resize_image(124, 124),
"Failed to resize art"
);
handle_magick_result!(
art_wand_cluster.adaptive_resize_image(124, 124),
"Failed to resize art_cluster"
);
handle_magick_result!(
main_wand.compose_images(&art_wand, CompositeOperator::SrcOver, false, 12, 12),
"Failed to combine images"
);
handle_magick_result!(
main_wand.compose_images(
&art_wand_cluster,
CompositeOperator::SrcOver,
false,
160,
12
),
"Failed to combine debug images"
);
handle_magick_result!(
main_wand.compose_images(&mask_wand, CompositeOperator::SrcOver, false, 401, 0),
"Failed to combine mask"
);
Reply::Image(main_wand.write_image_blob("png").unwrap()) Reply::Image(main_wand.write_image_blob("png").unwrap())
} else {
Reply::Text("Nothing playing.".to_string())
}
} }
async fn set(arg: &str) -> Reply { async fn set(ctx: &Context, arg: &str, id: UserId) -> Reply {
set_lastfm_username(ctx, id, arg.to_string()).await;
Reply::Text(format!("set user {}", arg)) Reply::Text(format!("set user {}", arg))
} }
@ -95,17 +169,17 @@ impl EventHandler for Handler {
let cmd = cmd_iter.next().unwrap_or(""); let cmd = cmd_iter.next().unwrap_or("");
let arg = cmd_iter.next().unwrap_or(""); let arg = cmd_iter.next().unwrap_or("");
let resp = match cmd { let resp = match cmd {
".fmi" => Some(fmi(arg).await), ".fmi" => Some(fmi(&ctx, arg, msg.author.id).await),
".set" => Some(set(arg).await), ".set" => Some(set(&ctx, arg, msg.author.id).await),
_ => None _ => None,
}; };
if let Some(reply) = resp { if let Some(reply) = resp {
let m = match reply { let m = match reply {
Reply::Image(img) => { Reply::Image(img) => {
let file = CreateAttachment::bytes(img, "fmi.png"); let file = CreateAttachment::bytes(img, "fmi.png");
CreateMessage::new().add_file(file) CreateMessage::new().add_file(file)
}, }
Reply::Text(txt) => CreateMessage::new().content(txt) Reply::Text(txt) => CreateMessage::new().content(txt),
}; };
let message = msg.channel_id.send_message(&ctx.http, m).await; let message = msg.channel_id.send_message(&ctx.http, m).await;
@ -116,26 +190,87 @@ impl EventHandler for Handler {
} }
} }
struct PoolContainer;
impl TypeMapKey for PoolContainer {
type Value = SqlitePool;
}
struct DBResponse {
lastfm_username: String,
}
async fn get_lastfm_username(ctx: &Context, id: UserId) -> Option<String> {
let data = ctx.data.write().await;
let pool = data
.get::<PoolContainer>()
.expect("Failed to get pool container");
let id = i64::from(id);
let resp = sqlx::query_as!(
DBResponse,
r#"
SELECT lastfm_username
FROM users
WHERE discord_userid = ?1
"#,
id
)
.fetch_one(pool)
.await;
match resp {
Ok(r) => Some(r.lastfm_username),
Err(_) => None,
}
}
async fn set_lastfm_username(ctx: &Context, id: UserId, user: String) {
let data = ctx.data.write().await;
let pool = data
.get::<PoolContainer>()
.expect("Failed to get pool container");
let id = i64::from(id);
sqlx::query!(
r#"
INSERT INTO users
VALUES (?1, ?2)
"#,
id, user
)
.execute(pool)
.await.expect("Failed to insert");
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
START.call_once(|| { START.call_once(|| {
dotenv().ok(); dotenvy::dotenv().expect("Failed to load .env");
magick_wand_genesis(); magick_wand_genesis();
}); });
// Login with a bot token from the environment let db_url = env::var("DATABASE_URL").expect("Failed to load DATABASE_URL");
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment"); let pool = SqlitePool::connect(&db_url)
.await
.expect("Failed to load db");
let token = env::var("DISCORD_TOKEN").expect("Failed to load DISCORD_TOKEN");
// Set gateway intents, which decides what events the bot will be notified about // Set gateway intents, which decides what events the bot will be notified about
let intents = GatewayIntents::GUILD_MESSAGES let intents = GatewayIntents::GUILD_MESSAGES
| GatewayIntents::DIRECT_MESSAGES | GatewayIntents::DIRECT_MESSAGES
| GatewayIntents::MESSAGE_CONTENT; | GatewayIntents::MESSAGE_CONTENT;
// Create a new instance of the Client, logging in as a bot. let mut client = Client::builder(&token, intents)
let mut client = .event_handler(Handler)
Client::builder(&token, intents).event_handler(Handler).await.expect("Err creating client"); .await
.expect("Err creating client");
{
let mut data = client.data.write().await;
data.insert::<PoolContainer>(pool);
}
// Start listening for events by starting a single shard
if let Err(why) = client.start().await { if let Err(why) = client.start().await {
println!("Client error: {why:?}"); println!("Client error: {why:?}");
} else {
println!("watcat started");
} }
} }