Full Code of MightySignal/slackiq for AI

master 5de9aaecc98e cached
12 files
12.9 KB
3.4k tokens
11 symbols
1 requests
Download .txt
Repository: MightySignal/slackiq
Branch: master
Commit: 5de9aaecc98e
Files: 12
Total size: 12.9 KB

Directory structure:
gitextract_pzzyaxu7/

├── .gitignore
├── CODE_OF_CONDUCT.md
├── Gemfile
├── LICENSE.txt
├── README.md
├── Rakefile
├── bin/
│   ├── console
│   └── setup
├── lib/
│   ├── slackiq/
│   │   ├── time_helper.rb
│   │   └── version.rb
│   └── slackiq.rb
└── slackiq.gemspec

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
/.bundle/
/.yardoc
/Gemfile.lock
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/


================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Code of Conduct

As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.

We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.

Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.

This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)


================================================
FILE: Gemfile
================================================
source 'https://rubygems.org'

# Specify your gem's dependencies in slackiq.gemspec
gemspec

================================================
FILE: LICENSE.txt
================================================
The MIT License (MIT)

Copyright (c) 2015 Jason Lew

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


================================================
FILE: README.md
================================================
# Slackiq 
[![Gem Version](https://badge.fury.io/rb/slackiq.svg)](http://badge.fury.io/rb/slackiq)

Slackiq (pronounced *slack-kick*) integrates [Slack](https://slack.com/) and [Sidekiq](http://sidekiq.org) so that you can have vital information about your Sidekiq jobs sent directly to your team's Slack.

![demo](http://i.imgur.com/4NLq2rP.gif)

## Installation

Add this line to your Gemfile:

```ruby
gem 'slackiq'
```

Then run:

```
bundle install
```

## Configuration

First, set up any number of Slack Incoming Webhooks [from your Slack](https://slack.com/services/new/incoming-webhook).

Then, you only need to call the `configure` method when your application launches to configure all of the webhooks to which you want to post. If you're using Rails, create an initializer at `config/initializers/slackiq.rb`. Here's an example:

```ruby
Slackiq.configure( web_scrapes: 'https://hooks.slack.com/services/HA298HF2/ALSKF2451/lknsaHHA2323KKDKND', 
                   data_processing: 'https://hooks.slack.com/services/HA298HF2/ALSKF2451/H24dLKAHD22423')
```

`:web_scrapes` and `data_processing` are examples of keys. Use whatever keys you want.

## Usage

You can call `notify` to send a nicely-formatted notification to your Slack. You can call `notify`

* Inside the Sidekiq Pro `on_success` or `on_complete` callback (not available on regular Sidekiq--only Pro)
* From inside a Sidekiq worker while it's running, in which case you should pass in the `bid` to the `perform` method of the worker

The `notify` method has a single Hash parameter. Here are the keys and values in the Hash:
* `:webhook_name` The name of the webhook (Symbol) that you configured (eg. `:web_scrapes` or `:data_processing`)
* `:title` The title of the notification (String)
* `:status` An instance of `Sidekiq::Batch::Status`
* Any other keys and values (both Strings) can be added too, and they'll be added to the Slack notification!

If you haven't used batches with Sidekiq Pro before, [read this first](https://github.com/mperham/sidekiq/wiki/Batches).

Here's an example showing how you would use Slackiq to send a notification to your Slack when your Sidekiq batch completes:

```ruby
class WebScraper
  
  class << self
  
    # Scrape the first 100 URLs in the database
    def scrape_100
      batch = Sidekiq::Batch.new
      batch.description = 'Scrape the first 100 URLs!' 
      batch.on(:complete, self)
      
      batch.jobs do
        
      urls = Url.limit(100) # Url is a Rails model in this case
      
      urls.each do |url|
        ScraperWorker.perform_async(url.id)
      end
    end
  
  end
  
  def on_complete(status, options)
    Slackiq.notify(webhook_name: :web_scrapes, status: status, title: 'Scrape Completed!', 
    'Total URLs in DB' => URL.count.to_s, 
    'Servers' => "#{Server.active_count} active, #{Server.inactive_count} inactive")
  end
  
end
```

Note that in this case, `'Total URLs in DB'` and `'Servers'` are custom fields that will also appear in Slack!

### Want to send a message to Slack that isn't Sidekiq-related?

No prob. Just: 

```ruby
Slackiq.message('Server 5 is overloaded!', webhook_name: :data_processing)
```

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/MightySignal/slackiq. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.


## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

## Blog Post about Slackiq

https://blog.mightysignal.com/slackiq-a-ruby-gem-that-connects-slack-and-sidekiq-a2308c1974b7

## More Open Source Projects

* [Slacktivity](https://github.com/MightySignal/slacktivity)



================================================
FILE: Rakefile
================================================
require "bundler/gem_tasks"

task :console do
  exec "irb -r slackiq -I ./lib"
end

task c: :console

================================================
FILE: bin/console
================================================
#!/usr/bin/env ruby

require "bundler/setup"
require "slackiq"

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start

require "irb"
IRB.start


================================================
FILE: bin/setup
================================================
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

bundle install

# Do any other automated setup that you need to do here


================================================
FILE: lib/slackiq/time_helper.rb
================================================
require 'date'

module Slackiq
  module TimeHelper

    class << self
    
      def elapsed_time_humanized(t0, t1)
        humanize(elapsed_seconds(t0, t1))
      end
  
      def elapsed_seconds(t0, t1)
        dt0 = t0.to_datetime
        dt1 = t1.to_datetime
        ((dt1-dt0)*24*60*60).to_i
      end
  
      # http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails
      def humanize(secs)
        [[60, :s], [60, :m], [24, :h], [1000, :d]].map{ |count, name|
          if secs > 0
            secs, n = secs.divmod(count)
            "#{n.to_i}#{name}"
          end
        }.compact.reverse.join(' ')
      end
      
      def format(time)
        time.strftime('%D @ %r').gsub('PM', 'pm').gsub('AM', 'am')
      end
  
    
    end
    
  end
end





================================================
FILE: lib/slackiq/version.rb
================================================
module Slackiq
  VERSION = "1.1.4"
end


================================================
FILE: lib/slackiq.rb
================================================
require 'slackiq/version'

require 'net/http'
require 'json'
require 'httparty'

require 'slackiq/time_helper'

require 'active_support' #for Hash#except

module Slackiq
  
  class << self
    
    # Configure all of the webhook URLs you're going to use
    # @author Jason Lew
    def configure(webhook_urls={})
      raise 'Argument must be a Hash' unless webhook_urls.class == Hash
      @@webhook_urls = webhook_urls
    end
    
    # Send a notification to Slack with Sidekiq info about the batch
    # @author Jason Lew
    def notify(options={})  
      url = @@webhook_urls[options[:webhook_name]]
      title = options[:title]
      #description = options[:description]
      status = options[:status]
      
      if (bid = options[:bid]) && status.nil?
        raise "Sidekiq::Batch::Status is not defined. Are you sure Sidekiq Pro is set up correctly?" unless defined?(Sidekiq::Batch::Status)
        
        status = Sidekiq::Batch::Status.new(bid)
      end
      
      extra_fields = options.except(:webhook_name, :title, :description, :status)

      fields = []
      
      if status
        created_at = status.created_at
      
        if created_at
          time_now = Time.now
          duration = Slackiq::TimeHelper.elapsed_time_humanized(created_at, time_now)
          time_now_title = (status.complete? ? 'Completed' : 'Now')
        end
      
        total_jobs = status.total
        failures = status.failures
        jobs_run = total_jobs - status.pending

        completion_percentage = (jobs_run/total_jobs.to_f)*100
        failure_percentage = (failures/total_jobs.to_f)*100 if total_jobs && failures

        # round to two decimal places
        decimal_places = 2
        completion_percentage = completion_percentage.round(decimal_places)
        failure_percentage = failure_percentage.round(decimal_places)
        
        description = status.description

        fields += [
                    {
                      'title' => 'Created',
                      'value' => Slackiq::TimeHelper.format(created_at),
                      'short' => true
                    },
                    {
                      'title' => time_now_title,
                      'value' => Slackiq::TimeHelper.format(time_now),
                      'short' => true
                    },
                    {
                      'title' => "Duration",
                      'value' => duration,
                      'short' => true
                    },
                    {
                      'title' => "Total Jobs",
                      'value' => total_jobs,
                      'short' => true
                    },
                    {
                      'title' => "Jobs Run",
                      'value' => jobs_run,
                      'short' => true
                    },
                    {
                      'title' => "Completion %",
                      'value' => "#{completion_percentage}%",
                      'short' => true
                    },
                    {
                      'title' => "Failures",
                      'value' => status.failures,
                      'short' => true
                    },
                    {
                      'title' => "Failure %",
                      'value' => "#{failure_percentage}%",
                      'short' => true
                    },
                  ]
      end
      
      
      
      # add extra fields
      fields += extra_fields.map do |title, value|
        {
          'title' => title,
          'value' => value,
          'short' => false
        }
      end
                
      attachments = 
      [
        {
          'fallback' => title,

          'color' => '#00ff66',

          'title' => title,

          'text' => description,

          'fields' => fields,
        }
    ]
    
      body = {attachments: attachments}.to_json
      
      HTTParty.post(url, body: body)
    end

    # Send a notification without Sidekiq batch info
    # @author Jason Lew
    def message(text, options)
      url = @@webhook_urls[options[:webhook_name]]

      body = { 'text' => text }.to_json
      
      HTTParty.post(url, body: body)
    end
    
  end
  
end

================================================
FILE: slackiq.gemspec
================================================
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'slackiq/version'

Gem::Specification.new do |spec|
  spec.name          = "slackiq"
  spec.version       = Slackiq::VERSION
  spec.authors       = ['Jason Lew']
  spec.email         = ['jason@mightysignal.com']
  spec.summary       = 'MightySignal: Slack and Sidekiq Pro integration'
  spec.description   = "Slackiq (by MightySignal) integrates Slack and Sidekiq so that you can have vital information about your Sidekiq jobs sent directly to your team's Slack."
  spec.homepage      = 'https://github.com/MightySignal/slackiq'
  spec.license       = 'MIT'

  spec.files         = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
  spec.bindir        = "exe"
  spec.executables   = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
  spec.require_paths = ["lib"]

  spec.add_dependency 'httparty'

  spec.add_development_dependency "bundler", "~> 1.10"
  spec.add_development_dependency "rake", "~> 10.0"
end
Download .txt
gitextract_pzzyaxu7/

├── .gitignore
├── CODE_OF_CONDUCT.md
├── Gemfile
├── LICENSE.txt
├── README.md
├── Rakefile
├── bin/
│   ├── console
│   └── setup
├── lib/
│   ├── slackiq/
│   │   ├── time_helper.rb
│   │   └── version.rb
│   └── slackiq.rb
└── slackiq.gemspec
Download .txt
SYMBOL INDEX (11 symbols across 3 files)

FILE: lib/slackiq.rb
  type Slackiq (line 11) | module Slackiq
    function configure (line 17) | def configure(webhook_urls={})
    function notify (line 24) | def notify(options={})
    function message (line 140) | def message(text, options)

FILE: lib/slackiq/time_helper.rb
  type Slackiq (line 3) | module Slackiq
    type TimeHelper (line 4) | module TimeHelper
      function elapsed_time_humanized (line 8) | def elapsed_time_humanized(t0, t1)
      function elapsed_seconds (line 12) | def elapsed_seconds(t0, t1)
      function humanize (line 19) | def humanize(secs)
      function format (line 28) | def format(time)

FILE: lib/slackiq/version.rb
  type Slackiq (line 1) | module Slackiq
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (14K chars).
[
  {
    "path": ".gitignore",
    "chars": 87,
    "preview": "/.bundle/\n/.yardoc\n/Gemfile.lock\n/_yardoc/\n/coverage/\n/doc/\n/pkg/\n/spec/reports/\n/tmp/\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 1434,
    "preview": "# Contributor Code of Conduct\n\nAs contributors and maintainers of this project, we pledge to respect all people who cont"
  },
  {
    "path": "Gemfile",
    "chars": 91,
    "preview": "source 'https://rubygems.org'\n\n# Specify your gem's dependencies in slackiq.gemspec\ngemspec"
  },
  {
    "path": "LICENSE.txt",
    "chars": 1076,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Jason Lew\n\nPermission is hereby granted, free of charge, to any person obtaini"
  },
  {
    "path": "README.md",
    "chars": 3808,
    "preview": "# Slackiq \n[![Gem Version](https://badge.fury.io/rb/slackiq.svg)](http://badge.fury.io/rb/slackiq)\n\nSlackiq (pronounced "
  },
  {
    "path": "Rakefile",
    "chars": 100,
    "preview": "require \"bundler/gem_tasks\"\n\ntask :console do\n  exec \"irb -r slackiq -I ./lib\"\nend\n\ntask c: :console"
  },
  {
    "path": "bin/console",
    "chars": 332,
    "preview": "#!/usr/bin/env ruby\n\nrequire \"bundler/setup\"\nrequire \"slackiq\"\n\n# You can add fixtures and/or initialization code here t"
  },
  {
    "path": "bin/setup",
    "chars": 115,
    "preview": "#!/bin/bash\nset -euo pipefail\nIFS=$'\\n\\t'\n\nbundle install\n\n# Do any other automated setup that you need to do here\n"
  },
  {
    "path": "lib/slackiq/time_helper.rb",
    "chars": 815,
    "preview": "require 'date'\n\nmodule Slackiq\n  module TimeHelper\n\n    class << self\n    \n      def elapsed_time_humanized(t0, t1)\n    "
  },
  {
    "path": "lib/slackiq/version.rb",
    "chars": 39,
    "preview": "module Slackiq\n  VERSION = \"1.1.4\"\nend\n"
  },
  {
    "path": "lib/slackiq.rb",
    "chars": 4250,
    "preview": "require 'slackiq/version'\n\nrequire 'net/http'\nrequire 'json'\nrequire 'httparty'\n\nrequire 'slackiq/time_helper'\n\nrequire "
  },
  {
    "path": "slackiq.gemspec",
    "chars": 1068,
    "preview": "# coding: utf-8\nlib = File.expand_path('../lib', __FILE__)\n$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)\nrequi"
  }
]

About this extraction

This page contains the full source code of the MightySignal/slackiq GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (12.9 KB), approximately 3.4k tokens, and a symbol index with 11 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!