LoginSignup
7

More than 5 years have passed since last update.

Slackに書いた分報をrubyでまとめる、少しは雑じゃないコード

Posted at

Slackに書いた分報をjqでまとめる雑なワンライナー の続きです

matome.rb
#! /usr/bin/env ruby
require 'slack'

Slack.configure do |config|
  config.token = ENV['SLACK_TOKEN']
end
client = Slack::Client.new

channel_name = ARGV[0]
if channel_name.nil?
  puts 'no channel name'
  exit 1
end

channel = client.channels_list(exclude_archived: 1)["channels"].find { |c| c["name"] == channel_name }
history = client.channels_history(channel: channel['id'], oldest: (Time.now - (60 * 60 * 24)).to_i, count: 1000)['messages'].reverse
users = {}
history.each do |message|
  next unless message['user']
  said_at = Time.at(message['ts'].to_i).strftime('%T')
  user = (users[message['user']] ||= client.users_info(user: message['user'])['user']['name'] )
  text = message['text'].gsub('|', '\\|').gsub("\n", '<br>').gsub('```', '')
  puts [said_at, user, text].join(' | ')
end

雑な解説

  • slack-api-gem を使っています
  • 環境変数でトークンを、引数でチャンネル名を渡します
  • 文字列加工部分は多分に個人都合です(markdownのtbodyにあたる部分にコピペで貼り付けるための加工をしている)
  • user名を1行毎に取りに行くとすごい量のAPIアクセスになるので、キャッシュしてます

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7