Class: ChatSDK::Telegram::FormatConverter

Inherits:
Format::Converter
  • Object
show all
Defined in:
lib/chat_sdk/telegram/format_converter.rb

Constant Summary collapse

SPECIAL_CHARS =
%w[_ * [ ] ( ) ~ \\ ` > # + - = | { } . !].freeze
ESCAPE_RE =
Regexp.union(SPECIAL_CHARS).freeze

Instance Method Summary collapse

Instance Method Details

#from_markdown(markdown) ⇒ Object

Standard Markdown → Telegram MarkdownV2



29
30
31
32
33
34
35
# File 'lib/chat_sdk/telegram/format_converter.rb', line 29

def from_markdown(markdown)
  text = markdown.to_s
  return "" if text.empty?

  parts = split_code_segments(text)
  parts.map.with_index { |part, i| i.odd? ? part : escape_special_chars(part) }.join
end

#to_markdown(platform_text) ⇒ Object

Telegram MarkdownV2 → standard Markdown



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/chat_sdk/telegram/format_converter.rb', line 10

def to_markdown(platform_text)
  text = platform_text.to_s
  return "" if text.empty?

  # Convert Telegram user links: [text](tg://user?id=123) → @123
  text = text.gsub(/\[([^\]]*)\]\(tg:\/\/user\?id=(\d+)\)/, '@\2')

  # Strip underline markers: __text__ → text
  # Use a loop to handle nested cases
  text = text.gsub(/(?<!_)__(?!_)(.+?)(?<!_)__(?!_)/m, '\1')

  # Strip spoiler markers: ||text|| → text
  text = text.gsub(/\|\|(.+?)\|\|/m, '\1')

  # Unescape all backslash-escaped characters
  text.gsub(/\\(.)/, '\1')
end