AI Engine User Location & Weather

Here are two functions you can add to your chatbots that will provide the user’s current location (city, region, country) as well as the current weather where they live.

Disclaimer: These functions use third party services. The user’s IP will be provided to proxycheck.io (free access under 1000 lookups per day) when retrieving their location. The weather service (free access for non-commercial use) first looks up their location using proxycheck.io in order to get the correct weather. The weather API does not receive the user’s IP. Both are free to use and require no API keys.

Installation

Add this as a “Global” snippet in Code Engine in order to use the two function calls we will be adding next:

<?php

function get_proxycheck_data($ip) {
    $api_key = ''; // place ProxyCheck.io API key here (optional)
    $transient_key = 'ai_engine_location_' . md5($ip);
    
    $cached_result = get_transient($transient_key);
    if ($cached_result !== false) {
        return $cached_result;
    }

    $url = $api_key ? 'https://proxycheck.io/v2/'.$ip.'?key='.$api_key.'&asn=1' : 'https://proxycheck.io/v2/'.$ip.'?&asn=1';
    $response = wp_remote_get($url);
    
    if (is_wp_error($response)) {
        return array(
            'json' => array(
                'city' => '',
                'region' => '',
                'country' => '',
                'latitude' => '',
                'longitude' => ''
            ),
            'string' => 'Location service unavailable'
        );
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (isset($data['status']) && ($data['status'] == 'ok' || $data['status'] == 'warning')) {
        if (isset($data[$ip])) {
            $location_data = $data[$ip];
            
            $location_json = array(
                'city' => !empty($location_data['city']) ? $location_data['city'] : '',
                'region' => !empty($location_data['region']) ? $location_data['region'] : '',
                'country' => !empty($location_data['country']) ? $location_data['country'] : '',
                'latitude' => !empty($location_data['latitude']) ? $location_data['latitude'] : '',
                'longitude' => !empty($location_data['longitude']) ? $location_data['longitude'] : ''
            );
            
            $location_parts = array_filter(array(
                $location_json['city'],
                $location_json['region'], 
                $location_json['country']
            ));
            
            $location_string = !empty($location_parts) ? implode(', ', $location_parts) : 'Unknown location';
            
            $cache_data = array(
                'json' => $location_json,
                'string' => $location_string,
                'timestamp' => time()
            );
            
            // Cache for 90 days
            set_transient($transient_key, $cache_data, 90 * DAY_IN_SECONDS);
            
            return $cache_data;
        }
    }

    $default_data = array(
        'json' => array(
            'city' => '',
            'region' => '',
            'country' => '',
            'latitude' => '',
            'longitude' => ''
        ),
        'string' => 'User location not found',
        'timestamp' => time()
    );
    
    set_transient($transient_key, $default_data, HOUR_IN_SECONDS);
    
    return $default_data;
}

Add this as a “Callable” type snippet in Code Engine if you want the ability for your chatbot to get the user’s current city:

function get_user_location() {
    global $mwai_core;
    if (!$mwai_core) {
        return "Location service unavailable";
    }
    
    $ip = $mwai_core->get_ip_address();
    if (!$ip) {
        return "Unable to determine user IP";
    }
    
    $location_data = get_proxycheck_data($ip);
    return "The user is in " . $location_data['string'];
}

Add this as a “Callable” type snippet in Code Engine if you want the ability for your chatbot to get the user’s current city and weather information:

function get_user_weather() {
    global $mwai_core;
    if (!$mwai_core) {
        return "Weather service unavailable";
    }
    
    $ip = $mwai_core->get_ip_address();
    if (!$ip) {
        return "Unable to determine user location";
    }
    
    // Get location data first
    $location_data = get_proxycheck_data($ip);
    $lat = $location_data['json']['latitude'];
    $long = $location_data['json']['longitude'];
    
    if (empty($lat) || empty($long)) {
        return 'Weather data unavailable - location unknown';
    }
    
    $weather_key = 'ai_engine_weather_' . md5($lat . '_' . $long);
    
    // Check weather cache
    $cached_weather = get_transient($weather_key);
    if ($cached_weather !== false) {
        return "The current weather for the user is " . $cached_weather . " which is in " . $location_data['string'];
    }
    
    // Make weather API request
    $url = "https://api.open-meteo.com/v1/forecast?latitude={$lat}&longitude={$long}&current=temperature_2m,wind_speed_10m";
    $response = wp_remote_get($url);
    
    if (is_wp_error($response)) {
        return 'Weather service unavailable';
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (isset($data['current'])) {
        $weather_string = sprintf(
            'Temperature: %.1f°C, Wind Speed: %.1f km/h',
            $data['current']['temperature_2m'],
            $data['current']['wind_speed_10m']
        );
        // Cache for 1 hour
        set_transient($weather_key, $weather_string, HOUR_IN_SECONDS);
        
        return "The current weather for the user is " . $weather_string . " which is in " . $location_data['string'];
    }
    
    return 'Weather data unavailable';
}

You can then add these as functions to your chatbots within the AI Engine chatbot settings.

Add to their instructions like this:

Begin a conversation by getting the weather using get_user_weather function, then synthesize the data into your greeting.

# Your Tools
## Weather
You can get the weather in the user's area by using "get_user_weather" function.
## User Location
You can get the user's current location (city, region, country) by using the "get_user_location" function.

Let’s enhance your business! I can help you develop custom AI engine extensions or broader AI strategies.

Contact me.

Leave a Reply

Your email address will not be published. Required fields are marked *