Class: Kodo::Channels::Telegram
- Defined in:
- lib/kodo/channels/telegram.rb
Constant Summary collapse
- API_BASE =
"https://api.telegram.org"
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
- #connect! ⇒ Object
- #disconnect! ⇒ Object
-
#initialize(bot_token:) ⇒ Telegram
constructor
A new instance of Telegram.
-
#poll ⇒ Object
Poll for new messages using long polling with a short timeout Returns ArrayKodo::Message.
- #send_message(message) ⇒ Object
Methods inherited from Base
Constructor Details
#initialize(bot_token:) ⇒ Telegram
Returns a new instance of Telegram.
12 13 14 15 16 17 |
# File 'lib/kodo/channels/telegram.rb', line 12 def initialize(bot_token:) @bot_token = bot_token @last_update_id = 0 @allowed_chat_ids = [] # empty = allow all (for now) super(channel_id: "telegram") end |
Instance Method Details
#connect! ⇒ Object
19 20 21 22 23 24 25 26 27 28 |
# File 'lib/kodo/channels/telegram.rb', line 19 def connect! # Verify the bot token works me = api_request("getMe") bot_name = me.dig("result", "username") Kodo.logger.info("Telegram connected as @#{bot_name}") @running = true self rescue StandardError => e raise Error, "Failed to connect Telegram: #{e.}" end |
#disconnect! ⇒ Object
30 31 32 33 |
# File 'lib/kodo/channels/telegram.rb', line 30 def disconnect! @running = false Kodo.logger.info("Telegram disconnected") end |
#poll ⇒ Object
Poll for new messages using long polling with a short timeout Returns ArrayKodo::Message
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/kodo/channels/telegram.rb', line 37 def poll return [] unless running? params = { offset: @last_update_id + 1, timeout: 1, # short poll — we're inside a heartbeat loop allowed_updates: ["message"] } response = api_request("getUpdates", params) updates = response.dig("result") || [] = updates.filter_map do |update| @last_update_id = update["update_id"] parse_update(update) end rescue StandardError => e Kodo.logger.warn("Telegram poll error: #{e.}") [] end |
#send_message(message) ⇒ Object
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 |
# File 'lib/kodo/channels/telegram.rb', line 60 def () chat_id = .[:chat_id] || .["chat_id"] return unless chat_id params = { chat_id: chat_id, text: .content, parse_mode: "Markdown" } # If replying to a specific message if (reply_to = .[:reply_to_message_id] || .["reply_to_message_id"]) params[:reply_to_message_id] = reply_to end api_request("sendMessage", params) Kodo.logger.debug("Sent Telegram message to chat #{chat_id}") rescue StandardError => e Kodo.logger.error("Telegram send error: #{e.}") # Retry without markdown if parse failed if e..include?("parse") params.delete(:parse_mode) api_request("sendMessage", params) rescue nil end end |