didgeridoo/src/main.rs
2021-05-03 22:06:19 +02:00

154 lines
4.5 KiB
Rust

use inbox::*;
use itertools::Itertools;
use lazy_static::lazy_static;
use serenity::client::Client;
use serenity::framework::standard::{
macros::{command, group},
CommandError, CommandResult, StandardFramework,
};
use serenity::model::{
channel::Message,
id::{ChannelId, GuildId, UserId},
prelude::User,
};
use serenity::prelude::*;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use time::Duration;
mod inbox;
const APPLICATION_NAME: &str = "didgeridoo";
const INBOX_OWNER: UserId = UserId(354694403798990848);
lazy_static! {
static ref INBOX: Inbox = Inbox(redis::Client::open("redis://127.0.0.1/").unwrap());
}
macro_rules! send_or_log {
($e: expr) => {
if let Err(e) = $e {
eprintln!("Couldn’t send message because {:?}", e);
}
};
}
#[group]
#[commands(name, message, question, inbox)]
struct Fluff;
struct Handler;
impl EventHandler for Handler {
fn guild_ban_addition(&self, ctx: Context, guild_id: GuildId, _: User) {
if guild_id == 427456811973738498 {
send_or_log!(
ChannelId(562731470423064587).say(&ctx, "Dies ist eine flauschige Diktatur!")
);
}
}
}
fn read_token() -> io::Result<String> {
let reader = BufReader::new(File::open("secret")?);
reader.lines().next().unwrap()
}
fn main() {
let mut client = Client::new(&read_token().expect("no secret file"), Handler)
.expect("Error creating client");
client.with_framework(
StandardFramework::new()
.configure(|c| c.prefix("!"))
.group(&FLUFF_GROUP),
);
INBOX.count_messages("test"); // initialize the lazy static so we know if redis is unavailable
if let Err(why) = client.start() {
println!("An error occurred while running the client: {:?}", why);
}
}
#[command]
fn name(ctx: &mut Context, msg: &Message) -> CommandResult {
if let Some((_, name)) = msg.content.split_once(' ') {
let (name, adjustment) = name.split_once(" -").unwrap_or((name, "0"));
let adjustment = adjustment.strip_suffix("h").unwrap_or(adjustment);
msg.guild(&ctx)
.unwrap()
.read()
.edit_member(&ctx, msg.author.id, |m| m.nickname(name))?;
let now = time::OffsetDateTime::now_utc()
- adjustment
.parse::<f32>()
.map(|a| (a * 3600.0) as i64)
.map(Duration::seconds)
.ok()
.unwrap_or_else(Duration::zero);
println!(
"{},{},{},{},{}",
now.format("%d.%m.%Y %H:%M"),
name,
now.format("%y%m"),
msg.author.id,
now.unix_timestamp()
);
} else {
return Err(CommandError(String::from("Please specify a new name.")));
}
Ok(())
}
#[command]
fn inbox(ctx: &mut Context, msg: &Message) -> CommandResult {
if msg.author.id != INBOX_OWNER {
send_or_log!(msg.reply(&ctx, "You don’t have the permission to do that"));
return Ok(());
}
if let Some((_, name)) = msg.content.split_once(' ') {
let messages = INBOX.fetch_messages(name);
if messages.is_empty() {
send_or_log!(msg.reply(&ctx, format!("Keine neuen Nachrichten für {}.", name)));
return Ok(());
}
let output = messages.into_iter().join("\n");
send_or_log!(msg.reply(&ctx, output));
} else {
send_or_log!(msg.reply(&ctx, "Kein Name für die Abfrage."));
}
Ok(())
}
#[command]
fn message(ctx: &mut Context, msg: &Message) -> CommandResult {
message_internal(ctx, msg, &msg.content)
}
#[command]
fn question(ctx: &mut Context, msg: &Message) -> CommandResult {
message_internal(
ctx,
msg,
&msg.content.replacen("!question", "!message Stream:", 1),
)
}
fn message_internal(ctx: &mut Context, msg: &Message, content: &str) -> CommandResult {
InboxMessage::parse(content, msg.author.id)
.ok_or_else(|| {
String::from(
"Nachricht konnte nicht gesendet werden.
Bitte achte auf die richtige Formulierung: “!message <name>: <text>”,
z.B. “!message Lana: Hawwu!”",
)
})
.and_then(|m| INBOX.queue_message(&m))
.map(|n| {
send_or_log!(msg.reply(
&ctx,
&format!("Deine Nachricht wurde erfolgreich an {} gesendet", n),
));
})
.map_err(|e| {
send_or_log!(msg.reply(&ctx, &e));
CommandError(e)
})
}