Skip to content

Instantly share code, notes, and snippets.

@vinzenzweber
Last active August 5, 2019 14:35
Show Gist options
  • Save vinzenzweber/94e70a9c72b7699999104e1505b9d4d7 to your computer and use it in GitHub Desktop.
Save vinzenzweber/94e70a9c72b7699999104e1505b9d4d7 to your computer and use it in GitHub Desktop.
Post text notifications to a Slack channel using a webhook https://api.slack.com/incoming-webhooks
# frozen_string_literal: true
# 1. Manage your Slack apps at https://your_slack_team_name.slack.com/apps/manage
# 2. Create an 'Incoming WebHooks' configuration
require 'net/http'
require 'json'
class Slack
def self.post(text, channel = '#channel', username = 'default username')
# 3. Copy/paste the webhook here
uri = URI('https://hooks.slack.com/services/your_webhook')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
req.body = { channel: channel, username: username, text: text }.to_json
res = http.request(req)
rescue StandardError => e
puts "failed #{e}"
end
end
Slack.post("Some notification text")
Slack.post("Some notification text", "#notifications", "Github")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment