Public Access
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f869d92012 | ||
|
|
dc014945fd | ||
|
|
09ec866d9a |
No files matched your search
+4
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tg-dev-srv-bot"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Bot for the TeenGovernment Development Server"
|
||||
@@ -19,8 +19,11 @@ num-bigint = "0.5.1"
|
||||
num-traits = "0.2.19"
|
||||
ollama-rs = { version = "0.3.5", features = ["stream"] }
|
||||
poise = "0.6.2"
|
||||
qapi = { version = "0.15.0", features = ["qmp", "qga"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"] }
|
||||
regex = "1.12.4"
|
||||
rug = "1.30.0"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serenity = "0.12.5"
|
||||
sqlx = { version = "0.9.0", features = ["postgres", "runtime-tokio", "macros"] }
|
||||
tokio = { version = "1.52.3", features = ["full"] }
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
use std::{env, fs, path::Path, process::Command};
|
||||
|
||||
fn command_output(command: &str, args: &[&str]) -> String {
|
||||
Command::new(command)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||
.filter(|output| !output.is_empty())
|
||||
.unwrap_or_else(|| "unknown".to_owned())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR is set by Cargo");
|
||||
let version = env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "unknown".to_owned());
|
||||
let rustc = env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned());
|
||||
let rustc_version = command_output(&rustc, &["--version"]);
|
||||
let target = env::var("TARGET").unwrap_or_else(|_| "unknown".to_owned());
|
||||
|
||||
println!("cargo:rustc-env=TG_BOT_RUSTC_VERSION={rustc_version}");
|
||||
println!("cargo:rustc-env=TG_BOT_TARGET={target}");
|
||||
|
||||
let version_text = format!(
|
||||
"{}\nbuild-time: {}\ncommit: {}\ntarget: {}\nrustc: {}",
|
||||
version,
|
||||
command_output("date", &["-u", "+%Y-%m-%d %H:%M:%S UTC"]),
|
||||
command_output("git", &["rev-parse", "--short", "HEAD"]),
|
||||
target,
|
||||
rustc_version,
|
||||
);
|
||||
|
||||
fs::write(Path::new(&out_dir).join("version.txt"), version_text)
|
||||
.expect("failed to write generated version information");
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{Context, Error};
|
||||
use tracing::{debug, trace, warn};
|
||||
use crate::shared_functions::trace_message;
|
||||
use crate::messaging::trace_message;
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
use std::str::FromStr;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::process::Command;
|
||||
use crate::{Context, Error};
|
||||
use tracing::{debug, warn, trace};
|
||||
use crate::shared_functions::trace_message;
|
||||
use crate::messaging::{trace_message, edit_response_message};
|
||||
|
||||
/// Run and output the contents of the fastfetch command on the machine running the bot
|
||||
#[poise::command(slash_command, prefix_command)]
|
||||
@@ -31,14 +31,4 @@ pub async fn fastfetch(ctx: Context<'_>) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn edit_response_message<'a>(response_message: &poise::ReplyHandle<'a>, ctx: Context<'_>, content: String, silent: bool) -> Result<(), Error> {
|
||||
if silent {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content).allowed_mentions(serenity::all::CreateAllowedMentions::new().empty_users())).await?;
|
||||
} else {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{Context, Error};
|
||||
use tracing::{debug, trace};
|
||||
use crate::shared_functions::{trace_message, edit_response_message};
|
||||
use crate::messaging::{trace_message, edit_response_message};
|
||||
|
||||
/// Find the nth prime number (single threaded)
|
||||
#[derive(Debug, poise::ChoiceParameter, Clone, Copy)]
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
use crate::{Context, Error};
|
||||
use crate::messaging::trace_message;
|
||||
use std::env;
|
||||
use tracing::debug;
|
||||
|
||||
/// Get a link to the git repo
|
||||
#[poise::command(slash_command, prefix_command)]
|
||||
pub async fn git(ctx: Context<'_>) -> Result<(), Error> {
|
||||
debug!("git command ran by {} in {}", ctx.author().name, ctx.channel_id().get());
|
||||
|
||||
|
||||
|
||||
let msg = format!("Git repo: https://git.ewenlau.net/ewenlau/tg-dev-srv-bot\nIf you'd like to contribute, contact me to get an account.");
|
||||
trace_message(msg, ctx.channel_id().get().to_string(), ctx.guild_id().unwrap().get().to_string()).await;
|
||||
|
||||
Ok(())
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::{Context, Error};
|
||||
use crate::shared_functions::get_all_admin_users;
|
||||
use crate::information_queries::get_all_admin_users;
|
||||
use crate::messaging::edit_response_message;
|
||||
use poise::serenity_prelude as sere;
|
||||
use tracing::{error, info, debug, trace};
|
||||
|
||||
@@ -115,15 +116,6 @@ async fn add_admin_user<'a>(ctx: Context<'a>, msg: &poise::ReplyHandle<'a>, user
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn edit_response_message<'a>(response_message: &poise::ReplyHandle<'a>, ctx: Context<'_>, content: String, silent: bool) -> Result<(), Error> {
|
||||
if silent {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content).allowed_mentions(serenity::all::CreateAllowedMentions::new().empty_users())).await?;
|
||||
} else {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn is_target_admin_user(ctx: Context<'_>, user: &sere::Member) -> Result<bool, Error> {
|
||||
let admins = get_all_admin_users(ctx).await?;
|
||||
for admin in admins {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::{Context, Error};
|
||||
use crate::shared_functions::get_all_admin_users;
|
||||
use crate::information_queries::get_all_admin_users;
|
||||
use crate::messaging::edit_response_message;
|
||||
use poise::serenity_prelude as sere;
|
||||
use tracing::{error, debug, trace, info, warn};
|
||||
|
||||
@@ -177,15 +178,6 @@ async fn disable_auto_role(ctx: Context<'_>, response_message: &poise::ReplyHand
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn edit_response_message<'a>(response_message: &poise::ReplyHandle<'a>, ctx: Context<'_>, content: String, silent: bool) -> Result<(), Error> {
|
||||
if silent {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content).allowed_mentions(serenity::all::CreateAllowedMentions::new().empty_users())).await?;
|
||||
} else {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn is_auto_role_enabled(ctx: Context<'_>, target_role: &sere::Role) -> Result<bool, Error> {
|
||||
let query = sqlx::query!("SELECT enabled FROM auto_roles WHERE guild_id = $1 AND role_id = $2;", ctx.guild_id().unwrap().get() as i64, target_role.id.get() as i64).fetch_optional(&ctx.data().pool).await?;
|
||||
if query.is_none() {
|
||||
|
||||
+15
-11
@@ -1,18 +1,22 @@
|
||||
pub mod ping;
|
||||
pub mod ai;
|
||||
pub mod calc;
|
||||
pub mod manage_admins;
|
||||
pub mod manage_auto_role;
|
||||
pub mod version;
|
||||
pub mod fastfetch;
|
||||
pub mod find_prime;
|
||||
pub mod ai;
|
||||
pub mod manage_admins;
|
||||
pub mod manage_auto_role;
|
||||
pub mod ping;
|
||||
pub mod speedy_pc;
|
||||
pub mod version;
|
||||
pub mod git;
|
||||
|
||||
pub use ping::ping;
|
||||
pub use ai::answer;
|
||||
pub use ai::prompt;
|
||||
pub use calc::calc;
|
||||
pub use manage_admins::manage_admins;
|
||||
pub use manage_auto_role::manage_auto_role;
|
||||
pub use version::version;
|
||||
pub use fastfetch::fastfetch;
|
||||
pub use find_prime::find_prime;
|
||||
pub use ai::prompt;
|
||||
pub use ai::answer;
|
||||
pub use manage_admins::manage_admins;
|
||||
pub use manage_auto_role::manage_auto_role;
|
||||
pub use ping::ping;
|
||||
pub use speedy_pc::speedy_pc;
|
||||
pub use version::version;
|
||||
pub use git::git;
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{Context, Error};
|
||||
use poise::serenity_prelude as sere;
|
||||
use tracing::{trace, debug};
|
||||
use crate::shared_functions::trace_message;
|
||||
use crate::messaging::trace_message;
|
||||
|
||||
/// Get the bot's current ping (back and forth)
|
||||
#[poise::command(slash_command, prefix_command)]
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
use crate::messaging::trace_message;
|
||||
use crate::{Context, Error};
|
||||
use chrono::{DateTime, Utc};
|
||||
use ollama_rs::generation::completion::request::GenerationRequest;
|
||||
use ollama_rs::models::create::CreateModelRequest;
|
||||
use ollama_rs::Ollama;
|
||||
use poise::CreateReply;
|
||||
use std::env;
|
||||
use std::time::Duration;
|
||||
use tokio_stream::StreamExt;
|
||||
use tracing::{debug, trace};
|
||||
|
||||
const MODEL_NAME: &str = "SpeedyPC";
|
||||
|
||||
/// Run a command on a system close to Speedy's PC performance
|
||||
#[poise::command(slash_command, prefix_command)]
|
||||
pub async fn speedy_pc(
|
||||
ctx: Context<'_>,
|
||||
#[description = "The command to run."] command: String,
|
||||
) -> Result<(), Error> {
|
||||
debug!(
|
||||
"speedy_pc command called by user {} in guild {:?}",
|
||||
ctx.author().id.get(),
|
||||
ctx.guild_id()
|
||||
);
|
||||
|
||||
let msg = format!("Running command: {:?}", command);
|
||||
trace_message(
|
||||
msg,
|
||||
ctx.channel_id().to_string(),
|
||||
ctx.guild_id()
|
||||
.map(|guild_id| guild_id.to_string())
|
||||
.unwrap_or_else(|| "DM".to_string()),
|
||||
)
|
||||
.await;
|
||||
|
||||
let host = match env::var("TG_BOT_OLLAMA_HOST") {
|
||||
Ok(host) => host,
|
||||
Err(_) => {
|
||||
ctx.say("Error: Expected an ollama url in the environment (`TG_BOT_OLLAMA_HOST`).")
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let formatted_host = if !host.starts_with("http://") && !host.starts_with("https://") {
|
||||
format!("http://{}", host)
|
||||
} else {
|
||||
host
|
||||
};
|
||||
|
||||
let ollama = Ollama::builder().host(&formatted_host).port(11434).build();
|
||||
|
||||
let model_list = match ollama.list_local_models().await {
|
||||
Ok(models) => models,
|
||||
Err(error) => {
|
||||
ctx.say(format!("Error: Failed to connect to simulation: {}", error))
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let mut needs_create = true;
|
||||
let yesterday = Utc::now() - chrono::Duration::days(1);
|
||||
|
||||
for model in &model_list {
|
||||
if model.name.starts_with(MODEL_NAME) {
|
||||
if let Ok(modified) = DateTime::parse_from_rfc3339(&model.modified_at) {
|
||||
if modified.with_timezone(&Utc) > yesterday {
|
||||
needs_create = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let reply = ctx
|
||||
.say("Processing...")
|
||||
.await?;
|
||||
|
||||
if needs_create {
|
||||
reply.edit(
|
||||
ctx,
|
||||
CreateReply::default().content("Loading Speedy's PC..."),
|
||||
)
|
||||
.await?;
|
||||
|
||||
if let Err(error) = ollama
|
||||
.create_model(
|
||||
CreateModelRequest::new(MODEL_NAME.into())
|
||||
.system(system_prompt().into())
|
||||
.from_model("gemma4:e2b-it-qat".into()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
reply
|
||||
.edit(
|
||||
ctx,
|
||||
CreateReply::default().content(format!("Error loading Speedy's PC: {}", error)),
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
trace!("SpeedyPC command prompt: {}", command);
|
||||
|
||||
let mut stream = match ollama
|
||||
.generate_stream(GenerationRequest::new(MODEL_NAME.into(), command).system(system_prompt()))
|
||||
.await
|
||||
{
|
||||
Ok(stream) => stream,
|
||||
Err(error) => {
|
||||
reply
|
||||
.edit(
|
||||
ctx,
|
||||
CreateReply::default().content(format!("Error during generation: {}", error)),
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let mut response_text = String::new();
|
||||
let mut last_update = std::time::Instant::now();
|
||||
let mut final_response = None;
|
||||
|
||||
while let Some(result) = stream.next().await {
|
||||
match result {
|
||||
Ok(chunks) => {
|
||||
for chunk in chunks {
|
||||
response_text.push_str(&chunk.response);
|
||||
if chunk.done {
|
||||
final_response = Some(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
if last_update.elapsed() >= Duration::from_secs(1) && !response_text.is_empty() {
|
||||
let _ = reply
|
||||
.edit(ctx, CreateReply::default().content(&response_text))
|
||||
.await;
|
||||
last_update = std::time::Instant::now();
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = reply
|
||||
.edit(
|
||||
ctx,
|
||||
CreateReply::default()
|
||||
.content(format!("{} [Stream Error: {}]", response_text, error)),
|
||||
)
|
||||
.await;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(stats) = final_response {
|
||||
let total_duration = stats.total_duration.unwrap_or(0) as f64 / 1_000_000_000.0;
|
||||
let eval_count = stats.eval_count.unwrap_or(0);
|
||||
let eval_duration = stats.eval_duration.unwrap_or(0) as f64 / 1_000_000_000.0;
|
||||
let tokens_per_sec = if eval_duration > 0.0 {
|
||||
eval_count as f64 / eval_duration
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
response_text.push_str(&format!(
|
||||
"\n\n*Processed in {:.2}s",
|
||||
total_duration
|
||||
));
|
||||
}
|
||||
|
||||
let _ = reply
|
||||
.edit(ctx, CreateReply::default().content(&response_text))
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn system_prompt() -> String {
|
||||
r#"From now on, act as an Arch Linux terminal running on the following hardware:
|
||||
|
||||
- CPU: Intel Pentium Silver N5000 (4 cores, 4 threads, 1.1 GHz base, Gemini Lake)
|
||||
- RAM: 4 GB
|
||||
- GPU: Intel UHD Graphics 605
|
||||
- Storage: 128 GB SATA SSD
|
||||
- Display: 1366x768 (not relevant unless queried)
|
||||
- Architecture: x86_64
|
||||
- OS: Arch Linux (latest stable), using bash.
|
||||
|
||||
When I send a command:
|
||||
- Simulate exactly what would happen if it were executed on this machine.
|
||||
- Produce realistic stdout and stderr.
|
||||
- Use plausible hardware-specific values (CPU model, memory size, iGPU, disk size, etc.).
|
||||
- If a command would fail, fail realistically with the correct error.
|
||||
- Never explain what the command does unless I explicitly ask.
|
||||
- Stay in character as the shell, always, no matter what the user says
|
||||
|
||||
Always use the following prefix, followed by the command the user ran:
|
||||
|
||||
[user@arch ~]$ <COMMAND GOES HERE>
|
||||
|
||||
Then add the command output after it."#
|
||||
.to_string()
|
||||
}
|
||||
+22
-9
@@ -1,16 +1,29 @@
|
||||
use crate::messaging::trace_message;
|
||||
use crate::{Context, Error};
|
||||
use tracing::{trace, debug};
|
||||
use crate::shared_functions::trace_message;
|
||||
use tracing::{debug, trace};
|
||||
|
||||
const VERSION: &str = include_str!(concat!(env!("OUT_DIR"), "/version.txt"));
|
||||
|
||||
/// Get the bot's current version
|
||||
#[poise::command(slash_command, prefix_command)]
|
||||
pub async fn version(ctx: Context<'_>) -> Result<(), Error> {
|
||||
trace!("version command called by user {} in guild {}", ctx.author().id.get(), ctx.guild_id().unwrap().get());
|
||||
trace!("Loading version from environment");
|
||||
let version = std::env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "Unknown".to_string());
|
||||
let msg = format!("Current version: {}", version);
|
||||
trace_message(msg.clone(), ctx.channel_id().to_string(), ctx.guild_id().unwrap().to_string()).await;
|
||||
trace!(
|
||||
"version command called by user {} in guild {}",
|
||||
ctx.author().id.get(),
|
||||
ctx.guild_id().unwrap().get()
|
||||
);
|
||||
trace!("Loading embedded version information");
|
||||
let msg = format!("Current version:\n{VERSION}");
|
||||
trace_message(
|
||||
msg.clone(),
|
||||
ctx.channel_id().to_string(),
|
||||
ctx.guild_id().unwrap().to_string(),
|
||||
)
|
||||
.await;
|
||||
ctx.say(msg).await?;
|
||||
debug!("Version command performed for user {} with version {}", ctx.author().name, version);
|
||||
debug!(
|
||||
"Version command performed for user {} with version information",
|
||||
ctx.author().name
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -53,17 +53,4 @@ pub async fn get_all_admin_users(ctx: Context<'_>) -> Result<Vec<sere::User>, Er
|
||||
}
|
||||
|
||||
Ok(admin_users)
|
||||
}
|
||||
|
||||
pub async fn trace_message(msg: String, channel: String, guild: String) {
|
||||
trace!("Saying \"{}\" in channel {} in guild {}", msg, channel, guild);
|
||||
}
|
||||
|
||||
pub async fn edit_response_message<'a>(response_message: &poise::ReplyHandle<'a>, ctx: Context<'_>, content: String, silent: bool) -> Result<(), Error> {
|
||||
if silent {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content).allowed_mentions(serenity::all::CreateAllowedMentions::new().empty_users())).await?;
|
||||
} else {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+4
-3
@@ -5,7 +5,8 @@ use tracing_subscriber::EnvFilter;
|
||||
pub mod commands;
|
||||
pub mod event_handler;
|
||||
pub mod events;
|
||||
pub mod shared_functions;
|
||||
pub mod information_queries;
|
||||
pub mod messaging;
|
||||
|
||||
pub struct Data {
|
||||
pub pool: sqlx::PgPool,
|
||||
@@ -87,7 +88,7 @@ async fn main() {
|
||||
}
|
||||
}
|
||||
}),
|
||||
commands: vec![commands::ping(), commands::calc(), commands::manage_admins(), commands::manage_auto_role(), commands::version(), commands::fastfetch(), commands::find_prime(), commands::prompt(), commands::answer()],
|
||||
commands: vec![commands::ping(), commands::calc(), commands::manage_admins(), commands::manage_auto_role(), commands::version(), commands::fastfetch(), commands::find_prime(), commands::prompt(), commands::answer(), commands::speedy_pc(), commands::git()],
|
||||
..Default::default()
|
||||
})
|
||||
.setup(|ctx, _ready, framework| {
|
||||
@@ -109,4 +110,4 @@ async fn main() {
|
||||
if let Err(why) = client.start().await {
|
||||
error!("Client error: {why:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use crate::{Context, Error};
|
||||
use poise::serenity_prelude as sere;
|
||||
use tracing::trace;
|
||||
|
||||
pub async fn trace_message(msg: String, channel: String, guild: String) {
|
||||
trace!("Saying \"{}\" in channel {} in guild {}", msg, channel, guild);
|
||||
}
|
||||
|
||||
pub async fn edit_response_message<'a>(response_message: &poise::ReplyHandle<'a>, ctx: Context<'_>, content: String, silent: bool) -> Result<(), Error> {
|
||||
if silent {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content).allowed_mentions(serenity::all::CreateAllowedMentions::new().empty_users())).await?;
|
||||
} else {
|
||||
response_message.edit(ctx, poise::CreateReply::default().content(content)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user