golgi/examples/ssb-stream-example.rs

86 lines
2.5 KiB
Rust

use std::process;
use async_std::stream::StreamExt;
use futures::{pin_mut, TryStreamExt};
use golgi::error::GolgiError;
use golgi::messages::{SsbMessageContentType, SsbMessageValue};
use golgi::sbot::Sbot;
async fn run() -> Result<(), GolgiError> {
let mut sbot_client = Sbot::connect(None, None).await?;
let id = sbot_client.whoami().await?;
println!("whoami: {}", id);
let author = id.clone();
// create a history stream
let history_stream = sbot_client
.create_history_stream(author.to_string())
.await?;
// loop through the results until the end of the stream
pin_mut!(history_stream); // needed for iteration
println!("looping through stream");
while let Some(res) = history_stream.next().await {
match res {
Ok(value) => {
println!("value: {:?}", value);
}
Err(err) => {
println!("err: {:?}", err);
}
}
}
println!("reached end of stream");
// create a history stream and convert it into a Vec<SsbMessageValue> using try_collect
// (if there is any error in the results, it will be raised)
let history_stream = sbot_client
.create_history_stream(author.to_string())
.await?;
let results: Vec<SsbMessageValue> = history_stream.try_collect().await?;
for x in results {
println!("x: {:?}", x);
}
// example to create a history stream and use a map to convert stream of SsbMessageValue
// into a stream of tuples of (String, SsbMessageContentType)
let history_stream = sbot_client
.create_history_stream(author.to_string())
.await?;
let type_stream = history_stream.map(|msg| match msg {
Ok(val) => {
let message_type = val.get_message_type()?;
let tuple: (String, SsbMessageContentType) = (val.signature, message_type);
Ok(tuple)
}
Err(err) => Err(err),
});
pin_mut!(type_stream); // needed for iteration
println!("looping through type stream");
while let Some(res) = type_stream.next().await {
match res {
Ok(value) => {
println!("value: {:?}", value);
}
Err(err) => {
println!("err: {:?}", err);
}
}
}
println!("reached end of type stream");
// return Ok
Ok(())
}
#[async_std::main]
async fn main() {
if let Err(e) = run().await {
eprintln!("Application error: {}", e);
process::exit(1);
}
}