Class: TeBot::Wire

Inherits:
Object
  • Object
show all
Defined in:
lib/te_bot/wire.rb

Constant Summary collapse

CONN =
Faraday.new(
  url: "https://api.telegram.org/",
  headers: {"Content-Type" => "application/json"}
)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token) ⇒ Wire

Returns a new instance of Wire.



24
25
26
# File 'lib/te_bot/wire.rb', line 24

def initialize(access_token)
  @access_token = access_token
end

Class Method Details

.sender(message_format, handler = nil, &block) ⇒ Object



9
10
11
12
# File 'lib/te_bot/wire.rb', line 9

def sender(message_format, handler = nil, &block)
  @senders ||= {}
  @senders[message_format] = (block || handler)
end

.sendersObject



14
15
16
# File 'lib/te_bot/wire.rb', line 14

def senders
  @senders || {}
end

Instance Method Details

#make_request(path, params: nil, headers: nil, body: nil) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/te_bot/wire.rb', line 28

def make_request(path, params: nil, headers: nil, body: nil)
  CONN.post(url(path)) do |req|
    req.params.merge!(params) if params
    req.headers.merge!(headers) if headers
    req.body = body if body
  end
end

#send_message(chat_id, **payload) ⇒ Object

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
48
49
# File 'lib/te_bot/wire.rb', line 40

def send_message(chat_id, **payload)
  message_format, message = payload.first
  handler = self.class.senders[message_format]

  raise ArgumentError, "Message type invalid. sender :#{message_format} not defined" if handler.nil?

  return instance_exec(chat_id, message, &handler) if handler.respond_to?(:call)

  public_send(handler, chat_id, message)
end

#url(path) ⇒ Object



36
37
38
# File 'lib/te_bot/wire.rb', line 36

def url(path)
  "/bot#{@access_token}/#{path}"
end