Skip to content

Commit

Permalink
feat(telegram): add code block escaping for Telegram messages
Browse files Browse the repository at this point in the history
  • Loading branch information
alextes committed Feb 20, 2025
1 parent 14480b9 commit 9c7d770
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
18 changes: 16 additions & 2 deletions src/phoenix/alerts/telegram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ pub static BUILDER_ID_CHANNEL_ID_MAP: LazyLock<HashMap<String, String>> = LazyLo
.collect()
});

// Used to escape characters in telegram messages.
// https://core.telegram.org/bots/api#markdownv2-style
/// Used to escape characters in telegram messages.
/// https://core.telegram.org/bots/api#markdownv2-style
pub fn escape_str(input: &str) -> String {
let mut output = String::new();
for c in input.chars() {
Expand All @@ -33,6 +33,20 @@ pub fn escape_str(input: &str) -> String {
output
}

/// Inside a ``` code block, we need to escape only backticks and backslashes.
/// https://core.telegram.org/bots/api#markdownv2-style
pub fn escape_code_block(input: &str) -> String {
let mut output: String = String::new();
for c in input.chars() {
match c {
'`' => output.push_str("\\`"),
'\\' => output.push_str("\\\\"),
_ => output.push(c),
}
}
output
}

/// Formats a message to be compatible with the Telegram bot API.
/// Respect escaping as described in: https://core.telegram.org/bots/api#markdownv2-style
/// Respect character limit of 4096.
Expand Down
4 changes: 3 additions & 1 deletion src/phoenix/demotion_monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,14 @@ fn filter_demotions(demotions: Vec<BuilderDemotion>) -> Vec<BuilderDemotion> {
.collect_vec()
}

// this fn sometimes produces a message telegram doesn't like.
// our current attempt to fix this is to escape the code block.
fn format_demotion_message(demotion: &BuilderDemotion) -> String {
let explorer_url = APP_CONFIG.network.to_beacon_explorer_url();
let builder_id = demotion.builder_id.as_deref().unwrap_or("unknown");
let escaped_builder_id = telegram::escape_str(builder_id);
let builder_pubkey = &demotion.builder_pubkey;
let error = telegram::escape_str(&demotion.sim_error);
let error = telegram::escape_code_block(&demotion.sim_error);
let slot = &demotion.slot;
let geo = &demotion.geo;
let block_hash = &demotion.block_hash;
Expand Down

0 comments on commit 9c7d770

Please sign in to comment.