GithubHelp home page GithubHelp logo

slack-notifier's Introduction

A simple wrapper to send notifications to Slack webhooks.

Build Status Code Climate Gem Version SemVer

Example

require 'slack-notifier'

notifier = Slack::Notifier.new "WEBHOOK_URL"
notifier.ping "Hello World"
# => if your webhook is setup, will message "Hello World"
# => to the default channel you set in slack

Installation

Install the latest stable release:

$ gem install slack-notifier

Or with Bundler, add it to your Gemfile:

gem "slack-notifier"

Setting Defaults

On initialization you can set default payloads by calling defaults in an initialization block:

notifier = Slack::Notifier.new "WEBHOOK_URL" do
  defaults channel: "#default",
           username: "notifier"
end

notifier.ping "Hello default"
# => will message "Hello default"
# => to the "#default" channel as 'notifier'

To get the WEBHOOK_URL you need:

  1. go to https://slack.com/apps/A0F7XDUAZ-incoming-webhooks
  2. choose your team, press configure
  3. in configurations press add configuration
  4. choose channel, press "Add Incoming WebHooks integration"

You can also set defaults through an options hash:

notifier = Slack::Notifier.new "WEBHOOK_URL", channel: "#default",
                                              username: "notifier"

These defaults are over-ridable for any individual ping.

notifier.ping "Hello random", channel: "#random"
# => will ping the "#random" channel

Links

Slack requires links to be formatted a certain way, so the default middlware stack of slack-notifier will look through your message and attempt to convert any html or markdown links to slack's format before posting.

Here's what it's doing under the covers:

message = "Hello world, [check](http://example.com) it <a href='http://example.com'>out</a>"
Slack::Notifier::Util::LinkFormatter.format(message)
# => "Hello world, <http://example.com|check> it <http://example.com|out>"

Formatting

Slack supports various different formatting options. For example, if you want to alert an entire channel you include <!channel> in your message

message = "<!channel> hey check this out"
notifier.ping message

#ends up posting "@channel hey check this out" in your Slack channel

You can see Slack's message documentation here

Escaping

Since sequences starting with < have special meaning in Slack, you should use Slack::Notifier::Util::Escape.html if your messages may contain &, < or >.

link_text = Slack::Notifier::Util::Escape.html("User <[email protected]>")
message = "Write to [#{link_text}](mailto:[email protected])"
notifier.ping message

Blocks

This plugin supports the Slack blocks format and block kit builder. This is useful for displaying buttons, dropdowns, and images.

blocks = [
  {
    "type": "image",
    "title": {
      "type": "plain_text",
      "text": "image1",
      "emoji": true
    },
    "image_url": "https://api.slack.com/img/blocks/bkb_template_images/onboardingComplex.jpg",
    "alt_text": "image1"
  },
  {
    "type": "section",
    "text": {
      "type": "mrkdwn",
      "text": "Hey there ๐Ÿ‘‹ I'm TaskBot. I'm here to help you create and manage tasks in Slack.\nThere are two ways to quickly create tasks:"
    }
  }
]

notifier.post(blocks: blocks)

Additional parameters

Any key passed to the post method is posted to the webhook endpoint. Check out the Slack webhook documentation for the available parameters.

Setting an icon:

notifier.post text: "feeling spooky", icon_emoji: ":ghost:"
# or
notifier.post text: "feeling chimpy", icon_url: "http://static.mailchimp.com/web/favicon.png"

Adding attachments:

a_ok_note = {
  fallback: "Everything looks peachy",
  text: "Everything looks peachy",
  color: "good"
}
notifier.post text: "with an attachment", attachments: [a_ok_note]

HTTP options

With the default HTTP client, you can send along options to customize its behavior as :http_options params when you post or initialize the notifier.

notifier = Slack::Notifier.new 'WEBHOOK_URL', http_options: { open_timeout: 5 }
notifier.post text: "hello", http_options: { open_timeout: 10 }

Note: you should only send along options that Net::HTTP has as setters, otherwise the option will be ignored and show a warning.

Proxies

:http_options can be used if you need to connect to Slack via an HTTP proxy. For example, to connect through a local squid proxy the following options would be used.

notifier = Slack::Notifier.new 'WEBHOOK_URL', http_options: {
                                                              proxy_address:  'localhost',
                                                              proxy_port:     3128,
                                                              proxy_from_env: false
                                                            }

Custom HTTP Client

There is a packaged default client wrapping Net::HTTP, but your HTTP needs might be a little different. In that case, you can pass in your own wrapper to handle sending the notifications. It just needs to respond to ::post with the arguments of the endpoint URI, and the payload pretty much the same as Net:HTTP.post_form.

A simple example:

module Client
  def self.post uri, params={}
    Net::HTTP.post_form uri, params
  end
end

notifier = Slack::Notifier.new 'WEBHOOK_URL' do
  http_client Client
end

It's also encouraged for any custom HTTP implementations to accept the :http_options key in params.

Setting client per post

You can also set the http_client per-post if you need to special case certain pings.

notifier.post text: "hello", http_client: CustomClient

Setting a No-Op client

In development (or testing), you may want to watch the behavior of the notifier without posting to slack. This can be handled with a no-op client.

class NoOpHTTPClient
  def self.post uri, params={}
    # bonus, you could log or observe posted params here
  end
end

notifier = Slack::Notifier.new 'WEBHOOK_URL' do
  http_client NoOpHTTPClient
end

Middleware

By default slack-notifier ships with middleware to format links in the message & text field of attachments. You can configure the middleware a notifier will use on initialization:

notifier = Slack::Notifier.new "WEBHOOK_URL" do
  middleware format_message: { formats: [:html] }
end
# this example will *only* use the format_message middleware and only format :html links

notifier.post text: "Hello <a href='http://example.com'>world</a>! [visit this](http://example.com)"
# => will post "Hello <http://example.com|world>! [visit this](http://example.com)"

The middleware can be set with a their name, or by name and options. They will be triggered in order.

notifier = Slack::Notifier.new "WEBHOOK_URL" do
  middleware :format_message, :format_attachments
end
# will run format_message then format_attachments with default options

notifier = Slack::Notifier.new "WEBHOOK_URL" do
  middleware format_message: { formats: [:html] },
             format_attachments: { formats: [:markdown] }
end
# will run format_message w/ formats [:html] then format_attachments with formats [:markdown]

Available middleware:

format_message

This middleware takes the :text key of the payload and runs it through the Linkformatter. You can configure which link formats to look for with a :formats option. You can set [:html] (only html links), [:markdown] (only markdown links) or [:html, :markdown] (the default, will format both).

format_attachments

This middleware takes the :text key of any attachment and runs it through the Linkformatter. You can configure which link formats to look for with a :formats option. You can set [:html] (only html links), [:markdown] (only markdown links) or [:html, :markdown] (the default, will format both).

at

This simplifies the process of notifying users and rooms to messages. By adding an :at key to the payload w/ an array of symbols the appropriately formatted commands will be prepended to the message. It will accept a single name, or an array.

For example:

notifier.post text: "hello", at: :casper
# => "<@casper> hello"

notifier.post text: "hello", at: [:here, :waldo]
# => "<!here> <@waldo> hello"

channels

If the channel argument of a payload is an array this splits the payload to be posted to each channel.

For example:

notifier.post text: "hello", channel: ["default", "all_the_things"]
# => will post "hello" to the default and all_the_things channel

To send a message directly to a user, their username no longer works. Instead you'll need to get the user's ID and set that as the channel.

At the time of writing, one way to get a user's ID is to:

  • go to their profile
  • click ... ("More actions")
  • click Copy Member ID

Writing your own Middleware

Middleware is fairly straightforward, it is any class that inherits from Slack::Notifier::PayloadMiddleware::Base and responds to #call. It will always be given the payload as a hash and should return the modified payload as a hash.

For example, lets say we want to replace words in every message, we could write a middleware like this:

class SwapWords < Slack::Notifier::PayloadMiddleware::Base
  middleware_name :swap_words # this is the key we use when setting
                              # the middleware stack for a notifier

  options pairs: ["hipchat" => "slack"] # the options takes a hash that will
                                        # serve as the default if not given any
                                        # when initialized

  def call payload={}
    return payload unless payload[:text] # noope if there is no message to work on

    # not efficient, but it's an example :)
    options[:pairs].each do |from, to|
      payload[:text] = payload[:text].gsub from, to
    end

    payload # always return the payload from your middleware
  end
end


notifier = Slack::Notifier.new "WEBHOOK_URL" do
  middleware :swap_words # setting our stack w/ just defaults
