Created
May 6, 2013 10:53
-
-
Save benilovj/5524472 to your computer and use it in GitHub Desktop.
This script uses the Zendesk REST API v2 to update triggers.
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
require 'yaml' | |
require 'json' | |
require 'httparty' | |
class Zendesk | |
include HTTParty | |
base_uri "https://zendeskinstance.zendesk.com/api/v2" | |
headers 'Content-Type' => "application/json" | |
# debug_output $stderr | |
def initialize | |
@config = load_config | |
end | |
def find_correct_triggers | |
all_triggers = [] | |
next_url = "/triggers.json" | |
until next_url.nil? | |
page = fetch(next_url) | |
all_triggers += page["triggers"] | |
next_url = page["next_page"] | |
end | |
subsection_triggers = all_triggers.select { |t| t["title"].start_with?("Sub-section: ") } | |
end | |
def save_trigger(trigger) | |
# new_trigger = { id: trigger["id"], conditions: trigger["conditions"] } | |
body = { trigger: trigger }.to_json | |
options_with_body = options.merge(body: body) | |
self.class.put("/triggers/#{trigger["id"]}.json", options_with_body) | |
end | |
protected | |
def load_config | |
YAML.load_file('config/zendesk.yml')['production'] | |
end | |
def options | |
{ basic_auth: { username: @config["username"], password: @config["password"] } } | |
end | |
def fetch(url) | |
url.gsub!("https://govuk.zendesk.com/api/v2") if url.start_with?("http") | |
JSON.parse(self.class.get(url, options).body) | |
end | |
end | |
class Trigger | |
PREFIX = "url: https://www.gov.uk" | |
def initialize(zendesk, trigger) | |
@zendesk = zendesk | |
@trigger = trigger | |
end | |
def update | |
if update_needed? | |
puts "Updating #{@trigger["title"]}" | |
@trigger["conditions"]["any"].each do |condition| | |
# puts "[#{condition["value"]}] => [#{new_string(condition["value"])}]" | |
condition["value"] = new_string(condition["value"]) | |
end | |
@zendesk.save_trigger(@trigger) | |
else | |
puts "Ignoring #{@trigger["title"]}" | |
end | |
end | |
protected | |
def new_string(old_string) | |
new_str = PREFIX.clone | |
new_str += "/" unless old_string.start_with?("/") | |
new_str + old_string | |
end | |
def update_needed? | |
@trigger["conditions"]["any"].none? {|condition| condition["value"].start_with?(PREFIX) } | |
end | |
end | |
zd = Zendesk.new | |
section_subsection_triggers = zd.find_correct_triggers | |
section_subsection_triggers.each do |trigger| | |
Trigger.new(zd, trigger).update | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment