Skip to content

Instantly share code, notes, and snippets.

@lyoshenka
Last active December 25, 2015 12:59
Show Gist options
  • Select an option

  • Save lyoshenka/6980849 to your computer and use it in GitHub Desktop.

Select an option

Save lyoshenka/6980849 to your computer and use it in GitHub Desktop.
Run this in cron every 5 minutes. Sends a message to HipChat when you start and stop your Toggl timer.
#!/usr/bin/env php
<?php
const
TOGGL_API_KEY = '',
HIPCHAT_API_KEY = '',
HIPCHAT_ROOM_ID = '',
HIPCHAT_FROM = 'Toggl',
HIPCHAT_COLOR = 'yellow', // One of "yellow", "red", "green", "purple", "gray", or "random".
START_MSG = 'NAME is doing work, yo',
STOP_MSG = 'NAME is done for the day';
$now = time();
if (!TOGGL_API_KEY)
{
echo "Toggl api key required.\n";
return 1;
}
if (!HIPCHAT_API_KEY)
{
echo "HipChat api key required.\n";
return 1;
}
if (!HIPCHAT_ROOM_ID)
{
echo "Room ID required. Get your room id here: https://www.hipchat.com/rooms/ids\n";
return 1;
}
$data = ['lastRun' => 0, 'currGuid' => null, 'lastGuid' => null];
$dataFile = '/tmp/toggl_hipchat.json';
if (is_readable($dataFile))
{
$data = json_decode(file_get_contents($dataFile), true);
if ($data['lastRun'] > $now - 60)
{
echo "Last run less than 60 seconds ago, quitting.\n";
return;
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.toggl.com/api/v8/time_entries');
curl_setopt($ch, CURLOPT_USERPWD, TOGGL_API_KEY.':api_token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$togglData = curl_exec($ch);
curl_close($ch);
$timeEntries = json_decode($togglData, true);
if ($timeEntries === null)
{
echo "Toggl API call failed\n";
return 1;
}
if (!count($timeEntries))
{
echo "no time entries\n";
return;
}
$last = end($timeEntries);
$message = null;
if (isset($last['stop']) && $last['guid'] != $data['lastGuid'])
{
$message = STOP_MSG;
$data['lastGuid'] = $last['guid'];
}
elseif ($last['guid'] != $data['currGuid'])
{
$message = START_MSG;
}
if ($message)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'https://api.hipchat.com/v1/rooms/message');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'auth_token' => HIPCHAT_API_KEY,
'format' => 'json',
'from' => HIPCHAT_FROM,
'room_id' => HIPCHAT_ROOM_ID,
'color' => HIPCHAT_COLOR,
'message' => utf8_encode($message),
'notify' => (int)1
]);
$hipchatData = curl_exec($ch);
curl_close($ch);
$response = json_decode($hipchatData, true);
if (!$response)
{
echo "HipChat API call failed\n";
return 1;
}
echo "Status updated.\n";
}
$data['currGuid'] = $last['guid'];
$data['lastRun'] = $now;
file_put_contents($dataFile, json_encode($data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment