Class: Telegrama::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/telegrama/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Client

Returns a new instance of Client.



8
9
10
11
12
# File 'lib/telegrama/client.rb', line 8

def initialize(config = {})
  @config = config
  @fallback_attempts = 0
  @max_fallback_attempts = 2
end

Instance Method Details

#send_message(message, options = {}) ⇒ Object

Send a message with built-in error handling and fallbacks



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
# File 'lib/telegrama/client.rb', line 15

def send_message(message, options = {})
  options = normalize_option_keys(options)

  # Allow chat ID override; fallback to config default
  chat_id = options.delete(:chat_id) || Telegrama.configuration.chat_id

  # Allow topic/thread override; fallback to config default.
  # Explicit nil means "send to the chat normally", even when a default topic is configured.
  message_thread_id = if options.key?(:message_thread_id)
                        options.delete(:message_thread_id)
                      else
                        Telegrama.configuration.message_thread_id
                      end
  validate_message_thread_id!(message_thread_id)

  # Get client options from config
  client_opts = Telegrama.configuration.client_options || {}
  client_opts = client_opts.merge(@config)

  # Default to MarkdownV2 parse mode unless explicitly overridden
  # Use key? to allow explicit nil override (for plain text without formatting)
  parse_mode = options.key?(:parse_mode) ? options[:parse_mode] : Telegrama.configuration.default_parse_mode

  # Allow runtime formatting options, merging with configured defaults.
  # Escape behavior must match the outgoing Telegram parse mode; otherwise
  # plain-text sends can display MarkdownV2 escape characters literally.
  formatting_opts = normalize_option_keys(options.delete(:formatting) || {})
  formatting_opts = formatting_options_for_parse_mode(parse_mode, formatting_opts)

  # Format the message text with our formatter
  formatted_message = Formatter.format(message, formatting_opts)

  # Reset fallback attempts counter
  @fallback_attempts = 0

  # Use a loop to implement fallback strategy
  begin
    # Prepare the request payload
    payload = {
      chat_id: chat_id,
      text: formatted_message,
      disable_web_page_preview: options.fetch(:disable_web_page_preview,
                                             Telegrama.configuration.disable_web_page_preview)
    }
    payload[:parse_mode] = parse_mode unless parse_mode.nil?
    payload[:message_thread_id] = message_thread_id unless message_thread_id.nil?

    # Additional options such as reply_markup can be added here
    payload.merge!(options.select { |k, _| [:reply_markup, :reply_to_message_id].include?(k) })

    # Make the API request
    response = perform_request(payload, client_opts)

    # If successful, reset fallback counter and return the response
    @fallback_attempts = 0
    return response

  rescue Error => e
    # Log the error for debugging
    begin
      Telegrama.log_error("Error sending message: #{e.message}")
    rescue => _log_error
      # Ignore logging errors in tests
    end

    # Track this attempt
    @fallback_attempts += 1

    # Try fallback strategies if we haven't exceeded the limit
    if @fallback_attempts < 3
      # If we were using MarkdownV2, try HTML as fallback
      if parse_mode == 'MarkdownV2' && @fallback_attempts == 1
        begin
          Telegrama.log_info("Falling back to HTML format")
        rescue => _log_error
          # Ignore logging errors
        end

        # Switch to HTML formatting
        parse_mode = 'HTML'
        formatting_opts = { escape_html: true, escape_markdown: false }
        formatted_message = Formatter.format(message, formatting_opts)

        # Retry the request
        retry

      # If HTML fails too, try plain text
      elsif parse_mode == 'HTML' && @fallback_attempts == 2
        begin
          Telegrama.log_info("Falling back to plain text format")
        rescue => _log_error
          # Ignore logging errors
        end

        # Switch to plain text (no special formatting)
        parse_mode = nil
        formatting_opts = { escape_markdown: false, escape_html: false }
        formatted_message = Formatter.format(message, formatting_opts)

        # Retry the request
        retry
      end
    end

    # If we've exhausted fallbacks or this is a different error, re-raise
    raise
  end
end