matrix-modbot/src/utils.rs

90 lines
3.1 KiB
Rust

// Snippet from https://github.com/haecker-felix/hebbot, licensed under AGPL, License terms apply
#[allow(clippy::module_inception)]
pub mod utils {
use matrix_sdk::ruma::events::room::message::{
MessageType, OriginalSyncRoomMessageEvent, TextMessageEventContent, Relation,
};
use matrix_sdk::ruma::OwnedEventId;
use sled::IVec;
use std::{
fs::File,
io::{copy, BufReader, BufRead, Result}, collections::HashMap,
};
use reqwest;
#[derive(Clone)]
pub struct SpamInfo {
pub detection_window: i64,
pub max_msg_per_window: i64,
pub author_msg_times: HashMap<String, Vec<i64>>,
}
impl SpamInfo {
pub fn new() -> Self {
SpamInfo { detection_window: 5, max_msg_per_window: 5, author_msg_times: HashMap::new() }
}
}
pub fn get_message_event_text(event: &OriginalSyncRoomMessageEvent) -> Option<String> {
if let MessageType::Text(TextMessageEventContent { body, .. }) = &event.content.msgtype {
Some(body.to_owned())
} else {
None
}
}
// A simplified way of getting an edited message
pub fn get_edited_message_event_text(
event: &OriginalSyncRoomMessageEvent,
) -> Option<(OwnedEventId, String)> {
if let Some(Relation::Replacement(r)) = &event.content.relates_to {
if "m.text" == r.new_content.msgtype() {
return Some((r.event_id.clone(), r.new_content.body().to_owned()));
}
}
None
}
pub fn create_swear_list(swear_list_url: &str) -> Result<Vec<String>> {
// Downloads the text file
let resp = reqwest::blocking::get(swear_list_url).expect("request failed");
let body = resp.text().expect("Invalid Body");
let mut out = File::create("list.txt").expect("failed to create file");
copy(&mut body.as_bytes(), &mut out).expect("failed to copy content");
// Reads file, returns vector of Strings through collecting iterator
BufReader::new(File::open("list.txt")?).lines().collect()
}
pub fn detect_swear_from_message(swear_list: &Vec<String>, message: &str) -> bool {
let message_words = message.split_whitespace();
for words in message_words {
for swear in swear_list {
if words.contains(swear) {
return true
}
}
}
false
}
pub fn convert_from_bytes_sled(bytes: &IVec) -> (i64, i64){
let timestamp: &[u8; 8] = bytes[..8].try_into().unwrap();
let reputation: &[u8; 8] = bytes[9..].try_into().unwrap();
let time_integer: i64 = i64::from_be_bytes(*timestamp);
let rep_integer: i64 = i64::from_be_bytes(*reputation);
(time_integer, rep_integer)
}
pub fn convert_to_bytes_sled(timestamp: i64, reputation: i64) -> [u8; 16] {
let timestamp: [u8; 8] = timestamp.to_be_bytes();
let reputation: [u8; 8] = reputation.to_be_bytes();
let bytes: &[u8; 16] = &[timestamp, reputation].concat().try_into().unwrap();
bytes.clone()
}
}