Class: MTProto::BotAuthorizer

Inherits:
Object
  • Object
show all
Defined in:
lib/mtproto/bot_authorizer.rb

Overview

Logs a bot in with auth.importBotAuthorization, following a USER_MIGRATE_X redirect. A bot token is bound to a home DC; importing it from any other DC answers RPC 303 USER_MIGRATE_X naming that DC. On that reply we drop the seed connection and re-import against a fresh connection to the named DC. The DC switch lives here rather than in the DC-bound Client (mirroring FileDownloader); addresses come from MTProto::DC, never hardcoded per bot.

Runs inside an Async reactor: the default connect starts a receiver.

Instance Method Summary collapse

Constructor Details

#initialize(api_id:, api_hash:, public_key:, test_mode: false, timeout: 10, connect: nil) ⇒ BotAuthorizer

Returns a new instance of BotAuthorizer.



16
17
18
19
20
21
22
23
# File 'lib/mtproto/bot_authorizer.rb', line 16

def initialize(api_id:, api_hash:, public_key:, test_mode: false, timeout: 10, connect: nil)
  @api_id = api_id
  @api_hash = api_hash
  @public_key = public_key
  @test_mode = test_mode
  @timeout = timeout
  @connect = connect || method(:default_connect)
end

Instance Method Details

#authorize(bot_auth_token, seed_dc: 2) ⇒ Object

Returns a connected, key-exchanged, receiving, initialised, authorized Client on the bot's home DC. seed_dc is only where the search starts; the real DC is discovered from the migrate redirect.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/mtproto/bot_authorizer.rb', line 28

def authorize(bot_auth_token, seed_dc: 2)
  dc = seed_dc
  visited = []
  loop do
    visited << dc
    client = @connect.call(dc)
    begin
      client.api.import_bot_authorization(bot_auth_token)
      return client
    rescue RpcError => e
      raise if e.migrate_dc.nil?

      client.disconnect!
      dc = e.migrate_dc
      raise Error, "bot authorization keeps migrating (revisited DC #{dc})" if visited.include?(dc)
    end
  end
end