use std::time::Duration;
use tokio::sync::mpsc;
use vaegram::types::{Message, Text};
use vaegram::{Client, ClientBuilder, Error, Result, filters};
const REPLY_TIMEOUT: Duration = Duration::from_secs(30);
pub struct Kit {
pub user: User,
pub bot: Client,
_disconnect: Disconnect,
}
pub struct Disconnect(pub Vec<Client>);
impl Drop for Disconnect {
fn drop(&mut self) {
for client in &self.0 {
client.disconnect();
}
}
}
pub struct User {
pub client: Client,
received: tokio::sync::Mutex<mpsc::UnboundedReceiver<Message>>,
}
impl Kit {
pub async fn from_env() -> Option<Kit> {
let vars = (std::env::var("VAEGRAM_USER_SESSION"), std::env::var("VAEGRAM_BOT_TOKEN"));
let (Ok(session), Ok(token)) = vars else {
eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name) and VAEGRAM_BOT_TOKEN");
return None;
};
let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
let (api_id, api_hash): (i32, String) = (env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"));
let user = Client::builder(session, api_id, api_hash.clone()).catch_up(false).connect().await.unwrap();
let bot =
start_bot(Client::builder("target/vaegram-kit-bot", api_id, api_hash).bot_token(token).catch_up(false))
.await?;
let (tx, received) = mpsc::unbounded_channel();
user.on_message(filters::private(), move |m| {
if !m.outgoing {
let _ = tx.send(m);
}
async { Ok(()) }
});
let (started_tx, mut started) = mpsc::unbounded_channel();
for client in [&user, &bot] {
let started_tx = started_tx.clone();
client.on_start(move |_| {
let _ = started_tx.send(());
async { Ok(()) }
});
let client = client.clone();
tokio::spawn(async move { client.run().await });
}
for _ in 0..2 {
tokio::time::timeout(REPLY_TIMEOUT, started.recv()).await.expect("a kit client's run didn't start");
}
let disconnect = Disconnect(vec![user.clone(), bot.clone()]);
let user = User { client: user, received: tokio::sync::Mutex::new(received) };
Some(Kit { user, bot, _disconnect: disconnect })
}
}
pub fn flood_limited(error: &Error, what: &str) -> bool {
let Some(wait) = error.flood_wait() else { return false };
eprintln!("skipped: {what} is flood-limited for {}s", wait.as_secs());
true
}
#[allow(dead_code)] pub fn story_limit_reached(error: &Error) -> bool {
if !error.is("STORIES_TOO_MUCH") {
return false;
}
eprintln!("skipped: the account can't post another story for now (STORIES_TOO_MUCH)");
true
}
pub async fn start_bot(builder: ClientBuilder) -> Option<Client> {
match builder.start().await {
Ok(bot) => Some(bot),
Err(e) if flood_limited(&e, "logging the bot into new storage") => None,
Err(e) => panic!("the bot didn't log in: {e:?}"),
}
}
#[allow(dead_code)] pub fn cleanup(result: Result<()>, what: &str) {
let Err(e) = result else { return };
match e.flood_wait() {
Some(wait) => eprintln!("skipped the cleanup: {what} is flood-limited for {}s; do it by hand", wait.as_secs()),
None => panic!("{what} failed: {e:?}"),
}
}
#[allow(dead_code)] pub async fn test_supergroup(user: &Client) -> Option<i64> {
match user.create_supergroup("vaegram live test", "deleted right away").await {
Ok(chat) => Some(chat.id),
Err(e) if flood_limited(&e, "creating a supergroup") => None,
Err(e) => panic!("creating a supergroup failed: {e:?}"),
}
}
impl User {
pub async fn send_and_wait_reply(&self, bot: &Client, text: impl Into<Text>) -> Result<Message> {
let me = bot.get_me().await?;
let username = me.username.ok_or(Error::Unexpected("the bot has no username"))?;
let bot_id = self.client.resolve_username(&username).await?;
let mut received = self.received.lock().await;
let sent = self.client.send_message(bot_id, text).await?.id;
self.next_reply(&mut received, bot_id, sent).await
}
#[allow(dead_code)] pub async fn wait_reply(&self, bot_id: i64, to: i32) -> Result<Message> {
self.next_reply(&mut *self.received.lock().await, bot_id, to).await
}
async fn next_reply(
&self,
received: &mut mpsc::UnboundedReceiver<Message>,
bot_id: i64,
to: i32,
) -> Result<Message> {
let waited = tokio::time::timeout(REPLY_TIMEOUT, async {
loop {
match received.recv().await {
Some(m) if m.chat.id == bot_id && m.id > to && m.reply_to_message_id == Some(to) => return Ok(m),
Some(_) => {}
None => return Err(Error::Disconnected),
}
}
})
.await;
let Ok(reply) = waited else {
let last = self.client.get_chat_history(bot_id).limit(5).await;
let last: Vec<_> = last.iter().flatten().map(|m| (m.id, m.outgoing, m.reply_to_message_id)).collect();
eprintln!(
"no reply to {to} within {REPLY_TIMEOUT:?}; the chat's last messages (id, outgoing, reply to): {last:?}"
);
return Err(Error::Timeout);
};
reply
}
}