From ad0dc32a64d9382615ad844aa8fc563b6d95155b 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 | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/lib/telegram/bot/client.rb b/lib/telegram/bot/client.rb index 68f77ec..01286b6 100644 --- a/lib/telegram/bot/client.rb +++ b/lib/telegram/bot/client.rb @@ -6,6 +6,8 @@ class Client attr_reader :api, :options attr_accessor :logger + DEFAULT_THREADS_NUM = 10 + def self.run(*args, &block) new(*args).run(&block) end @@ -17,25 +19,34 @@ def initialize(token, hash = {}) 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(options).each do |update| + threads << block.call(handle_update(update)) + end end - rescue Faraday::TimeoutError, Faraday::ConnectionFailed - retry if @running end def handle_update(update) @@ -51,6 +62,7 @@ def handle_update(update) def default_options { offset: 0, + threads: DEFAULT_THREADS_NUM, timeout: 20, logger: NullLogger.new, url: 'https://api.telegram.org',