class TickingAway::Bot
Constants
- DEFAULT_TIME_API
- EXCUSES
- TIMEAT_CMD
- TIMEPOPULARITY_CMD
Attributes
Public Class Methods
Allow the caller to pass in the storage method via primitive DI. Other storage methods must implement increment_stat(<tz_info>) and get_stat(<tz_info or prefix>)
# File lib/ticking_away/bot.rb, line 17 def initialize(storage: nil, time_api: nil) @storage = storage || TickingAway::JSONFileStorage.new @time_api = ENV['TIME_API'] || time_api || DEFAULT_TIME_API end
Public Instance Methods
Send a string to the Bot
in the format of <user_name>: <message> or just <message> Only !timeat <tz_info> and !timepopularity <tz_info or prefix> commands will return a string response
# File lib/ticking_away/bot.rb, line 26 def chat(msg) message = strip_username(msg) case message.partition(' ')[0] when TIMEAT_CMD.strip time_check(message) when TIMEPOPULARITY_CMD.strip stat_check(message) end end
Return the statistic for the provided tz_info or prefix
# File lib/ticking_away/bot.rb, line 48 def stat_check(msg) storage.get_stat(parse_message(msg, TIMEPOPULARITY_CMD.length)) end
Check time for the timezone provided against the provided time api.
# File lib/ticking_away/bot.rb, line 39 def time_check(msg) tz_info = parse_message(msg, TIMEAT_CMD.length) puts "Event: Checking Time for timezone: #{tz_info}" time_message(tz_info) end
Private Instance Methods
Parse the message for the string after the command. Requires the command length (including the ! and space) to know where to start the substring
# File lib/ticking_away/bot.rb, line 63 def parse_message(msg, cmd_length) msg[cmd_length..msg.length] end
# File lib/ticking_away/bot.rb, line 54 def strip_username(msg) return msg unless msg.include?(':') msg.partition(':')[2].strip end
Generate the time message, returning “unknown timezone” for any unrecognized time zones and logging any uncaught errors before returning an excuse at random. Stats will only be incremented if the api call was successful
# File lib/ticking_away/bot.rb, line 71 def time_message(tz_info) time = TickingAway::WorldTime.time_at(time_api, tz_info) storage.increment_stat(tz_info) time.strftime('%e %b %Y %H:%M') rescue TickingAway::Errors::UnrecognizedTimeZone => e puts e.message 'unknown timezone' rescue TickingAway::Errors::TimeTravelIsHard => e puts e.message EXCUSES.sample end