Created
February 14, 2017 15:53
-
-
Save astyagun/5d3c6533e2f9c4ce5a4bed9916327eb2 to your computer and use it in GitHub Desktop.
Counts the number of occurrences of links to most popular domains
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Quick and dirty Slack channel links counter. Counts the number of occurrences of links to most popular domains. | |
require 'slack' # gem install slack-api | |
TOKEN = ENV['TOKEN'] | |
CHANNEL_NAME = 'general' | |
client = Slack::Client.new token: TOKEN | |
channel_detector = proc { |channel| channel['name'] == CHANNEL_NAME } | |
channel_id = client.channels_list['channels'].find(&channel_detector)['id'] | |
# Fetch messages | |
source_messages = [] | |
has_more = true | |
latest = 0 | |
while has_more | |
response = client.channels_history channel: channel_id, latest: latest | |
source_messages.concat response['messages'] | |
has_more = response['has_more'] | |
latest = source_messages.last['ts'] | |
end | |
# Collect domains | |
domains = {} | |
source_messages.each do |source_message| | |
source_message['text'].scan(/<[^>]+>/).each do |_link| | |
link = _link.match URI::regexp(%w(http https)) | |
if link | |
domain = link[4] | |
domains[domain] ||= 0 | |
domains[domain] += 1 | |
end | |
end | |
end | |
sorted_domains = domains.sort_by { |domain, count| -count } | |
# Remove unpopular domains | |
sorted_domains = sorted_domains.find_all { |domain, count| count > 2 } | |
# Render message | |
message = "Messages scanned: #{source_messages.length}" | |
unless sorted_domains.empty? | |
message += "\nMost popular domains:" | |
message += sorted_domains.inject('') { |result, (domain, count)| result += "\n>#{domain}: #{count}" } | |
else | |
message += 'No popular domains found' | |
end | |
puts message | |
# Send report | |
puts client.chat_postMessage \ | |
channel: channel_id, | |
text: message, | |
username: 'Links counter' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment