Class: Ruboty::Handlers::Mtgcard

Inherits:
Base
  • Object
show all
Defined in:
lib/ruboty/handlers/mtgcard.rb

Constant Summary collapse

API_URL =
'https://api.magicthegathering.io/v1/cards?'
DEFAULT_MTGCARD_LANGUAGE =
'english'
DEFAULT_MTGCARD_MESSAGE_WHEN_NOT_FOUND =
'No cards found.'
LANGUAGE =
ENV['MTGCARD_LANGUAGE'] || DEFAULT_MTGCARD_LANGUAGE
MESSAGE_WHEN_NOT_FOUND =
ENV['MTGCARD_MESSAGE_WHEN_NOT_FOUND'] || DEFAULT_MTGCARD_MESSAGE_WHEN_NOT_FOUND

Instance Method Summary collapse

Instance Method Details

#mtgcard(message) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ruboty/handlers/mtgcard.rb', line 24

def mtgcard(message)
  image_url = nil

  begin
    res = open "#{api_url}&name=#{URI.escape(message[:keyword])}"
  rescue => e
    return message.reply e
  end

  cards = JSON.parse(res.read)['cards']
  return message.reply MESSAGE_WHEN_NOT_FOUND if cards.length == 0

  if LANGUAGE == 'english'
    while image_url.nil? || image_url.length == 0
      image_url = cards.sample['imageUrl']
    end
  else
    while image_url.nil? || image_url.length == 0
      card = cards.sample['foreignNames'].find { |foreig_name| foreig_name['language'] == LANGUAGE.capitalize }
      image_url = card['imageUrl']
    end
  end

  message.reply image_url
end