From 2a64e966c639660190a68bee2a6bb41c1f158b7a Mon Sep 17 00:00:00 2001 From: Malik Bakti Date: Sun, 10 Nov 2024 20:37:43 +0600 Subject: [PATCH] Use threads (up to 10 by default) --- lib/telegram/bot/client.rb | 46 ++++++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/lib/telegram/bot/client.rb b/lib/telegram/bot/client.rb index 68f77ec..0e5ef18 100644 --- a/lib/telegram/bot/client.rb +++ b/lib/telegram/bot/client.rb @@ -6,40 +6,54 @@ class Client attr_reader :api, :options attr_accessor :logger + DEFAULT_THREADS_NUM = 10 + def self.run(*args, &block) new(*args).run(&block) end def initialize(token, hash = {}) @options = default_options.merge(hash) - @api = Api.new(token, url: options.delete(:url), environment: options.delete(:environment)) - @logger = options.delete(:logger) + @api = Api.new(token, url: options[:url], environment: options[:environment]) + @logger = options[:logger] + @offset = 0 + @limit = options[:threads_num] + @timeout = options[:timeout] end def run + logger.info('Starting bot') + @running = true yield self end def listen(&block) - logger.info('Starting bot') - @running = true - fetch_updates(&block) while @running + loop do + break unless @running + + begin + threads = fetch_updates(&block) + threads.map(&:join) + rescue Faraday::TimeoutError, Faraday::ConnectionFailed + # :no-op: + end + end end def stop @running = false end - def fetch_updates - api.getUpdates(options).each do |update| - yield handle_update(update) + def fetch_updates(&block) + [].tap do |threads| + api.getUpdates(params).each do |update| + threads << Thread.new { block.call(handle_update(update)) } + end end - rescue Faraday::TimeoutError, Faraday::ConnectionFailed - retry if @running end def handle_update(update) - @options[:offset] = update.update_id.next + @offset = update.update_id.next message = update.current_message log_incoming_message(message) @@ -48,9 +62,17 @@ def handle_update(update) private + def params + { + limit: @limit, + offset: @offset, + timeout: @timeout + } + end + def default_options { - offset: 0, + threads_num: DEFAULT_THREADS_NUM, timeout: 20, logger: NullLogger.new, url: 'https://api.telegram.org',