end
notifier.ping "hipchat is awesome!"
# => pings slack with "slack is awesome!"

notifier = Slack::Notifier.new "WEBHOOK_URL" do
  # here we set new options for the middleware
  middleware swap_words: { pairs: ["hipchat" => "slack",
                                   "awesome" => "really awesome"]}
end

notifier.ping "hipchat is awesome!"
# => pings slack with "slack is really awesome!"

If your middleware returns an array, that will split the message into multiple pings. An example for pinging multiple channels:

class MultiChannel < Slack::Notifier::PayloadMiddleware::Base
  middleware_name :channels

  def call payload={}
    return payload unless payload[:channel].respond_to?(:to_ary)

    payload[:channel].to_ary.map do |channel|
      pld = payload.dup
      pld[:channel] = channel
      pld
    end
  end
end

Versioning

Since version 1.0 has been released, the aim is to follow Semantic Versioning as much as possible. However, it is encouraged to check the changelog when updating to see what changes have been made.

To summarize the reasoning for versioning:

Given a version number MAJOR.MINOR.PATCH, increment:

- MAJOR version when incompatible API changes are made
- MINOR version for adding functionality in a backwards-compatible manner or bug fixes that *may* change behavior
- PATCH version for make backwards-compatible bug fixes

Testing

$ rspec

There is also an integration test setup to just double check pinging across the supported rubies. To run:

  1. Copy the .env-example file to .env and replace with your details.
  2. Make sure bin/test is executable
  3. then run and watch for the pings in your slack room
$ bin/test

Contributing

If there is any thing you'd like to contribute or fix, please:

  • Fork the repo
  • Add tests for any new functionality
  • Make your changes
  • Verify all new & existing tests pass
  • Make a pull request

License

The slack-notifier gem is distributed under the MIT License.

slack-notifier's People

Contributors

alexjfisher avatar aurelien-iapp avatar bruskiza avatar dlackty avatar dormi avatar greysteil avatar kazuooooo avatar keithpitty avatar markquezada avatar monkbroc avatar olivierlacan avatar olleolleolle avatar patrickdavey avatar pirj avatar pocke avatar razielgn avatar rememberlenny avatar revolter avatar rkallensee avatar s-osa avatar siegy22 avatar snow avatar stevenosloan avatar veverkap avatar walski avatar waynn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

slack-notifier's Issues

JIRA ticket channel.

Does anyone know if there is channel available for JIRA to create tickets if we get exception ?

Warn if initializing with the old method signature

Hey Steven!

I was just bit by a little something. I (finally) got around to updating some gems and when I rolled out my changes to our staging app we started seeing the following exception - TypeError: no implicit conversion of Symbol into String with the following stack-trace:

[GEM_ROOT]/gems/slack-notifier-1.0.0/lib/slack-notifier.rb:14 :in `delete`
[GEM_ROOT]/gems/slack-notifier-1.0.0/lib/slack-notifier.rb:14 :in `initialize`

Because I replace Slack::Notifier with a custom FakeSlack::Notifier in our test environment ... my tests never caught this. I was baffled until I looked the slack-notifier source and noticed the initializer's method signature changed.

Now, this is just fine, but I'm thinking a warning to people passing in two strings (the old way) would be SUPER valuable. I would have noticed this earlier. If you're cool with it I'd be more than happy to submit a PR for this.

Thoughts?

"\xE4" on US-ASCII

I ran slack function by fastlane and got the following error message ("\xE4" on US-ASCII):

/Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-1.2.0/lib/slack-notifier.rb:23:in `encode': "\xE4" on US-ASCII (Encoding::InvalidByteSequenceError)
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-1.2.0/lib/slack-notifier.rb:23:in `to_json'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-1.2.0/lib/slack-notifier.rb:23:in `ping'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/actions/slack.rb:57:in `run'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/fast_file.rb:112:in `block (2 levels) in method_missing'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/actions/actions_helper.rb:35:in `execute_action'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/fast_file.rb:94:in `block in method_missing'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/fast_file.rb:93:in `chdir'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/fast_file.rb:93:in `method_missing'
    from (eval):159:in `block (3 levels) in parse'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/runner.rb:49:in `call'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/runner.rb:49:in `block in execute'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/runner.rb:45:in `chdir'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/runner.rb:45:in `rescue in execute'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/runner.rb:8:in `execute'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/lib/fastlane/lane_manager.rb:33:in `cruise_lane'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/bin/fastlane:39:in `block (2 levels) in run'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/commander-4.3.4/lib/commander/command.rb:178:in `call'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/commander-4.3.4/lib/commander/command.rb:178:in `call'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/commander-4.3.4/lib/commander/command.rb:153:in `run'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/commander-4.3.4/lib/commander/runner.rb:428:in `run_active_command'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/commander-4.3.4/lib/commander/runner.rb:68:in `run!'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/commander-4.3.4/lib/commander/delegates.rb:15:in `run!'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/bin/fastlane:118:in `run'
    from /Users/XXXXXXXX/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/fastlane-0.13.0/bin/fastlane:124:in `<top (required)>'
    from /Users/XXXXXXXX/.rvm/gems/ruby-2.2.1/bin/fastlane:23:in `load'
    from /Users/XXXXXXXX/.rvm/gems/ruby-2.2.1/bin/fastlane:23:in `<main>'
    from /Users/XXXXXXXX/.rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `eval'
    from /Users/XXXXXXXX/.rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `<main>'

I think I didn't use a character รค (\xE4) for the parameter message. Any idea or suggestion about this?

Can't send message to private groups

After #6, I tried to port this change to similar libraries in different languages. However, someone pointed out that "Slack uses no prefix for private groups", so this "automatically add # prefix" approach make it impossible to send message to private groups.

I saw you made a change for private message in b85a3d1, but had no idea how we could workaround this without introducing new syntax for private groups. (e.g. add . before names)

Any idea?

Raise on API Error?

Hey man, it's been a time since I worked on this. But I just added it to a project and experienced that when the API call fails, it just returns the HTTP repsonse. IMO this should definitely throw an error.
What do you think @stevenosloan?
If you're okay with raising an error I could work on a PR to achieve this.

Cheers ๐Ÿป

Send snippet using Slack API

Hi,

Not really an issue, but is it possible to create a message including a snippet from the API using a specific markup ? I cannot see anything related in Slack documentation.

Thanks.

Language accent not displayed properly in Slack

Hi @stevenosloan,

Thanks for this wrapper that's very useful. I have a problem though with french accent being rendered as question marks when they land in Slack when posted with your client.

I tried a manual curl to my Slack webhook and accents are parsed ok.
Could you help me on this?

Thanks !

Error when upgrade to `2.2.0` from `2.1.0`

Bundler::GemRequireError: There was an error while trying to load the gem 'slack-notifier'.
Gem Load Error is: uninitialized constant Slack
Backtrace for gem load error is:

just me?

Error when using ping to send a message

I'm trying this:
irb(main):013:0> notifier = Slack::Notifier.new "https://hooks.slack.com/services/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2K", channel: "#qe", username: "notifier"

Then:
irb(main):014:0> notifier.ping "Hi", channel: "#qe"

I get this error message:
URI::InvalidURIError: bad URI(is not URI?): https://https://hooks.slack.com/services/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.slack.com/services/hooks/incoming-webhook?token={:channel=>"#qe", :username=>"notifier"}

Syntax Error: unexpected tLABEL

Getting the following error when trying to load the gem:
/gems_path/.gem/ruby/1.9.1/gems/slack-notifier-2.1.0/lib/slack-notifier.rb:6:in `require_relative': /gems_path/.gem/ruby/1.9.1/gems/slack-notifier-2.1.0/lib/slack-notifier/util/link_formatter.rb:20: syntax error, unexpected tLABEL (SyntaxError) def initialize string, formats: [:html, :markdown] ^ /gems_path/.gem/ruby/1.9.1/gems/slack-notifier-2.1.0/lib/slack-notifier/util/link_formatter.rb:63: syntax error, unexpected keyword_end, expecting $end from /gems_path/.gem/ruby/1.9.1/gems/slack-notifier-2.1.0/lib/slack-notifier.rb:6:in `<top (required)>' from /gems_path/.gem/ruby/1.9.1/gems/bundler-1.11.2/lib/bundler/runtime.rb:77:in `require' from /gems_path/.gem/ruby/1.9.1/gems/bundler-1.11.2/lib/bundler/runtime.rb:77:in `block (2 levels) in require' from /gems_path/.gem/ruby/1.9.1/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each' from /gems_path/.gem/ruby/1.9.1/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require' from /gems_path/.gem/ruby/1.9.1/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each' from /gems_path/.gem/ruby/1.9.1/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require' from /gems_path/.gem/ruby/1.9.1/gems/bundler-1.11.2/lib/bundler.rb:99:in `require' from build.rb:3:in `<main>'
I'm running Ruby version 1.9.3p551

Thread support?

I'm trying to post with a thread_ts that I know corresponds to a thread's ts but it's still printed to the channel, not the thread in the channel. If I omit the channel parameter to the post call, it's not posted to the channel at all. How can I post a message to an existing thread?

Here's the Slack Threading API docs.

Async call

We send slack messages when our users create a booking and don't want the messaging blocking the booking process.

Would an async call make sense for this gem? If yes, I can open a pull request.

How to use http proxy

Hi

I'm trying to use this gem to connect to slack through an http proxy. It looks like this should be possible by setting http_options, but so far, no luck. Perhaps I'm doing something wrong. There are setters for proxy_address and proxy_port

So

Slack::Notifier.new 'WEBHOOK_URL', http_options: { proxy_address: 'proxy.example.com', proxy_port: 3128 }

should work? Or am I missing something...

Thanks

Errors after upgrade from 2.1.0 => 2.2.2

Hello,

Upgraded recently the gem and started getting these weird errors:

Slack::Notifier::APIError: The slack API returned an error: missing_text_or_fallback_or_attachments (HTTP Code 500)Check the "Handling Errors" section on https://api.slack.com/incoming-webhooks for more information

When testing in cli, everything seems to be normal, I get the message in the channel. What could be an issue?

Thank you

Could you add icon_url to set the bots icon?

From docs:

You can customize the name and icon of your Incoming Webhook in the Integration Settings section below.
However, you can override the displayed name by sending "username": "new-bot-name" in your JSON payload. You can also override the bot icon either with "icon_url": "https://slack.com/img/icons/app-57.png" or "icon_emoji": ":ghost:".

Passing array into ping has some weird side effects

First off, I have added on to the ping method. Here's my ping method:

def ping(message)
    if message.is_a? Array
        final = message.join("\n")
        @slack.ping(final)
    end
    @slack.ping(message)
end

You can ping a string line normal, but you can pass through an array, which will format it as a string with \n characters. This will let you send multi line messages in slack. eg.

ping(['line1', 'line2', 'line3'])

in slacks appears as:

line1
line2
line3

This runs fine, but after execution I get the following error:

NoMethodError: undefined method `gsub' for ["line1", "line2", "line3"]:Array
from /var/lib/gems/2.1.0/gems/slack-notifier-2.1.0/lib/slack-notifier/util/link_formatter.rb:42:in `sub_html_links'

I believe this has something to do with how slack-notifier parses links. I don't fully understand this, I'm not sure if this is intended behavior. The ping goes through and sends without a problem first, and then the error happens.

Direct messages

Is it possible to send direct message as well with slack-notifier?

Format links

would be cool to take html or markdown links and format them for slack

<url> or <url|text>

Dummy client in development

Hi,

I only want to send events to Slack in production, not in development.

I was thinking of creating a Slack::DummyNotifier that implements the same methods as Slack::Notifier all as no-ops.

Would you consider pulling this into the gem if I send a pull request?

Any other way you are using to avoid flooding Slack while developing?

Slack::Notifier::APIError: The slack API returned an error: action_prohibited (HTTP Code 500)

I got 500 error with simple test code. any idea what is missing?

notifier = Slack::Notifier.new webhook do
  defaults channel: "#test"
end
notifier.ping "Hello"
Slack::Notifier::APIError: The slack API returned an error: action_prohibited (HTTP Code 500)
Check the "Handling Errors" section on https://api.slack.com/incoming-webhooks for more information

	from /Users/xxx/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-2.2.2/lib/slack-notifier/util/http_client.rb:29:in `block in call'
	from /Users/xxx/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-2.2.2/lib/slack-notifier/util/http_client.rb:27:in `tap'
	from /Users/xxx/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-2.2.2/lib/slack-notifier/util/http_client.rb:27:in `call'
	from /Users/xxx/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-2.2.2/lib/slack-notifier/util/http_client.rb:14:in `post'
	from /Users/xxx/.rvm/gems/ruby-2.2.1@global/gems/slack-notifier-2.2.2/lib/slack-notifier.rb:47:in `post'
	from /Users/xxx/.rvm/gems/ruby-2.2.1@global/gems/slack-notifier-2.2.2/lib/slack-notifier.rb:36:in `ping'
	from (irb):63
	from /Users/xxx/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'

LinkFormatter.format method doesn't work, if a line includes multiple links

LinkFormatter.format method doesn't render text correctly in Slack, if a line includes multiple links.

procedure for reproducing the bug is following. thanks in advance. :)

require 'slack-notifier'
corret_link = "<a href='https://github.com/'>github</a>"
wrong_link = "<a href='https://github.com/'>github</a><a href='https://slack.com'>slack</a>"

Slack::Notifier::LinkFormatter.format(corret_link) # works fine
Slack::Notifier::LinkFormatter.format(wrong_link) # doesn't work

`rescue in split': bad URI(is not URI?)

