Skip to content

Instantly share code, notes, and snippets.

@techonomics69
Forked from choran/write_to_csv.rb
Created March 24, 2018 22:34
Show Gist options
  • Save techonomics69/2738974a49f89c5e6e8749d6c45f472b to your computer and use it in GitHub Desktop.
Save techonomics69/2738974a49f89c5e6e8749d6c45f472b to your computer and use it in GitHub Desktop.
require 'json'
require 'intercom'
require 'json'
require 'csv'
class ConvoParser
attr_reader :intercom, :output_file
def initialize(client, file_name)
@intercom = client
@output_file = file_name
File.write(file_name, "")
end
def write_to_csv(content)
File.open(output_file, 'a+') do |f|
f.puts(content.to_s + "\n")
end
end
def parse_conversation_part(convo_part)
write_to_csv(",,,,#{convo_part.id}, #{convo_part.part_type}, #{convo_part.body}")
end
def parse_conversation_parts(convo)
total_count = convo.conversation_parts.length
current_count = 0
write_to_csv("#{convo.id}, #{total_count}")
convo.conversation_parts.each do |convo_part|
write_to_csv(",,#{current_count+=1}, #{total_count}")
parse_conversation_part(convo_part)
end
end
end
class ConvoSetup
attr_reader :intercom, :convo_parser
def initialize(access_token, file_name)
# You should alwasy store you access token in a environment variable
# This ensures you never accidentally expose it in your code
@intercom = Intercom::Client.new(token: ENV[access_token])
@convo_parser = ConvoParser.new(intercom, file_name)
end
def get_single_convo(convo_id)
# Get a single conversation
intercom.conversations.find(id: convo_id)
end
def get_all_conversations
# Get the first page of your conversations
convos = intercom.get("/conversations", "")
convos
end
def run
# Get list of all conversations
result = get_all_conversations
# Write the header for the CSV
convo_parser.write_to_csv("CONVO ID, NUM PARTS, PART, TOTAL, PART ID, PART TYPE, PART BODY")
# Parse through each conversation to see what is provided via the list
result["conversations"].each do |single_convo|
convo_parser.parse_conversation_parts(get_single_convo(single_convo['id']))
end
end
end
ConvoSetup.new("AT", "convo_output.csv").run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment