Validate Agent's Response Character Count Script

This script validates whether an agent's response for the Twitter channel is less than or equal to 280 characters.

You must add this script as a validation rule to the Message object (child of Service Request object). You must also add a validation message that's displayed to the agents when their Twitter response is greater than 280 characters.

Use the following code as an example:

if(ChannelId == null){ 
    return true; 
}
def channelVO = newView('ChannelVO')
channelVO.appendViewCriteria("ChannelId = '${ChannelId}'")
channelVO.executeQuery()
def networkType = null
if(channelVO.hasNext())
{ 
    def channelRow = channelVO.next(); 
    networkType = channelRow.getAttribute("NetworkTypeCd") 
}
if(networkType == null || networkType != 'TWITTER') { 
    return true
}
String MessageContent = MessageContent.toString()
Long channelId = ChannelId
Long charCount = MessageContent.length();
String pattern = ~/(http|https):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*/
if(null == MessageContent)
return true;
String message = MessageContent.toString()
String[] tokens = message.split(" ")
for(int i=0;i<tokens.size();i++){
    if(tokens[i].matches(pattern )) {
        //this is an url
        Long urlLength = tokens[i].length()
        if(urlLength > 23)   { 
            charCount = charCount - (urlLength -23) 
        }
        else    { 
            charCount = charCount + (23- urlLength) 
        }
    }
}
if(charCount > 280)
    return false
else
    return true