@stevenosloan Using Hash values in initialize Slack::Notifier.new return this error

/Users//.rbenv/versions/2.2.1/lib/ruby/2.2.0/uri/rfc3986_parser.rb:17:in rescue in split': bad URI(is not URI?): (URI::InvalidURIError) from /Users/**/.rbenv/versions/2.2.1/lib/ruby/2.2.0/uri/rfc3986_parser.rb:14:in split'
from /Users/
/.rbenv/versions/2.2.1/lib/ruby/2.2.0/uri/rfc3986_parser.rb:72:inparse' from /Users/**/.rbenv/versions/2.2.1/lib/ruby/2.2.0/uri/common.rb:226:in parse'
from /Users/**/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/slack-notifier-1.2.1/lib/slack-notifier.rb:13:in `initialize'

Support for jruby-1.7.26 (1.9.3-p551)

I would like to use the slack-notifier gem on the latest version of Puppet Servers which embed unfortunately only jruby 1.7.26 (running 1.9.3p551 ruby).

$> puppetserver ruby --version
jruby 1.7.26 (1.9.3p551) 2016-08-26 69763b8 on OpenJDK 64-Bit Server VM 1.8.0_131-b11 +jit [linux-amd64]

So far, slack-notifier fails on this version:

#> puppetserver gem install slack-notifier
Fetching: slack-notifier-2.1.0.gem (100%)
Successfully installed slack-notifier-2.1.0
1 gem installed
#> puppetserver irb
irb(main):001:0> require 'slack-notifier'
SyntaxError: /opt/puppetlabs/server/data/puppetserver/jruby-gems/gems/slack-notifier-2.1.0/lib/slack-notifier/util/link_formatter.rb:20: syntax error, unexpected tLABEL
        def initialize string, formats: [:html, :markdown]
                                       ^
        from org/jruby/RubyKernel.java:1040:in `require'
        from /opt/puppetlabs/server/apps/puppetserver/puppet-server-release.jar!/META-INF/jruby.home/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:54:in `require'
        from file:/opt/puppetlabs/server/apps/puppetserver/puppet-server-release.jar!/jruby/kernel19/kernel.rb:13:in `require_relative'
        from /opt/puppetlabs/server/data/puppetserver/jruby-gems/gems/slack-notifier-2.1.0/lib/slack-notifier.rb:6:in `(root)'
        from org/jruby/RubyKernel.java:1040:in `require'
        from /opt/puppetlabs/server/apps/puppetserver/puppet-server-release.jar!/META-INF/jruby.home/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:1:in `(root)'
        from /opt/puppetlabs/server/apps/puppetserver/puppet-server-release.jar!/META-INF/jruby.home/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:128:in `require'
        from org/jruby/RubyKernel.java:1079:in `eval'
        from (irb):1:in `evaluate'
        from org/jruby/RubyKernel.java:1479:in `loop'
        from org/jruby/RubyKernel.java:1242:in `catch'
        from org/jruby/RubyKernel.java:1242:in `catch'
        from org/jruby/RubyKernel.java:1059:in `load'
        from /opt/puppetlabs/server/apps/puppetserver/puppet-server-release.jar!/META-INF/jruby.home/bin/irb:17:in `(root)'
        from jruby_core.clj:259:in `invoke'
        from jruby_core.clj:253:in `invoke'
        from jruby_core.clj:270:in `invoke'
        from jruby_core.clj:261:in `invoke'
        from irb.clj:9:in `invokeStatic'
        from irb.clj:6:in `invoke'
        from subcommand.clj:37:in `invokeStatic'
        from subcommand.clj:26:in `invoke'
        from irb.clj:13:in `invokeStatic'
        from irb.clj:11:in `doInvoke'
        from core.clj:646:in `invokeStatic'
        from main.clj:314:in `invokeStatic'
        from main.clj:310:in `invoke'
        from main.clj:421:in `invokeStatic'
        from main.clj:384:in `doInvoke'irb(main):002:0>

