use std::sync::Arc;
use anyhow::Result;
use log::*;
use mobot::{
api::{SendMessageRequest, API},
handlers::auth_handler,
*,
};
async fn handle_chat_event(e: Event, _: State<()>) -> Result<Action, anyhow::Error> {
Ok(Action::ReplyText(format!(
"pong: {}",
e.update.from_user()?.username.as_ref().unwrap()
)))
}
async fn error_handler<S: handler::BotState>(
api: Arc<API>,
chat_id: i64,
_: State<S>,
err: anyhow::Error,
) {
error!("Error: {}", err);
let result = api
.send_message(&SendMessageRequest {
chat_id,
text: format!("Sorry! {}.", err),
..Default::default()
})
.await;
if let Err(err) = result {
error!("Error in default error handler: {}", err);
}
}
#[tokio::test]
async fn it_works() {
mobot::init_logger();
let fakeserver = fake::FakeAPI::new();
let client = Client::new("token".to_string()).with_post_handler(fakeserver.clone());
let mut router = Router::new(client)
.with_poll_timeout_s(1)
.with_error_handler(error_handler);
let (shutdown_notifier, shutdown_tx) = router.shutdown();
router
.add_route(Route::Default, auth_handler(vec!["qubyte".to_string()]))
.add_route(Route::Default, handle_chat_event);
tokio::spawn(async move {
info!("Starting router...");
router.start().await;
});
let chat = fakeserver.create_chat("qubyte").await;
chat.send_text("ping1").await.unwrap();
assert_eq!(
chat.recv_update().await.unwrap().to_string(),
"pong: qubyte"
);
let chat2 = fakeserver.create_chat("hacker").await;
chat2.send_text("ping1").await.unwrap();
assert_eq!(
chat2.recv_update().await.unwrap().to_string(),
"Sorry! Unauthorized user: hacker."
);
info!("Shutting down...");
shutdown_tx.send(()).await.unwrap();
shutdown_notifier.notified().await;
}