1mod api;
2mod types;
3mod util;
4
5pub use api::*;
6pub use types::*;
7
8pub use tg_flows_macros::*;
9
10use http_req::request;
11use lazy_static::lazy_static;
12
13use flowsnet_platform_sdk::write_error_log;
14
15lazy_static! {
16 static ref TG_API_PREFIX: String = String::from(
17 std::option_env!("TG_API_PREFIX").unwrap_or("https://telegram.flows.network/api")
18 );
19}
20
21extern "C" {
22 fn get_flows_user(p: *mut u8) -> i32;
24
25 fn get_flow_id(p: *mut u8) -> i32;
27
28 fn set_output(p: *const u8, len: i32);
29 fn set_error_code(code: i16);
30}
31
32unsafe fn _get_flows_user() -> String {
33 let mut flows_user = Vec::<u8>::with_capacity(100);
34 let c = get_flows_user(flows_user.as_mut_ptr());
35 flows_user.set_len(c as usize);
36 String::from_utf8(flows_user).unwrap()
37}
38
39unsafe fn _get_flow_id() -> String {
40 let mut flow_id = Vec::<u8>::with_capacity(100);
41 let c = get_flow_id(flow_id.as_mut_ptr());
42 if c == 0 {
43 panic!("Failed to get flow id");
44 }
45 flow_id.set_len(c as usize);
46 String::from_utf8(flow_id).unwrap()
47}
48
49pub async fn listen_to_update<T>(token: T)
55where
56 T: ToString,
57{
58 unsafe {
59 let flows_user = _get_flows_user();
60 let flow_id = _get_flow_id();
61
62 let mut writer = Vec::new();
63 let res = request::get(
64 format!(
65 "{}/{flows_user}/{flow_id}/listen?token={}&handler_fn={}",
66 TG_API_PREFIX.as_str(),
67 urlencoding::encode(&token.to_string()),
68 "__telegram__on_updated"
69 ),
70 &mut writer,
71 )
72 .unwrap();
73
74 match res.status_code().is_success() {
75 true => {
76 let output = format!(
77 "[{}] Listening for all messages to your bot.",
78 std::env!("CARGO_CRATE_NAME")
79 );
80 set_output(output.as_ptr(), output.len() as i32);
81 }
82 false => {
83 write_error_log!(String::from_utf8_lossy(&writer));
84 set_error_code(format!("{}", res.status_code()).parse::<i16>().unwrap_or(0));
85 }
86 }
87 }
88}