Created
January 25, 2018 23:50
-
-
Save fool/d7f87d776e1ff3007fbc7f70130bc8f0 to your computer and use it in GitHub Desktop.
Rake tasks to sync user and conversation tags from Intercom to a database
This file contains 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
require 'intercom' | |
namespace :sync do | |
desc "Migrate tags table with full list of intercom tags" | |
task :tag_list => :environment do | |
intercom = IntercomHelper.api | |
intercom.tags.all.each do |tag| | |
if Tag.where(tag_id: tag.id).count == 0 | |
Tag.create!(tag_id: tag.id, name: tag.name) | |
end | |
end | |
end | |
desc "Sync intercom user and company tags with user_tags in database" | |
task :user_tags => :environment do | |
intercom = IntercomHelper.api | |
Tag.all.each do |tag| | |
begin | |
intercom.users.find_all(tag_id: tag.tag_id).each do |user| | |
if UserTag.where(tag_id: tag.tag_id).where(user_id: user.user_id).count == 0 | |
# Choose properties to sync | |
UserTag.create!(user_id: user.user_id, user_email: user.email, tag_id: tag.tag_id, tag_name: tag.name, tag_type: 'user', monthly_spend: user.custom_attributes[:monthly_spend]) | |
end | |
end | |
rescue | |
tag.deleted_time = Time.now | |
tag.save | |
end | |
end | |
end | |
desc "Sync intercom conversation tags with conversation_tags in database" | |
task :conversation_tags => :environment do | |
intercom = IntercomHelper.api | |
#iterate through customer success admins id's, gather conversations, update tags if does not exist for the user | |
[ADMIN_IDS_WHICH_USE_INTERCOM].each do |admins| | |
intercom.conversations.find_all(type: 'admin', id: admins).each do |intercom_conversation| | |
c = intercom.conversations.find(id: intercom_conversation.id) | |
user = intercom.users.find(id: c.user.id) | |
c.tags.each do |tags| | |
unless UserTag.where(tag_name: tags.name).where(user_id: user.user_id).count > 0 | |
# Choose properties to sync | |
UserTag.create!(user_id: user.user_id, user_email: user.email, tag_id: tags.id, tag_name: tags.name, tag_type: 'conversation', monthly_spend: user.custom_attributes[:monthly_spend]) | |
end | |
# Sleep to prevent rate limiting | |
sleep 0.2 | |
end | |
sleep 1 | |
end | |
end | |
end | |
task :all => [:tag_list, :user_tags, :conversation_tags] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment