diff --git a/src/commands.rs b/src/commands.rs index 1f1c1e9..b837948 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -80,3 +80,24 @@ pub(crate) async fn markov_all(api: Api, message: Message) -> Result<(), Error> //api.send(message.from.text("Private text")).await?; Ok(()) } + +pub(crate) async fn markov(api: Api, message: Message) -> Result<(), Error> { + let messages = db::get_random_messages_group().await?; + let mut chain = Chain::new(); + chain.feed(messages); + let mut sentences = chain.generate(); + let mut msg = String::new(); + for _ in 1..rand::thread_rng().gen_range(2, 10) { + msg = format!("{} {}", msg, sentences.pop().unwrap()); + } + match api + .send(message.text_reply(msg.trim()).parse_mode(ParseMode::Html)) + .await + { + Ok(_) => debug!("/markov command sent to {}", message.chat.id()), + Err(_) => warn!("/markov command sent failed to {}", message.chat.id()), + } + //api.send(message.chat.text("Text to message chat")).await?; + //api.send(message.from.text("Private text")).await?; + Ok(()) +} diff --git a/src/db.rs b/src/db.rs index 716a238..d8559cd 100644 --- a/src/db.rs +++ b/src/db.rs @@ -115,6 +115,23 @@ pub(crate) async fn get_random_messages() -> Result, Error> { Ok(messages) } +pub(crate) async fn get_random_messages_group() -> Result, Error> { + let conn = open()?; + let mut stmt = conn.prepare_cached(" + SELECT m.text FROM messages m + LEFT JOIN relations r ON r.msg_id = m.id + ORDER BY RANDOM() LIMIT 50 + " + )?; + let mut rows = stmt.query_named(named_params![])?; + let mut messages = Vec::new(); + + while let Some(row) = rows.next()? { + messages.push(row.get(0)?) + } + Ok(messages) +} + pub(crate) fn get_members(id: telegram_bot::ChatId) -> Result> { let conn = open()?; let mut stmt = conn.prepare_cached( diff --git a/src/handlers.rs b/src/handlers.rs index 65f9eec..aacc520 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -31,6 +31,7 @@ pub async fn handler( "/top" => commands::top(api, message).await?, "/stat" => commands::top(api, message).await?, "/markov_all" => commands::markov_all(api, message).await?, + "/markov" => commands::markov(api, message).await?, _ => (), } }