Skip to content

Instantly share code, notes, and snippets.

@Varun-garg
Last active December 27, 2021 07:26
Show Gist options
  • Save Varun-garg/effdc054d43a152cf47d227277e8893e to your computer and use it in GitHub Desktop.
Save Varun-garg/effdc054d43a152cf47d227277e8893e to your computer and use it in GitHub Desktop.
slack status updater
#!/usr/bin/ruby
require 'net/http'
require 'optparse'
require 'json'
require 'date'
API_TOKEN = ENV['SLACK_TOKEN']
OPTS = Hash[ ARGV.join(' ').scan(/--?([^=\s]+)(?: (\S+))?/) ] # regex to arrange args in hash
ARGS = ARGV - OPTS.keys.map{|k| "--#{k}"}
URL = 'https://slack.com/api/users.profile.set'
HEADERS = {
'Authorization'=> "Bearer #{API_TOKEN}",
'Content-Type' =>'application/json; charset=ISO-8859-1',
'Accept'=>'application/json'
}
SIGNED_OFF = {
profile: {
status_text: "Signed off, call if urgent.",
status_emoji: ":mobile_phone_off:",
status_expiration: DateTime.new( DateTime.now.year, DateTime.now.month, DateTime.now.day, 23, 59, 59, DateTime.now.zone).to_time.to_i
},
}
LUNCH = {
profile: {
status_text: "Lunch",
status_emoji: ":pizza:",
status_expiration: DateTime.new( DateTime.now.year, DateTime.now.month, DateTime.now.day, 15, 00, 00, DateTime.now.zone).to_time.to_i
},
}
uri = URI(URL)
STATUS_MAPS = {
signed_off: SIGNED_OFF,
lunch: LUNCH
}
unless ARGS[0]
STDERR.puts "Require additional status parameter from - [#{STATUS_MAPS.keys.join(', ')}]"
Kernel.exit(1)
end
status_to_update = STATUS_MAPS[ARGS[0].to_sym]
puts status_to_update
req = Net::HTTP::Post.new(uri, HEADERS)
req.body = status_to_update.to_json
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(req)
end
puts JSON.parse(res.body)
@Varun-garg
Copy link
Author

Varun-garg commented May 14, 2021

Obtaining token (source: https://github.com/yuya373/emacs-slack#how-to-get-token):

  1. Go to https://my.slack.com/customize
  2. Open developer tools
  3. Go to the console and enter: window.prompt("your api token is: ", TS.boot_data.api_token)
  4. create env variable SLACK_TOKEN and set it to the token

Example usage (crontab)

# Slack update lunch during weekdays 2:30 PM - 3:00 PM.
30 14 * * 1-5 bash -lc "slack_status lunch 1>&2"
# slack sign off weekdays 8:30 PM till midnight.
30 20 * * 1-5 bash -lc "slack_status signed_off 1>&2"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment