From f75b1ddb4ac5dc0bf57c0eb94291c126bedb0485 Mon Sep 17 00:00:00 2001 From: evazion Date: Thu, 18 Mar 2021 21:44:28 -0500 Subject: [PATCH] discord: add /time command. --- app/logical/discord_slash_command.rb | 1 + .../discord_slash_command/time_command.rb | 57 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 app/logical/discord_slash_command/time_command.rb diff --git a/app/logical/discord_slash_command.rb b/app/logical/discord_slash_command.rb index de71f7df0..1d064b921 100644 --- a/app/logical/discord_slash_command.rb +++ b/app/logical/discord_slash_command.rb @@ -5,6 +5,7 @@ class DiscordSlashCommand count: DiscordSlashCommand::CountCommand, posts: DiscordSlashCommand::PostsCommand, random: DiscordSlashCommand::RandomCommand, + time: DiscordSlashCommand::TimeCommand, wiki: DiscordSlashCommand::WikiCommand, } diff --git a/app/logical/discord_slash_command/time_command.rb b/app/logical/discord_slash_command/time_command.rb new file mode 100644 index 000000000..e8089ef99 --- /dev/null +++ b/app/logical/discord_slash_command/time_command.rb @@ -0,0 +1,57 @@ +class DiscordSlashCommand + class TimeCommand < DiscordSlashCommand + def name + "time" + end + + def description + "Show the current time around the world" + end + + def options + [{ + name: "name", + description: "The name of the country to show", + required: false, + type: ApplicationCommandOptionType::String + }] + end + + def call + name = params[:name] + + if name.present? + msg = times_for_country(name) + msg = "Timezone not found: #{name}" if msg.blank? + else + msg = <<~EOS + `US (west): #{time("US/Pacific")}` + `US (east): #{time("US/Eastern")}` + `Europe: #{time("Europe/Berlin")}` + `Japan: #{time("Asia/Tokyo")}` + `Australia: #{time("Australia/Sydney")}` + EOS + end + + respond_with(msg) + end + + def times_for_country(country_name) + country = TZInfo::Country.all.find do |country| + country.name.downcase == country_name.downcase + end + + return nil if country.nil? + + zones = country.zones.group_by(&:abbr).transform_values(&:first).values + zones.map do |zone| + "`#{zone.friendly_identifier}: #{time(zone.identifier)}`" + end.join("\n") + end + + # format: Thu, Nov 02 2017 6:11 PM CDT + def time(zone, format: "%a, %b %d %Y %l:%M %p %Z") + Time.use_zone(zone) { Time.current.strftime(format) } + end + end +end