teloxide-fork 0.19.0

An elegant Telegram bots framework for Rust
Documentation
//! Receive Telegram updates as a [`futures::Stream`] without a dispatcher.
//!
//! ```no_run
//! use futures::StreamExt;
//! use teloxide::{prelude::*, types::UpdateKind};
//!
//! #[tokio::main]
//! async fn main() {
//!     let bot = Bot::from_env();
//!     let mut updates = bot.update_stream().build().await;
//!
//!     while let Some(item) = updates.next().await {
//!         match item {
//!             Ok(update) => {
//!                 if let UpdateKind::Message(message) = update.kind {
//!                     if let Some(text) = message.text() {
//!                         bot.send_message(text)
//!                             .chat_id(message.chat.id)
//!                             .await
//!                             .log_on_error()
//!                             .await;
//!                     }
//!                 }
//!             }
//!             Err(error) => log::error!("Could not receive update: {error}"),
//!         }
//!     }
//! }
//! ```
//!
//! For a manually configured polling listener or a webhook listener, use
//! [`UpdateStream::from_listener`] instead.

use std::{
    pin::Pin,
    task::{Context, Poll},
    time::Duration,
};

use futures::{Stream, StreamExt};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;

use crate::{
    stop::StopToken,
    types::{AllowedUpdate, Update},
    update_listeners::{Polling, PollingBuilder, UpdateListener},
    Bot, RequestError,
};

/// Adds [`update_stream`](Self::update_stream) to [`Bot`].
pub trait UpdateStreamExt {
    /// Configures a stream backed by long polling, with a 10-second polling
    /// timeout by default.
    ///
    /// Do not run another polling consumer for the same bot concurrently.
    fn update_stream(&self) -> UpdateStreamBuilder;
}

impl UpdateStreamExt for Bot {
    fn update_stream(&self) -> UpdateStreamBuilder {
        UpdateStreamBuilder(Polling::builder(self.clone()).timeout(Duration::from_secs(10)))
    }
}

/// Configures a long-polling [`UpdateStream`].
#[must_use = "the builder does nothing until build is called"]
pub struct UpdateStreamBuilder(PollingBuilder<Bot>);

impl UpdateStreamBuilder {
    /// Sets the long polling timeout. Defaults to 10 seconds.
    pub fn timeout(self, timeout: Duration) -> Self {
        Self(self.0.timeout(timeout))
    }

    /// Sets how many updates to retrieve per request. Panics outside `1..=100`.
    #[track_caller]
    pub fn limit(self, limit: u8) -> Self {
        Self(self.0.limit(limit))
    }

    /// Selects the update types to receive.
    pub fn allowed_updates(self, allowed: Vec<AllowedUpdate>) -> Self {
        Self(self.0.allowed_updates(allowed))
    }

    /// Drops pending updates on startup.
    pub fn drop_pending_updates(self) -> Self {
        Self(self.0.drop_pending_updates())
    }

    /// Removes any configured webhook (logging errors) and starts polling.
    pub async fn build(self) -> UpdateStream {
        UpdateStream::from_listener(self.0.delete_webhook().await.build())
    }
}

/// A stream yielding updates and errors from an update listener.
///
/// The listener runs in a Tokio task, forwarding items through a bounded
/// channel. Polling errors are yielded as items, not treated as stream end.
#[must_use = "streams do nothing unless consumed"]
pub struct UpdateStream<E = RequestError> {
    receiver: ReceiverStream<Result<Update, E>>,
    stop: StopToken,
}

impl<E> UpdateStream<E> {
    /// Runs an existing [`UpdateListener`] as an owned stream.
    ///
    /// This must be called from within a Tokio runtime. For example, with the
    /// `webhooks-axum` feature, pass the listener returned by
    /// `teloxide::update_listeners::webhooks::axum` to this method.
    pub fn from_listener<L>(mut listener: L) -> Self
    where
        L: UpdateListener<Err = E> + Send + 'static,
        E: Send + 'static,
    {
        let stop = listener.stop_token();
        let (send, receive) = mpsc::channel(1);

        tokio::spawn(async move {
            let mut stream = std::pin::pin!(listener.as_stream());

            // Wait for capacity before asking the listener for the next item.
            while let Ok(permit) = send.reserve().await {
                let item = tokio::select! {
                    item = stream.next() => item,
                    _ = send.closed() => break,
                };
                let Some(item) = item else { break };
                permit.send(item);
            }
        });

        Self { receiver: ReceiverStream::new(receive), stop }
    }

    /// Signals the listener to stop. Keep reading until the stream returns
    /// `None` so the listener can finish shutting down and buffered items can
    /// be delivered. Dropping the stream also signals the listener to stop,
    /// but does not wait for graceful shutdown.
    pub fn shutdown(&self) {
        self.stop.stop();
    }
}

impl<E> Stream for UpdateStream<E> {
    type Item = Result<Update, E>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.receiver.poll_next_unpin(cx)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.receiver.size_hint()
    }
}

impl<E> Drop for UpdateStream<E> {
    fn drop(&mut self) {
        self.shutdown();
    }
}

#[cfg(test)]
mod tests {
    use futures::stream;

    use super::*;
    use crate::{stop::mk_stop_token, update_listeners::StatefulListener};

    #[tokio::test]
    async fn shutdown_drains_items_and_signals_listener() {
        let (token, flag) = mk_stop_token();
        let listener = StatefulListener::new(
            token,
            |_: &mut StopToken| stream::iter([Err::<Update, _>(1), Err(2)]),
            |token: &mut StopToken| token.clone(),
        );
        let mut updates = UpdateStream::from_listener(listener);

        updates.shutdown();
        assert!(flag.is_stopped());
        assert_eq!(updates.next().await.unwrap().unwrap_err(), 1);
        assert_eq!(updates.next().await.unwrap().unwrap_err(), 2);
        assert!(updates.next().await.is_none());
    }

    #[tokio::test]
    async fn dropping_stream_signals_listener() {
        let (token, flag) = mk_stop_token();
        let listener = StatefulListener::new(
            token,
            |_: &mut StopToken| stream::pending::<Result<Update, ()>>(),
            |token: &mut StopToken| token.clone(),
        );
        drop(UpdateStream::from_listener(listener));
        assert!(flag.is_stopped());
    }
}