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

def send_message(message, options = {})
  # Allow chat ID override; fallback to config default
  chat_id = options.delete(:chat_id) || Telegrama.configuration.chat_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
  parse_mode = options[:parse_mode] || Telegrama.configuration.default_parse_mode

  # Allow runtime formatting options, merging with configured defaults
  formatting_opts = options.delete(:formatting) || {}

  # Add parse mode specific options
  if parse_mode == 'MarkdownV2'
    formatting_opts[:escape_markdown] = true unless formatting_opts.key?(:escape_markdown)
  elsif parse_mode == 'HTML'
    formatting_opts[:escape_html] = true unless formatting_opts.key?(:escape_html)
  end

  # 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,
      parse_mode: parse_mode,
      disable_web_page_preview: options.fetch(:disable_web_page_preview,
                                             Telegrama.configuration.disable_web_page_preview)
    }

    # 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