This isn’t really a WordPress specific question. However, I recently wrote a function for this (and blocking other user agents). Perhaps you could use it, or some of it?:
function is_a_bot(){
$is_bot = false;
$user_agents = array( 'GTmetrix', 'Googlebot', 'Bingbot', 'BingPreview', 'msnbot', 'slurp', 'Ask Jeeves/Teoma', 'Baidu', 'DuckDuckBot', 'AOLBuild' );
$user_agent = $_SERVER['HTTP_USER_AGENT'];
foreach ( $user_agents as $agent ){
if ( strpos( $user_agent, $agent) ){
$is_bot = true;
}
}
return $is_bot;
}
Simply add/remove the bots that you want/don’t want from the array $user_agents
and use in the following way:
if ( ! is_a_bot() ){
// Do something if it's not a bot (eg. display ad code, template part or run your function here...)
}