|
| 1 | +use crate::posts::publish_media_container; |
| 2 | +use crate::retrieve_media::SimpleMediaObject; |
| 3 | +use std::time::Duration; |
| 4 | + |
| 5 | +pub async fn create_reply( |
| 6 | + reply_to_id: &str, |
| 7 | + text: Option<&str>, |
| 8 | + image_url: Option<&str>, |
| 9 | + video_url: Option<&str>, |
| 10 | + token: &str, |
| 11 | +) -> Result<SimpleMediaObject, reqwest::Error> { |
| 12 | + let mut url = format!( |
| 13 | + "https://graph.threads.net/v1.0/me/threads\ |
| 14 | + ?reply_to_id={reply_to_id}\ |
| 15 | + &access_token={token}" |
| 16 | + ); |
| 17 | + |
| 18 | + let mut publish_wait_time_ms = 300; |
| 19 | + let mut media_type = "TEXT"; |
| 20 | + if let Some(text) = text { |
| 21 | + url.push_str(format!("&text={text}").as_str()); |
| 22 | + } |
| 23 | + if let Some(image_url) = image_url { |
| 24 | + url.push_str(format!("&image_url={image_url}").as_str()); |
| 25 | + media_type = "IMAGE"; |
| 26 | + publish_wait_time_ms = 3000; |
| 27 | + } |
| 28 | + if let Some(video_url) = video_url { |
| 29 | + url.push_str(format!("&video_url={video_url}").as_str()); |
| 30 | + media_type = "VIDEO"; |
| 31 | + publish_wait_time_ms = 30000; |
| 32 | + } |
| 33 | + url.push_str(format!("&media_type={media_type}").as_str()); |
| 34 | + |
| 35 | + let media_container = reqwest::Client::new() |
| 36 | + .post(&url) |
| 37 | + .send() |
| 38 | + .await? |
| 39 | + .json::<SimpleMediaObject>() |
| 40 | + .await?; |
| 41 | + |
| 42 | + // ideally we proceed as long as we have `id` in the media_container, or poll until we have it |
| 43 | + // https://developers.facebook.com/docs/threads/troubleshooting#publishing-does-not-return-a-media-id |
| 44 | + // but for now it's alright to stick with some hardcoded wait time |
| 45 | + tokio::time::sleep(Duration::from_millis(publish_wait_time_ms)).await; |
| 46 | + |
| 47 | + let res = publish_media_container(&media_container.id, token).await?; |
| 48 | + |
| 49 | + Ok(res) |
| 50 | +} |
| 51 | + |
| 52 | +#[cfg(test)] |
| 53 | +mod tests { |
| 54 | + use super::*; |
| 55 | + use crate::utils::read_dot_env; |
| 56 | + use log::debug; |
| 57 | + use urlencoding::encode; |
| 58 | + |
| 59 | + #[tokio::test] |
| 60 | + async fn test_create_reply() { |
| 61 | + let should_log_verbose = true; |
| 62 | + let _ = env_logger::builder() |
| 63 | + .is_test(!should_log_verbose) |
| 64 | + .try_init(); |
| 65 | + |
| 66 | + let env = read_dot_env(); |
| 67 | + let token = env.get("ACCESS_TOKEN").unwrap(); |
| 68 | + |
| 69 | + let reply_to_id = "17961951074882947"; |
| 70 | + let text = encode("you see me rollin' 🥁"); |
| 71 | + let image_url = "https://i.imgur.com/Cj33AKk.png"; |
| 72 | + let res = create_reply(reply_to_id, Some(&*text), Some(image_url), None, &token).await; |
| 73 | + |
| 74 | + debug!("{:?}", res); |
| 75 | + assert_eq!(true, res.is_ok()); |
| 76 | + } |
| 77 | +} |
0 commit comments