iChat script to automate login and logout

I use my iChat all day long at work to communicate with co-workers, friends, and vendors. Sometimes at the end of the day I will forget to log out of iChat only to return the next morning finding someone tried to reach me via iChat. Same thing when I do remember to log out at the end of the day, I forget to login in the morning. I created the following script to solve these two problems.

When the script executes it first checks to see if iChat is running, then checks the idle time of the computer, and the time of day, to determine whether to log into or out of iChat.

  • If its morning, the script will detect when I arrive and start using the computer and will log into iChat for me. If there is no activity the script continue to check for ninety minutes, then timeout concluding I’m not going to show up for work that day.

  • If it is afternoon the script does just the opposite. It patiently waits (up to four hours) for me to quit using the computer and go home, then it will log me out of iChat.

I use iCal to execute the script. iCal launches the script twice a day, once in the morning (45 minutes before I usually arrive) and in the evening (15 minutes after I typically leave for the day). For some reason running the script in iCal will conveniently not launch iChat when the script executes. So when I plan to be out of the office for a long period of time, I will quit the iChat application to not have the script accidently log into iChat since I routinely log into my computer remotely.

Enjoy -

tell application "System Events"
	if exists process "iChat" then -- See if iChat is running first, if not then we exit
		if the time of (current date) is less than 43200 then -- if it's morning (before noon), we want to log IN (and not out)
			repeat 90 times -- we test every minute to see if there is any activity in case I'm late for work
				set idleTime to (do shell script "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle,\"\";last}'") as number
				if idleTime < 180 then
					tell application "iChat"
						set the status to "Log into AIM"
					end tell
					exit repeat
				else
					delay 60 -- no activity yet, wait for another 60 seconds
				end if
			end repeat
		else -- otherwise it must be afternoon
			repeat 50 times -- repeat every five minutes to see if I've left work yet
				set idleTime to (do shell script "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle,\"\";last}'") as number
				if idleTime > 30 * 60 then
					tell application "iChat"
						set the status to offline
					end tell
					exit repeat
				else
					delay 5 * 60 -- I must still be using the computer, wait for another five
				end if
			end repeat
		end if
	end if
end tell