tg-cli 0.2.1

A "unix-like" utility for sending yourself Telegram messages from the terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use std::{
    fs,
    io::{self},
    path::PathBuf,
};

use teloxide::{
    Bot, RequestError,
    payloads::{EditMessageTextSetters, SendDocumentSetters, SendMessageSetters},
    prelude::Requester,
    types::{ChatId, InputFile, MessageId, ParseMode as TeloxideParseMode},
};

use crate::config::{ConfigFile, config_path};

mod config;
mod secret_store;

#[derive(Debug)]
pub enum SendMessageError {
    MissingToken(Option<String>),
    MissingChatId(Option<String>),
    RuntimeInit(io::Error),
    Request(RequestError),
}

impl std::fmt::Display for SendMessageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SendMessageError::MissingToken(None) => {
                write!(f, "No token configured. Run `tg setup` first.")
            }
            SendMessageError::MissingToken(Some(profile)) => {
                write!(
                    f,
                    "No token configured for profile '{profile}'. Run `tg --profile {profile} setup` first."
                )
            }
            SendMessageError::MissingChatId(None) => {
                write!(f, "No chat ID configured. Run `tg setup` first.")
            }
            SendMessageError::MissingChatId(Some(profile)) => {
                write!(
                    f,
                    "No chat ID configured for profile '{profile}'. Run `tg --profile {profile} setup` first."
                )
            }
            SendMessageError::RuntimeInit(err) => {
                write!(f, "Failed to initialize async runtime: {err}")
            }
            SendMessageError::Request(err) => write!(f, "Failed to send message: {err}"),
        }
    }
}

impl std::error::Error for SendMessageError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SendMessageError::RuntimeInit(err) => Some(err),
            SendMessageError::Request(err) => Some(err),
            SendMessageError::MissingToken(_) | SendMessageError::MissingChatId(_) => None,
        }
    }
}

pub type TgResult<T> = Result<T, SendMessageError>;

pub struct SetupStatus {
    pub has_token: bool,
    pub chat_id: Option<i64>,
}

pub struct BotConfigStatus {
    pub path: PathBuf,
    pub config_file_present: bool,
    pub chat_id: Option<i64>,
    pub token: TokenStatus,
    pub secret_service: SecretServiceStatus,
}

pub enum TokenStatus {
    SecretService,
    PlaintextFallback,
    NotConfigured,
}

pub enum SecretServiceStatus {
    Available,
    Unavailable,
    Error(String),
}

pub struct TgSession {
    bot: Bot,
    chat_id: ChatId,
}

#[derive(Debug, Clone, Copy)]
pub enum ParseMode {
    Markdown,
    Html,
}

impl From<ParseMode> for TeloxideParseMode {
    fn from(mode: ParseMode) -> Self {
        match mode {
            ParseMode::Markdown => TeloxideParseMode::MarkdownV2,
            ParseMode::Html => TeloxideParseMode::Html,
        }
    }
}

impl TgSession {
    pub async fn from_config(profile: Option<&str>) -> TgResult<Self> {
        let file = ConfigFile::load();
        let profile_data = file.get_profile(profile);
        let token = profile_data
            .resolved_token_for(profile)
            .await
            .ok_or_else(|| SendMessageError::MissingToken(profile.map(|s| s.to_string())))?;
        let chat_id = profile_data
            .chat_id
            .ok_or_else(|| SendMessageError::MissingChatId(profile.map(|s| s.to_string())))?;

        Ok(Self {
            bot: Bot::new(token),
            chat_id: ChatId(chat_id),
        })
    }

    fn sanitize_text(text: String) -> String {
        text.replace("\r\n", "\n")
            .replace('_', "\\_")
            .replace('*', "\\*")
            .replace('[', "\\[")
            .replace(']', "\\]")
            .replace('(', "\\(")
            .replace(')', "\\)")
            .replace('~', "\\~")
            .replace('`', "\\`")
            .replace('>', "\\>")
            .replace('#', "\\#")
            .replace('+', "\\+")
            .replace('-', "\\-")
            .replace('=', "\\=")
            .replace('|', "\\|")
            .replace('{', "\\{")
            .replace('}', "\\}")
            .replace('.', "\\.")
            .replace('!', "\\!")
    }

