Scan-and-set

From Request Tracker Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
#!/usr/bin/perl -w
 #
 # Sample script to scan RT ticket attachments for a 4 digit number
 # following the string "important number" and add the value to
 # a custom field called "CustomField"
 #
 # It's an example of scanning attachchments and setting a custom field
 # from an external Perl script
 #
 # author    rmeden@yahoo.com
 #
 use strict;
 
 use lib ("/path/to/rt/lib");  # Change this to your RT lib path!
 use RT::Interface::CLI qw(CleanEnv GetCurrentUser GetMessageContent loc);
 use RT::Tickets;
 
 select STDERR; $|=1;
 select STDOUT; $|=1;
 
 # Clean our environment
 CleanEnv();
 
 # Load the RT configuration
 RT::LoadConfig();
 RT::Init();
 
 
 my $tickets = new RT::Tickets($RT::SystemUser); # Used to store Ticket search results
 $tickets->LimitStatus(VALUE => 'new');
 $tickets->LimitStatus(VALUE => 'open');
 $tickets->LimitCustomField(CUSTOMFIELD => 'CustomField',
                            OPERATOR    => "is",
                            VALUE       => "NULL");
 
 # Loop through tickets
 while (my $Ticket = $tickets->Next) {
     my $NUM="";
 
     #
     # Scan attachments and keep latest value
     #
     my $txns = $Ticket->Transactions;
     while (my $txn = $txns->Next ) {
        my $attachments = RT::Attachments->new($txn->CurrentUser);
        $attachments->Limit( FIELD => 'TransactionID', VALUE => $txn->id );
        $attachments->OrderBy( FIELD => 'Id', ORDER => 'ASC' );
        while ( my $a = $attachments->Next ) {
               next unless $a->ContentEncoding eq "none";
               $NUM=$1 if $a->Content =~ /important number (\d{4})/m;
           }
       }
 
      next unless $NUM; # nothing found?
 
      printf "Setting Ticket %d Important Number %d\n",$Ticket->id,$NUM;
      $Ticket->AddCustomFieldValue(Field=>"CustomField",Value=>$NUM,RecordTransaction=>0);
  } # Ticket loop
 
 $RT::Handle->Disconnect();
 exit;