site logo

Example: User CSV import creation (Ruby)


Example: user creation (Ruby)  

#  $Id: user-csv-import.rb,v 1.1 2008/01/16 11:30:18 d Exp $

#  Mojo Helpdesk API example

#  Description
#  -----------
#    This script creates Mojo Helpdesk users from a CSV file. If a user
#    already exists it is skipped. The unique key is the user email address.
#   
#
require 'csv'
require 'soap/wsdlDriver'
require 'open-uri'

########################################
# Your helpdesk URL
# URL = "http://supportxyz.mojohelpdeskcom
#
# Your key (can be found in your helpdesk user profile)
# MY_KEY = "asdfasdf134341e2642e56fa3b72bc5c2a0"
#
# CSV file containing the users to import
# CSV_FILE = 'user-csv-import.csv'
#
#
# Replace the info below with your own:
#
###
URL = "http://yourhelpdesk.mojohelpdesk.com"
MY_KEY = "dsaf13r132r2bbc64378cce01bacf1d3a4b59b9"
###
# In our example the csv file has the following structure:
#
# first / last / screenname / email / company / password
#"daniel","smith","ds","ds@mail.com","newco",'password123'
#"daniel","smith","ds","d2s@mail.com","newco",'password123'
#"daniel","smith","ds","ds3@mail.com","newco",'password123'
#"daniel","smith","ds","d23s@mail.com","newco",'password123'
#
CSV_FILE = 'user-csv-import.csv'
#
#########################################
# Connection to the service
begin
  rpc = SOAP::WSDLDriverFactory.new("#{URL}/backend/service.wsdl").create_rpc_driver
rescue
  printf "Could not connect to server.wsdl or an error occured (%s). Check your URL and try again.\n", $!
  exit(-1)
end


total_in_file = 0
user_created = 0
 
CSV::Reader.parse(File.open(CSV_FILE, 'rb')) do |row|   
  total_in_file += 1
  params = {
    ###
    # setup of user params
    # change it based on your csv file structure
    ##
    :first_name   => row[0],
    :last_name    => row[1],
    :display_name => row[2],
    :email        => row[3],
    :company_id   => row[4],
    :password     => row[5]
  }
  printf "Processing record #%d: %s\n", total_in_file, row[3]

  # check if use exists
  result = rpc.GetUserByEmail("#{MY_KEY}", params[:email])
  # puts result.user.inspect
  if result.user != nil
    printf "User already exists, skipping/__metadot__.\n"
    next
  end
 
  result = rpc.CreateUser("#{MY_KEY}", params)

  if result['successful'] != true
    printf "Error: %s\n", result['error_message']
    next # go to next record to record
  end
 
  user_created += 1
  u = result.user
  printf "User created, id: %d, email %s\n", u['id'], u['email']
 
end

printf "\n\nDone. Records in file: %d, created: %d\n", total_in_file, user_created

exit 0