Slack2Mattermost_dms_converter/slack-converter.rb
2019-07-08 18:15:49 +02:00

101 lines
2.1 KiB
Ruby

require 'json'
# this class converts the direct messages from a slack export to
# a format wich can then be imported by mattermost
# author Daniel Schubert <mail@schubertdaniel.de>
class ImportDMS
def initialize()
@dms = {}
@users = {}
self.xtract_users
self.xtract_dms
end
def xtract_users()
data = self.read_json('users.json')
data.each do |d|
@users.store( d["id"], d["name"])
end
end
def xtract_dms()
data = self.read_json('dms.json')
data.each do |d|
@dms.store( d["id"],d["members"])
end
end
def read_json( file )
f = File.open file
d = JSON.load f
end
def get_usr_name( id )
unless (id == nil)
@users.fetch(id)
end
end
def cnvrt_ts( ts )
# converts the slack timestamp to a mattermost timestamp
t = ts.sub!(".", "")
t[0,13]
end
def get_messages(chat_id)
files = Dir.glob("#{chat_id}/*.json")
chats = Array.new
files.each { |file|
f = read_json( file )
f.each { |m|
n = self.get_usr_name( m["user"] )
ts = self.cnvrt_ts( m["ts"] )
#user,ts, test
chats.push( [ts, n, m["text"]] )
}
}
return chats
end
def create_json
# version; required
puts '{"type":"version","version":1}'
@dms.each_key do |key|
#get user names
user_names = []
@dms.fetch(key).each do |u_id|
user_names.push( @users.fetch(u_id) )
end
self.create_channel_list(user_names)
self.create_direct_messages(key, user_names)
end
end
def create_direct_messages(key, user_names)
#TODO : replies are output as normal messages; should be grouped as replies
# create direct messages list
m = get_messages(key)
m.each do |msg|
ml = {"type"=>"direct_post","direct_post"=>{"channel_members" => user_names, "user" => msg[1], "message" => msg[2], "create_at" => msg[0].to_i, "flagged_by" => nil, "reactions" => nil, "replies"=> nil, "attachments"=> nil } }.to_json
puts ml
end
end
def create_channel_list( user_names )
cl = {"type" => "direct_channel", "direct_channel" => {"members" => user_names, "favorited_by" => nil,"header" => "" }}.to_json
puts cl
end
end
# usage
i = ImportDMS.new
i.create_json