    pub async fn send_message(
        &self,
        text: String,
        parse_mode: ParseMode,
        silent: bool,
    ) -> TgResult<i32> {
        let mut req = self
            .bot
            .send_message(self.chat_id, Self::sanitize_text(text));
        req = req.parse_mode(parse_mode.into());

        if silent {
            req = req.disable_notification(true);
        }

        let message = req.await.map_err(SendMessageError::Request)?;
        Ok(message.id.0)
    }

    pub async fn send_document(&self, path: &std::path::Path, silent: bool) -> TgResult<()> {
        let input_file = InputFile::file(path);
        let mut req = self.bot.send_document(self.chat_id, input_file);

        if silent {
            req = req.disable_notification(true);
        }

        req.await.map_err(SendMessageError::Request)?;
        Ok(())
    }

    pub async fn edit_message(
        &self,
        message_id: i32,
        text: String,
        parse_mode: ParseMode,
    ) -> TgResult<()> {
        let mut req = self.bot.edit_message_text(
            self.chat_id,
            MessageId(message_id),
            Self::sanitize_text(text),
        );
        req = req.parse_mode(parse_mode.into());
        req.await.map_err(SendMessageError::Request)?;
        Ok(())
    }
}

pub async fn load_setup_status(profile: Option<&str>) -> SetupStatus {
    let file = ConfigFile::load();
    let profile_data = file.get_profile(profile);
    SetupStatus {
        has_token: profile_data.resolved_token_for(profile).await.is_some(),
        chat_id: profile_data.chat_id,
    }
}

pub async fn bot_from_config_token(profile: Option<&str>) -> TgResult<Bot> {
    let file = ConfigFile::load();
    let profile_data = file.get_profile(profile);
    let token = profile_data
        .resolved_token_for(profile)
        .await
        .ok_or_else(|| SendMessageError::MissingToken(profile.map(|s| s.to_string())))?;
    Ok(Bot::new(token))
}

pub async fn listen_config(profile: Option<&str>) -> TgResult<(Bot, ChatId)> {
    let bot = bot_from_config_token(profile).await?;
    let file = ConfigFile::load();
    let chat_id = file
        .get_profile(profile)
        .chat_id
        .ok_or_else(|| SendMessageError::MissingChatId(profile.map(|s| s.to_string())))?;
    Ok((bot, ChatId(chat_id)))
}

pub async fn inspect_bot_config(profile: Option<&str>) -> BotConfigStatus {
    let path = config_path();
    let file = ConfigFile::load();
    let profile_data = file.get_profile(profile);

    let (secret_service, token) =
        match secret_store::load_token_for(profile.map(|s| s.to_string())).await {
            Ok(Some(_)) => (SecretServiceStatus::Available, TokenStatus::SecretService),
            Ok(None) => (
                SecretServiceStatus::Available,
                if profile_data.token.is_some() {
                    TokenStatus::PlaintextFallback
                } else {
                    TokenStatus::NotConfigured
                },
            ),
            Err(err) if secret_store::is_unavailable(&err) => (
                SecretServiceStatus::Unavailable,
                if profile_data.token.is_some() {
                    TokenStatus::PlaintextFallback
                } else {
                    TokenStatus::NotConfigured
                },
            ),
            Err(err) => (
                SecretServiceStatus::Error(err.to_string()),
                if profile_data.token.is_some() {
                    TokenStatus::PlaintextFallback
                } else {
                    TokenStatus::NotConfigured
                },
            ),
        };

    BotConfigStatus {
        config_file_present: path.exists(),
        path,
        chat_id: profile_data.chat_id,
        token,
        secret_service,
    }
}

pub async fn save_bot_config(token: &str, chat_id: i64, profile: Option<&str>) {
    let mut file = ConfigFile::load();
    let mut profile_data = file.get_profile(profile);
    let _ = profile_data.persist_token_for(token, profile).await;
    profile_data.chat_id = Some(chat_id);
    file.set_profile(profile, profile_data);
    file.save();
}

pub fn save_chat_id(chat_id: i64, profile: Option<&str>) {
    let mut file = ConfigFile::load();
    let mut profile_data = file.get_profile(profile);
    profile_data.chat_id = Some(chat_id);
    file.set_profile(profile, profile_data);
    file.save();
}

pub async fn delete_bot_config(profile: Option<&str>) -> bool {
    let path = config_path();
    let mut file = ConfigFile::load();
    let had_data = file.get_profile(profile).chat_id.is_some();
    file.delete_profile(profile);

    if file.is_empty() {
        if path.exists() {
            fs::remove_file(&path).expect("failed to delete config");
        }
    } else {
        file.save();
    }

    let mut removed_any = had_data;

    match secret_store::delete_token_for(profile.map(|s| s.to_string())).await {
        Ok(()) => {
            removed_any = true;
        }
        Err(err) if secret_store::is_unavailable(&err) => {
            eprintln!(
                "Warning: Secret Service API unavailable; could not delete keyring token ({err})."
            );
        }
        Err(err) => {
            eprintln!("Warning: failed to delete keyring token ({err}).");
        }
    }

    removed_any
}

pub fn list_profile_names() -> Vec<String> {
    let file = ConfigFile::load();
    let mut names: Vec<String> = file.profiles.keys().cloned().collect();
    names.sort();
    names
}

pub async fn send_tg_message(
    text: String,
    parse_mode: ParseMode,
    silent: bool,
    profile: Option<&str>,
) -> TgResult<()> {
    let session = TgSession::from_config(profile).await?;
    session.send_message(text, parse_mode, silent).await?;
    Ok(())
}

pub fn send_tg_message_blocking(
    text: String,
    parse_mode: ParseMode,
    silent: bool,
    profile: Option<&str>,
) -> TgResult<()> {
    let profile_owned = profile.map(|s| s.to_string());
    if tokio::runtime::Handle::try_current().is_ok() {
        let worker = std::thread::spawn(move || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(SendMessageError::RuntimeInit)?;
            rt.block_on(send_tg_message(
                text,
                parse_mode,
                silent,
                profile_owned.as_deref(),
            ))
        });

        return match worker.join() {
            Ok(result) => result,
            Err(_) => Err(SendMessageError::RuntimeInit(io::Error::other(
                "failed to join Telegram sender thread",
            ))),
        };
    }

    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(SendMessageError::RuntimeInit)?;
    rt.block_on(send_tg_message(
        text,
        parse_mode,
        silent,
        profile_owned.as_deref(),
    ))
}

#[cfg(feature = "non-blocking")]
#[macro_export]
macro_rules! telegram {
    () => {{
        $crate::telegram!("")
    }};
    ($($arg:tt)*) => {{
        let msg = format!($($arg)*);
        let profile = std::env::var("TG_PROFILE").ok();
        tokio::spawn(async move {
            if let Err(err) = $crate::send_tg_message(
                msg,
                $crate::ParseMode::Markdown,
                false,
                profile.as_deref(),
            )
            .await
            {
                eprintln!("{err}");
            }
        });
    }};
}

#[cfg(not(feature = "non-blocking"))]
#[macro_export]
macro_rules! telegram {
    () => {{
        $crate::telegram!("")
    }};
    ($($arg:tt)*) => {{
        let profile = std::env::var("TG_PROFILE").ok();
        if let Err(err) = $crate::send_tg_message_blocking(
            format!($($arg)*),
            $crate::ParseMode::Markdown,
            false,
            profile.as_deref(),
        ) {
            eprintln!("{err}");
        }
    }};
}