telegram.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // This bot throws a dice on each incoming message.
  2. use derive_more::From;
  3. use teloxide::prelude::*;
  4. use teloxide::types::*;
  5. use teloxide::{net::Download, types::File as TgFile, Bot};
  6. use teloxide::{DownloadError, RequestError};
  7. use thiserror::Error;
  8. use tokio::fs::File;
  9. #[cfg(feature = "telegram")]
  10. #[tokio::main]
  11. pub async fn bot() {
  12. run().await;
  13. }
  14. /// Possible error while receiving a file
  15. #[cfg(feature = "telegram")]
  16. #[derive(Debug, Error, From)]
  17. enum FileReceiveError {
  18. /// Download process error
  19. #[error("File download error: {0}")]
  20. Download(#[source] DownloadError),
  21. /// Telegram request error
  22. #[error("Web request error: {0}")]
  23. Request(#[source] RequestError),
  24. /// Io error while writing file
  25. #[error("An I/O error: {0}")]
  26. Io(#[source] std::io::Error),
  27. }
  28. #[cfg(feature = "telegram")]
  29. async fn download_file(downloader: &Bot, file_id: &str) -> Result<String, FileReceiveError> {
  30. let TgFile {
  31. file_id, file_path, ..
  32. } = downloader.get_file(file_id).send().await?;
  33. let filepath = format!("/tmp/{}", file_id);
  34. let mut file = File::create(&filepath).await?;
  35. downloader.download_file(&file_path, &mut file).await?;
  36. Ok(filepath)
  37. }
  38. #[cfg(feature = "telegram")]
  39. async fn run() {
  40. teloxide::enable_logging!();
  41. log::info!("Starting dices_bot...");
  42. let bot = Bot::from_env().auto_send();
  43. teloxide::repl(bot, |message| async move {
  44. let update = &message.update;
  45. if let MessageKind::Common(msg) = &update.kind {
  46. if let MediaKind::Document(doc) = &msg.media_kind {
  47. if let Ok(newfile) =
  48. download_file(&message.requester.inner(), &doc.document.file_id).await
  49. {
  50. message
  51. .answer(format!("File received: {:} ", newfile))
  52. .await?;
  53. }
  54. message.answer_dice().await?;
  55. }
  56. }
  57. respond(())
  58. })
  59. .await;
  60. }