Is there a chance you can make your code backward compliant for this version of Ruby ? I confess I don't know how to change util/link_formatter.rb:20 to make it possible, nor if other piece of code use ruby >= 2.0 code.

Add a test mode

Which will be not perform a real HTTP request and actually do nothing

How do i use use "fields" in attachments

I try to implement the fields described here:

"fields": [
                {
                    "title": "Priority",
                    "value": "High",
                    "short": false
                }
            ],

My Syntax for your class is:

msg = "Some Message"
att = {
        fallback: "fallback",
        title: "title",
        text: "text",
        color: "danger",
        author_name: "author name",
        fields: [{
                title: "priority",
                value: "normal",
                short: true
        }]
}
notifier.ping(msg, attachments: [att])

without the fields everything works fine, but i dont get those fields displayed. How do i need to set them up?

Regards

Dirk

Consider a different interface.

slack = Slack::Client.new(whatever)
slack.notify(whatever)

Thinking out loud. If I feel strongly enough after messing with it for a few days, I'll send a pull request your way.

Format URLs as Slack links

If you want to send URLs in Slack, you need to format them as such so they are clickable. Without that, they are just plain text.

LinkFormatter already does markdown and html links, so that is a logical place to put it. I've been trying to figure out how to do this, but the hard part is that you need to regex to match the URL but not match an html or markdown link that's been converted already.

