Skip to content

Commit

Permalink
Use threads (up to 10 by default)
Browse files Browse the repository at this point in the history
  • Loading branch information
maliqq committed Nov 10, 2024
1 parent 64a092a commit 2a64e96
Showing 1 changed file with 34 additions and 12 deletions.
46 changes: 34 additions & 12 deletions lib/telegram/bot/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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',
Expand Down

0 comments on commit 2a64e96

Please sign in to comment.