Compare commits
4 Commits
4e3b4ee234
...
06102b6ffa
| Author | SHA1 | Date | |
|---|---|---|---|
| 06102b6ffa | |||
| 19cd656028 | |||
| e0b86dbc39 | |||
| 5e3bc7a6d8 |
3
.env.example
Normal file
3
.env.example
Normal file
@ -0,0 +1,3 @@
|
||||
DISCORD_TOKEN=
|
||||
LASTFM_API_KEY=
|
||||
DATABASE_URL=sqlite:watcat.db
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,2 +1,3 @@
|
||||
/target
|
||||
/.env
|
||||
/watcat.db*
|
||||
|
||||
4
.gitmodules
vendored
Normal file
4
.gitmodules
vendored
Normal 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
926
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
17
Cargo.toml
17
Cargo.toml
@ -5,7 +5,18 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serenity = "0.12"
|
||||
tokio = { version = "1.21.2", features = ["macros", "rt-multi-thread"] }
|
||||
dotenv = "0.15.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"]
|
||||
|
||||
12
README.md
12
README.md
@ -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
|
||||
|
||||
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
|
||||
-------------------
|
||||
|
||||
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
1
magick-rust
Submodule
Submodule magick-rust added at 5fbc506983
5
migrations/20250515121632_init.sql
Normal file
5
migrations/20250515121632_init.sql
Normal file
@ -0,0 +1,5 @@
|
||||
CREATE TABLE IF NOT EXISTS users
|
||||
(
|
||||
discord_userid INTEGER PRIMARY KEY NOT NULL,
|
||||
lastfm_username TEXT NOT NULL
|
||||
) STRICT;
|
||||
311
src/main.rs
311
src/main.rs
@ -1,141 +1,276 @@
|
||||
extern crate dotenvy;
|
||||
extern crate lastfm;
|
||||
use dotenv::dotenv;
|
||||
|
||||
use serenity::async_trait;
|
||||
use serenity::model::channel::Message;
|
||||
use serenity::prelude::*;
|
||||
use serenity::builder::{CreateAttachment, CreateMessage};
|
||||
use serenity::model::channel::Message;
|
||||
use serenity::model::id::UserId;
|
||||
use serenity::prelude::*;
|
||||
|
||||
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::sync::Once;
|
||||
|
||||
extern crate sqlx;
|
||||
use sqlx::sqlite::SqlitePool;
|
||||
|
||||
static START: Once = Once::new();
|
||||
|
||||
struct Handler;
|
||||
|
||||
enum Reply {
|
||||
Image(Vec<u8>),
|
||||
Text(String)
|
||||
Image(Vec<u8>),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
macro_rules! handle_magick_result {
|
||||
($a: expr, $b: literal) => {
|
||||
match $a {
|
||||
Ok(_) => {},
|
||||
Err(e) => return Reply::Text(format!("Error: {} {}", $b, e)),
|
||||
}
|
||||
}
|
||||
($a: expr, $b: literal) => {
|
||||
match $a {
|
||||
Ok(_) => {}
|
||||
Err(e) => return Reply::Text(format!("Error: {} {}", $b, e)),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! handle_magick_option {
|
||||
($a: expr, $b: literal) => {
|
||||
match $a {
|
||||
Some(res) => res,
|
||||
None => return Reply::Text($b.to_string()),
|
||||
}
|
||||
}
|
||||
($a: expr, $b: literal) => {
|
||||
match $a {
|
||||
Some(res) => res,
|
||||
None => return Reply::Text($b.to_string()),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async fn fmi(_arg: &str) -> Reply {
|
||||
let client = lastfm::Client::<String, &str>::from_env("seoxi");
|
||||
let now_playing = match client.now_playing().await {
|
||||
Ok(np) => np,
|
||||
Err(e) => return Reply::Text(format!("Error: grabbing last.fm user data failed {e}")),
|
||||
};
|
||||
if let Some(track) = now_playing {
|
||||
let image_uri = match track.image.extralarge {
|
||||
Some(iu) => iu,
|
||||
None => return Reply::Text("Error: getting image uri failed".to_string()),
|
||||
};
|
||||
let mut base_color = PixelWand::new();
|
||||
#[allow(unused_mut)]
|
||||
let mut main_wand = MagickWand::new();
|
||||
#[allow(unused_mut)]
|
||||
let mut art_wand = MagickWand::new();
|
||||
//#[allow(unused_mut)]
|
||||
let mut art_wand_cluster = MagickWand::new();
|
||||
#[allow(unused)]
|
||||
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 {
|
||||
Ok(np) => np,
|
||||
Err(e) => return Reply::Text(format!("Error: grabbing last.fm user data failed {e}")),
|
||||
};
|
||||
let track = match now_playing {
|
||||
Some(track) => track,
|
||||
None => return Reply::Text("Nothing playing.".to_string()),
|
||||
};
|
||||
let image_uri = match track.image.extralarge {
|
||||
Some(iu) => iu,
|
||||
None => return Reply::Text("Error: getting image uri failed".to_string()),
|
||||
};
|
||||
let mut base_color = PixelWand::new();
|
||||
let mut white = PixelWand::new();
|
||||
let mut main_wand = MagickWand::new();
|
||||
let mut art_wand = 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!(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");
|
||||
handle_magick_result!(
|
||||
base_color.set_color("#7f7f7f"),
|
||||
"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());
|
||||
handle_magick_result!(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
|
||||
handle_magick_result!(art_wand_cluster.set_image_colorspace(ColorspaceType::Lab), "Failed to set cluster colorspace");
|
||||
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");
|
||||
println!("{}", colors.len());
|
||||
colors.sort_by_cached_key(|color| -(color.get_color_count() as isize));
|
||||
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!(
|
||||
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
|
||||
handle_magick_result!(
|
||||
art_wand_cluster.set_image_colorspace(ColorspaceType::Lab),
|
||||
"Failed to set cluster colorspace"
|
||||
);
|
||||
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));
|
||||
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!(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 images");
|
||||
Reply::Image(main_wand.write_image_blob("png").unwrap())
|
||||
} else {
|
||||
Reply::Text("Nothing playing.".to_string())
|
||||
}
|
||||
handle_magick_result!(white.set_color("#ffffff"), "Failed to set init white");
|
||||
handle_magick_result!(mask_wand.read_image("mask.png"), "Failed to load mask");
|
||||
handle_magick_result!(
|
||||
mask_wand.opaque_paint_image(&white, accent_color, 0.0, false),
|
||||
"Failed to paint mask"
|
||||
);
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EventHandler for Handler {
|
||||
async fn message(&self, ctx: Context, msg: Message) {
|
||||
let mut cmd_iter = msg.content.split(" ");
|
||||
let cmd = cmd_iter.next().unwrap_or("");
|
||||
let arg = cmd_iter.next().unwrap_or("");
|
||||
let resp = match cmd {
|
||||
".fmi" => Some(fmi(arg).await),
|
||||
".set" => Some(set(arg).await),
|
||||
_ => None
|
||||
};
|
||||
if let Some(reply) = resp {
|
||||
let m = match reply {
|
||||
Reply::Image(img) => {
|
||||
let file = CreateAttachment::bytes(img, "fmi.png");
|
||||
CreateMessage::new().add_file(file)
|
||||
},
|
||||
Reply::Text(txt) => CreateMessage::new().content(txt)
|
||||
};
|
||||
let mut cmd_iter = msg.content.split(" ");
|
||||
let cmd = cmd_iter.next().unwrap_or("");
|
||||
let arg = cmd_iter.next().unwrap_or("");
|
||||
let resp = match cmd {
|
||||
".fmi" => Some(fmi(&ctx, arg, msg.author.id).await),
|
||||
".set" => Some(set(&ctx, arg, msg.author.id).await),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(reply) = resp {
|
||||
let m = match reply {
|
||||
Reply::Image(img) => {
|
||||
let file = CreateAttachment::bytes(img, "fmi.png");
|
||||
CreateMessage::new().add_file(file)
|
||||
}
|
||||
Reply::Text(txt) => CreateMessage::new().content(txt),
|
||||
};
|
||||
|
||||
let message = msg.channel_id.send_message(&ctx.http, m).await;
|
||||
if let Err(why) = message {
|
||||
println!("Error sending message: {why:?}");
|
||||
}
|
||||
}
|
||||
let message = msg.channel_id.send_message(&ctx.http, m).await;
|
||||
if let Err(why) = message {
|
||||
println!("Error sending message: {why:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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]
|
||||
async fn main() {
|
||||
START.call_once(|| {
|
||||
dotenv().ok();
|
||||
START.call_once(|| {
|
||||
dotenvy::dotenv().expect("Failed to load .env");
|
||||
magick_wand_genesis();
|
||||
});
|
||||
|
||||
// Login with a bot token from the environment
|
||||
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
|
||||
let db_url = env::var("DATABASE_URL").expect("Failed to load DATABASE_URL");
|
||||
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
|
||||
let intents = GatewayIntents::GUILD_MESSAGES
|
||||
| GatewayIntents::DIRECT_MESSAGES
|
||||
| GatewayIntents::MESSAGE_CONTENT;
|
||||
|
||||
// Create a new instance of the Client, logging in as a bot.
|
||||
let mut client =
|
||||
Client::builder(&token, intents).event_handler(Handler).await.expect("Err creating client");
|
||||
let mut client = Client::builder(&token, intents)
|
||||
.event_handler(Handler)
|
||||
.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 {
|
||||
println!("Client error: {why:?}");
|
||||
} else {
|
||||
println!("watcat started");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user