I've found that you can use uri_regexp = URI.regexp(['http', 'https']) to get a uri regexp. I'm not sure if this includes fragments though, ie # on the end.

Would be nice to prepend the hash to channel name

I was getting 500 errors back from slack API with no clue about why (shame on you slack) and it turns out it was because I didn't have the hash prepended to the channel. Would be nice if slack-notifier did it for you if it doesn't see a hash.

notifier.channel  = "\##{channel}"

Stack trace when leaving out message

slack.ping(attachments: [attachment], channel: '#jean-test')
Exception: undefined method `gsub' for #<Hash:0x007fea74b110c8>
/Users/Jean/.gem/ruby/2.2.3/gems/slack-notifier-1.4.0/lib/slack-notifier/link_formatter.rb:22:in `formatted'

I believe this is a valid format, sending only an attachment, correct?

2.0.x Roadmap

Hi Users. Y'all have been fantastic, truely. This Gem is now at over 1 million downloads thanks to you -- and I'm shocked. I never expected this pet project to create such a buzz. I guess other people appreciated a simple interface to just send a message to slack.

With some recent issues I'm seeing a common thread of changes necessary that I believe will lead to the 2.x version of the library, but I want to start to develop these changes out in the open. I don't have too many initial features in mind, but would like to change the interface a bit to make it more flexible for the future. Any issues/features you'd like addressed would be fantastic to hear about.

New Interface (not too different)

notifier = Slack::Notifier.new ENV['WEBHOOK_URL', message: MESSAGE_DEFAULTS, link_formatter: LINK_FORMATTER_DEFAULTS, etc
notifier.ping "The message text", options={ message: CURRENT_ARGS, ARGS_FOR_MIDDLEWARE }

Currently options could contain any number of things (channel, username, icon_emoji, etc) -- things that may pertain to the message, or may not (http_options). In the future any message defaults will go under the key :message, so other keys can be used for other options.

I would also like to think of the LinkFormatter more as middleware. There's nothing particularly special about the way it modifies messages, so to fill cases like those from @technicalpickles -- making it more extensible seems like a good option to me.

A look at how that might work:

class PlainLinkFormatter < Slack::Notifier::Middleware
  register :plain_link

  def format message
    # do the stuff
  end
end

notifier.ping 'the message', format: [:markdown, :plain_link]

This shows creating a new middleware, registering it with a name, and then using it for a message. I'd like to think of a way to "add" a single middleware to a message that isn't necessarily in a default -- but that may come later.

That's about it for my initial thinking -- I'd love to hear any feedback. The work should start relatively soon on a branch 2.0.x.

cheers,
steven

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.