Annotation For src/tg_bot.rs
Logged in as anonymous

Origin for each line in src/tg_bot.rs from check-in be0b8602d1:

9adc69d514 2026-03-25    1: use crate::{
9adc69d514 2026-03-25    2: 	Arc,
9adc69d514 2026-03-25    3: 	Mutex,
3fd8c40aa8 2026-03-30    4: 	core::FeedList,
9adc69d514 2026-03-25    5: };
9adc69d514 2026-03-25    6: 
9adc69d514 2026-03-25    7: use std::{
9adc69d514 2026-03-25    8: 	borrow::Cow,
9adc69d514 2026-03-25    9: 	fmt,
be0b8602d1 2026-04-18   10: 	time::Duration,
9adc69d514 2026-03-25   11: };
9adc69d514 2026-03-25   12: 
13265e7697 2026-01-10   13: use serde::{
13265e7697 2026-01-10   14: 	Deserialize,
13265e7697 2026-01-10   15: 	Serialize,
13265e7697 2026-01-10   16: };
be0b8602d1 2026-04-18   17: use smol::Timer;
9c4f09193a 2026-01-09   18: use stacked_errors::{
9adc69d514 2026-03-25   19: 	bail,
9c4f09193a 2026-01-09   20: 	Result,
9c4f09193a 2026-01-09   21: 	StackableErr,
9c4f09193a 2026-01-09   22: };
9c4f09193a 2026-01-09   23: use tgbot::{
be0b8602d1 2026-04-18   24: 	api::{
be0b8602d1 2026-04-18   25: 		Client,
be0b8602d1 2026-04-18   26: 		ExecuteError
be0b8602d1 2026-04-18   27: 	},
9c4f09193a 2026-01-09   28: 	types::{
3fd8c40aa8 2026-03-30   29: 		AnswerCallbackQuery,
9c4f09193a 2026-01-09   30: 		Bot,
9c4f09193a 2026-01-09   31: 		ChatPeerId,
be0b8602d1 2026-04-18   32: 		EditMessageResult,
be0b8602d1 2026-04-18   33: 		EditMessageText,
9c4f09193a 2026-01-09   34: 		GetBot,
13265e7697 2026-01-10   35: 		InlineKeyboardButton,
13265e7697 2026-01-10   36: 		InlineKeyboardMarkup,
9c4f09193a 2026-01-09   37: 		Message,
9c4f09193a 2026-01-09   38: 		ParseMode,
9c4f09193a 2026-01-09   39: 		SendMessage,
9c4f09193a 2026-01-09   40: 	},
9c4f09193a 2026-01-09   41: };
13265e7697 2026-01-10   42: 
9adc69d514 2026-03-25   43: const CB_VERSION: u8 = 0;
9adc69d514 2026-03-25   44: 
13265e7697 2026-01-10   45: #[derive(Serialize, Deserialize, Debug)]
9adc69d514 2026-03-25   46: pub enum Callback {
3fd8c40aa8 2026-03-30   47: 	// Edit one feed (version, name)
3fd8c40aa8 2026-03-30   48: 	Edit(u8, String),
9adc69d514 2026-03-25   49: 	// List all feeds (version, name to show, page number)
be0b8602d1 2026-04-18   50: 	List(u8, String, usize),
3fd8c40aa8 2026-03-30   51: 	// Show root menu (version)
3fd8c40aa8 2026-03-30   52: 	Menu(u8),
9adc69d514 2026-03-25   53: }
9adc69d514 2026-03-25   54: 
9adc69d514 2026-03-25   55: impl Callback {
3fd8c40aa8 2026-03-30   56: 	pub fn edit <S>(text: S) -> Callback
3fd8c40aa8 2026-03-30   57: 	where S: Into<String> {
3fd8c40aa8 2026-03-30   58: 		Callback::Edit(CB_VERSION, text.into())
3fd8c40aa8 2026-03-30   59: 	}
3fd8c40aa8 2026-03-30   60: 
be0b8602d1 2026-04-18   61: 	pub fn list <S>(text: S, page: usize) -> Callback
3fd8c40aa8 2026-03-30   62: 	where S: Into<String> {
3fd8c40aa8 2026-03-30   63: 		Callback::List(CB_VERSION, text.into(), page)
3fd8c40aa8 2026-03-30   64: 	}
3fd8c40aa8 2026-03-30   65: 
3fd8c40aa8 2026-03-30   66: 	pub fn menu () -> Callback {
3fd8c40aa8 2026-03-30   67: 		Callback::Menu(CB_VERSION)
9adc69d514 2026-03-25   68: 	}
9adc69d514 2026-03-25   69: 
9adc69d514 2026-03-25   70: 	fn version (&self) -> u8 {
9adc69d514 2026-03-25   71: 		match self {
3fd8c40aa8 2026-03-30   72: 			Callback::Edit(version, .. ) => *version,
9adc69d514 2026-03-25   73: 			Callback::List(version, .. ) => *version,
3fd8c40aa8 2026-03-30   74: 			Callback::Menu(version) => *version,
9adc69d514 2026-03-25   75: 		}
9adc69d514 2026-03-25   76: 	}
9adc69d514 2026-03-25   77: }
9adc69d514 2026-03-25   78: 
9adc69d514 2026-03-25   79: impl fmt::Display for Callback {
9adc69d514 2026-03-25   80: 	fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result {
9adc69d514 2026-03-25   81: 		f.write_str(&toml::to_string(self).map_err(|_| fmt::Error)?)
9adc69d514 2026-03-25   82: 	}
13265e7697 2026-01-10   83: }
13265e7697 2026-01-10   84: 
9adc69d514 2026-03-25   85: /// Produce new Keyboard Markup from current Callback
be0b8602d1 2026-04-18   86: pub async fn get_kb (cb: &Callback, feeds: &Arc<Mutex<FeedList>>) -> Result<InlineKeyboardMarkup> {
9adc69d514 2026-03-25   87: 	if cb.version() != CB_VERSION {
9adc69d514 2026-03-25   88: 		bail!("Wrong callback version.");
9adc69d514 2026-03-25   89: 	}
9adc69d514 2026-03-25   90: 	let mark = match cb {
3fd8c40aa8 2026-03-30   91: 		Callback::Edit(_, _name) => { // XXX edit missing
3fd8c40aa8 2026-03-30   92: 			let kb: Vec<Vec<InlineKeyboardButton>> = vec![];
3fd8c40aa8 2026-03-30   93: 			InlineKeyboardMarkup::from(kb)
3fd8c40aa8 2026-03-30   94: 		},
9adc69d514 2026-03-25   95: 		Callback::List(_, name, page) => {
9adc69d514 2026-03-25   96: 			let mut kb = vec![];
9adc69d514 2026-03-25   97: 			let feeds = feeds.lock_arc().await;
9adc69d514 2026-03-25   98: 			let long = feeds.len() > 6;
9adc69d514 2026-03-25   99: 			let (start, end) = if long {
be0b8602d1 2026-04-18  100: 				(page * 5, 5 + page * 5)
9adc69d514 2026-03-25  101: 			} else {
9adc69d514 2026-03-25  102: 				(0, 6)
9adc69d514 2026-03-25  103: 			};
9adc69d514 2026-03-25  104: 			let mut i = 0;
9adc69d514 2026-03-25  105: 			if name.is_empty() {
be0b8602d1 2026-04-18  106: 				let feed_iter = feeds.iter().skip(start);
be0b8602d1 2026-04-18  107: 				for (id, name) in feed_iter {
374eadef45 2026-03-28  108: 					kb.push(vec![
374eadef45 2026-03-28  109: 						InlineKeyboardButton::for_callback_data(
374eadef45 2026-03-28  110: 							format!("{}. {}", id, name),
3fd8c40aa8 2026-03-30  111: 							Callback::edit(name).to_string()),
374eadef45 2026-03-28  112: 					]);
be0b8602d1 2026-04-18  113: 					i += 1;
be0b8602d1 2026-04-18  114: 					if i == end { break }
374eadef45 2026-03-28  115: 				}
9adc69d514 2026-03-25  116: 			} else {
374eadef45 2026-03-28  117: 				let mut found = false;
374eadef45 2026-03-28  118: 				let mut first_page = None;
374eadef45 2026-03-28  119: 				for (id, feed_name) in feeds.iter() {
374eadef45 2026-03-28  120: 					if name == feed_name {
374eadef45 2026-03-28  121: 						found = true;
374eadef45 2026-03-28  122: 					}
374eadef45 2026-03-28  123: 					i += 1;
374eadef45 2026-03-28  124: 					kb.push(vec![
374eadef45 2026-03-28  125: 						InlineKeyboardButton::for_callback_data(
374eadef45 2026-03-28  126: 							format!("{}. {}", id, feed_name),
374eadef45 2026-03-28  127: 							Callback::list("xxx", *page).to_string()), // XXX edit
374eadef45 2026-03-28  128: 					]);
be0b8602d1 2026-04-18  129: 					if i == end {
374eadef45 2026-03-28  130: 						// page complete, if found we got the right page, if not - reset and
374eadef45 2026-03-28  131: 						// continue.
374eadef45 2026-03-28  132: 						if found {
374eadef45 2026-03-28  133: 							break
374eadef45 2026-03-28  134: 						} else {
374eadef45 2026-03-28  135: 							if first_page.is_none() {
374eadef45 2026-03-28  136: 								first_page = Some(kb);
374eadef45 2026-03-28  137: 							}
374eadef45 2026-03-28  138: 							kb = vec![];
374eadef45 2026-03-28  139: 							i = 0
374eadef45 2026-03-28  140: 						}
374eadef45 2026-03-28  141: 					}
374eadef45 2026-03-28  142: 				}
374eadef45 2026-03-28  143: 				if !found {
374eadef45 2026-03-28  144: 					// name not found, showing first page
374eadef45 2026-03-28  145: 					kb = first_page.unwrap_or_default();
374eadef45 2026-03-28  146: 				}
9adc69d514 2026-03-25  147: 			}
9adc69d514 2026-03-25  148: 			if long {
9adc69d514 2026-03-25  149: 				kb.push(vec![
9adc69d514 2026-03-25  150: 					InlineKeyboardButton::for_callback_data("<<",
9adc69d514 2026-03-25  151: 						Callback::list("", if *page == 0 { *page } else { page - 1 } ).to_string()),
9adc69d514 2026-03-25  152: 					InlineKeyboardButton::for_callback_data(">>",
9adc69d514 2026-03-25  153: 						Callback::list("", page + 1).to_string()),
9adc69d514 2026-03-25  154: 				]);
9adc69d514 2026-03-25  155: 			}
9adc69d514 2026-03-25  156: 			InlineKeyboardMarkup::from(kb)
9adc69d514 2026-03-25  157: 		},
3fd8c40aa8 2026-03-30  158: 		Callback::Menu(_) => {
3fd8c40aa8 2026-03-30  159: 			let kb = vec![
3fd8c40aa8 2026-03-30  160: 				vec![
3fd8c40aa8 2026-03-30  161: 					InlineKeyboardButton::for_callback_data(
3fd8c40aa8 2026-03-30  162: 						"Add new channel",
3fd8c40aa8 2026-03-30  163: 						Callback::menu().to_string()), // new XXX
3fd8c40aa8 2026-03-30  164: 				],
3fd8c40aa8 2026-03-30  165: 				vec![
3fd8c40aa8 2026-03-30  166: 					InlineKeyboardButton::for_callback_data(
3fd8c40aa8 2026-03-30  167: 						"List channels",
3fd8c40aa8 2026-03-30  168: 						Callback::list("", 0).to_string()),
3fd8c40aa8 2026-03-30  169: 				],
3fd8c40aa8 2026-03-30  170: 			];
3fd8c40aa8 2026-03-30  171: 			InlineKeyboardMarkup::from(kb)
3fd8c40aa8 2026-03-30  172: 		},
9adc69d514 2026-03-25  173: 	};
13265e7697 2026-01-10  174: 	Ok(mark)
9adc69d514 2026-03-25  175: }
9adc69d514 2026-03-25  176: 
9adc69d514 2026-03-25  177: pub enum MyMessage <'a> {
9adc69d514 2026-03-25  178: 	Html { text: Cow<'a, str> },
9adc69d514 2026-03-25  179: 	HtmlTo { text: Cow<'a, str>, to: ChatPeerId },
9adc69d514 2026-03-25  180: 	HtmlToKb { text: Cow<'a, str>, to: ChatPeerId, kb: InlineKeyboardMarkup },
9adc69d514 2026-03-25  181: }
9adc69d514 2026-03-25  182: 
9adc69d514 2026-03-25  183: impl MyMessage <'_> {
9adc69d514 2026-03-25  184: 	pub fn html <'a, S> (text: S) -> MyMessage<'a>
9adc69d514 2026-03-25  185: 	where S: Into<Cow<'a, str>> {
9adc69d514 2026-03-25  186: 		let text = text.into();
9adc69d514 2026-03-25  187: 		MyMessage::Html { text }
9adc69d514 2026-03-25  188: 	}
9adc69d514 2026-03-25  189: 	
9adc69d514 2026-03-25  190: 	pub fn html_to <'a, S> (text: S, to: ChatPeerId) -> MyMessage<'a>
9adc69d514 2026-03-25  191: 	where S: Into<Cow<'a, str>> {
9adc69d514 2026-03-25  192: 		let text = text.into();
9adc69d514 2026-03-25  193: 		MyMessage::HtmlTo { text, to }
9adc69d514 2026-03-25  194: 	}
9adc69d514 2026-03-25  195: 	
9adc69d514 2026-03-25  196: 	pub fn html_to_kb <'a, S> (text: S, to: ChatPeerId, kb: InlineKeyboardMarkup) -> MyMessage<'a>
9adc69d514 2026-03-25  197: 	where S: Into<Cow<'a, str>> {
9adc69d514 2026-03-25  198: 		let text = text.into();
9adc69d514 2026-03-25  199: 		MyMessage::HtmlToKb { text, to, kb }
9adc69d514 2026-03-25  200: 	}
9adc69d514 2026-03-25  201: 	
9adc69d514 2026-03-25  202: 	fn req (&self, tg: &Tg) -> Result<SendMessage> {
9adc69d514 2026-03-25  203: 		Ok(match self {
9adc69d514 2026-03-25  204: 			MyMessage::Html { text } =>
9adc69d514 2026-03-25  205: 				SendMessage::new(tg.owner, text.as_ref())
9adc69d514 2026-03-25  206: 					.with_parse_mode(ParseMode::Html),
9adc69d514 2026-03-25  207: 			MyMessage::HtmlTo { text, to } =>
9adc69d514 2026-03-25  208: 				SendMessage::new(*to, text.as_ref())
9adc69d514 2026-03-25  209: 					.with_parse_mode(ParseMode::Html),
9adc69d514 2026-03-25  210: 			MyMessage::HtmlToKb { text, to, kb } =>
9adc69d514 2026-03-25  211: 				SendMessage::new(*to, text.as_ref())
9adc69d514 2026-03-25  212: 					.with_parse_mode(ParseMode::Html)
9adc69d514 2026-03-25  213: 					.with_reply_markup(kb.clone()),
9adc69d514 2026-03-25  214: 		})
9adc69d514 2026-03-25  215: 	}
13265e7697 2026-01-10  216: }
9c4f09193a 2026-01-09  217: 
9c4f09193a 2026-01-09  218: #[derive(Clone)]
9c4f09193a 2026-01-09  219: pub struct Tg {
9c4f09193a 2026-01-09  220: 	pub me: Bot,
9c4f09193a 2026-01-09  221: 	pub owner: ChatPeerId,
9c4f09193a 2026-01-09  222: 	pub client: Client,
9c4f09193a 2026-01-09  223: }
9c4f09193a 2026-01-09  224: 
9c4f09193a 2026-01-09  225: impl Tg {
fabcca1eaf 2026-01-09  226: 	/// Construct a new `Tg` instance from configuration.
fabcca1eaf 2026-01-09  227: 	///
fabcca1eaf 2026-01-09  228: 	/// The `settings` must provide the following keys:
fabcca1eaf 2026-01-09  229: 	///  - `"api_key"` (string),
fabcca1eaf 2026-01-09  230: 	///  - `"owner"` (integer chat id),
fabcca1eaf 2026-01-09  231: 	///  - `"api_gateway"` (string).
fabcca1eaf 2026-01-09  232: 	///
fabcca1eaf 2026-01-09  233: 	/// The function initialises the client, configures the gateway and fetches the bot identity
fabcca1eaf 2026-01-09  234: 	/// before returning the constructed `Tg`.
9c4f09193a 2026-01-09  235: 	pub async fn new (settings: &config::Config) -> Result<Tg> {
9c4f09193a 2026-01-09  236: 		let api_key = settings.get_string("api_key").stack()?;
9c4f09193a 2026-01-09  237: 
9c4f09193a 2026-01-09  238: 		let owner = ChatPeerId::from(settings.get_int("owner").stack()?);
be0b8602d1 2026-04-18  239: 		// We don't use retries, as in async environment this will just get us stuck for extra
be0b8602d1 2026-04-18  240: 		// amount of time on simple requests. Just bail, show error and ack it in the code. In
be0b8602d1 2026-04-18  241: 		// other case we might got stuck with multiple open transactions in database.
9c4f09193a 2026-01-09  242: 		let client = Client::new(&api_key).stack()?
9c4f09193a 2026-01-09  243: 			.with_host(settings.get_string("api_gateway").stack()?)
9c4f09193a 2026-01-09  244: 			.with_max_retries(0);
9c4f09193a 2026-01-09  245: 		let me = client.execute(GetBot).await.stack()?;
9c4f09193a 2026-01-09  246: 		Ok(Tg {
9c4f09193a 2026-01-09  247: 			me,
9c4f09193a 2026-01-09  248: 			owner,
9c4f09193a 2026-01-09  249: 			client,
9c4f09193a 2026-01-09  250: 		})
9c4f09193a 2026-01-09  251: 	}
9c4f09193a 2026-01-09  252: 
fabcca1eaf 2026-01-09  253: 	/// Send a text message to a chat, using an optional target and parse mode.
fabcca1eaf 2026-01-09  254: 	///
fabcca1eaf 2026-01-09  255: 	/// # Returns
fabcca1eaf 2026-01-09  256: 	/// The sent `Message` on success.
9adc69d514 2026-03-25  257: 	pub async fn send (&self, msg: MyMessage<'_>) -> Result<Message> {
9adc69d514 2026-03-25  258: 		self.client.execute(msg.req(self)?).await.stack()
9adc69d514 2026-03-25  259: 	}
9adc69d514 2026-03-25  260: 
3fd8c40aa8 2026-03-30  261: 	pub async fn answer_cb (&self, id: String, text: String) -> Result<bool> {
3fd8c40aa8 2026-03-30  262: 		self.client.execute(
3fd8c40aa8 2026-03-30  263: 			AnswerCallbackQuery::new(id)
3fd8c40aa8 2026-03-30  264: 				.with_text(text)
3fd8c40aa8 2026-03-30  265: 		).await.stack()
3fd8c40aa8 2026-03-30  266: 	}
3fd8c40aa8 2026-03-30  267: 
fabcca1eaf 2026-01-09  268: 	/// Create a copy of this `Tg` with the owner replaced by the given chat ID.
fabcca1eaf 2026-01-09  269: 	///
fabcca1eaf 2026-01-09  270: 	/// # Parameters
fabcca1eaf 2026-01-09  271: 	/// - `owner`: The Telegram chat identifier to set as the new owner (expressed as an `i64`).
fabcca1eaf 2026-01-09  272: 	///
fabcca1eaf 2026-01-09  273: 	/// # Returns
fabcca1eaf 2026-01-09  274: 	/// A new `Tg` instance identical to the original except its `owner` field is set to the provided chat ID.
fabcca1eaf 2026-01-09  275: 	pub fn with_owner <O>(&self, owner: O) -> Tg
fabcca1eaf 2026-01-09  276: 	where O: Into<i64> {
9c4f09193a 2026-01-09  277: 		Tg {
fabcca1eaf 2026-01-09  278: 			owner: ChatPeerId::from(owner.into()),
9c4f09193a 2026-01-09  279: 			..self.clone()
be0b8602d1 2026-04-18  280: 		}
be0b8602d1 2026-04-18  281: 	}
be0b8602d1 2026-04-18  282: 
be0b8602d1 2026-04-18  283: 	pub async fn update_message (&self, chat_id: i64, message_id: i64, text: String, feeds: &Arc<Mutex<FeedList>>, cb: Callback) -> Result<EditMessageResult> {
be0b8602d1 2026-04-18  284: 		loop {
be0b8602d1 2026-04-18  285: 			let req = EditMessageText::for_chat_message(chat_id, message_id, &text)
be0b8602d1 2026-04-18  286: 				.with_reply_markup(get_kb(&cb, feeds).await.stack()?);
be0b8602d1 2026-04-18  287: 			let res = self.client.execute(req).await;
be0b8602d1 2026-04-18  288: 			match res {
be0b8602d1 2026-04-18  289: 				Ok(res) => return Ok(res),
be0b8602d1 2026-04-18  290: 				Err(ref err) => {
be0b8602d1 2026-04-18  291: 					if let ExecuteError::Response(resp) = err
be0b8602d1 2026-04-18  292: 						&& let Some(delay) = resp.retry_after()
be0b8602d1 2026-04-18  293: 					{
be0b8602d1 2026-04-18  294: 						if delay > 60 {
be0b8602d1 2026-04-18  295: 							return res.context("Delay too big (>60), not waiting.");
be0b8602d1 2026-04-18  296: 						}
be0b8602d1 2026-04-18  297: 						Timer::after(Duration::from_secs(delay)).await;
be0b8602d1 2026-04-18  298: 					} else {
be0b8602d1 2026-04-18  299: 						return res.context("Can't update message");
be0b8602d1 2026-04-18  300: 					}
be0b8602d1 2026-04-18  301: 				},
be0b8602d1 2026-04-18  302: 			};
9c4f09193a 2026-01-09  303: 		}
9c4f09193a 2026-01-09  304: 	}
9c4f09193a 2026-01-09  305: }