---
# System prepended metadata

title: Page traitement - Meteo monde / Skill Alexa

---

# Page traitement - Meteo monde / Skill Alexa
```
<?php
setlocale(LC_ALL, 'fra', 'fr_FR');
/*Varaibles*/
$all_mois = [
    '01' => "Janvier",
    '02' => "Février",
    '03' => "Mars",
    '04' => "Avril",
    '05' => "Mai",
    '06' => "Juin",
    '07' => "Juillet",
    '08' => "Août",
    '09' => "Septembre",
    '10' => "Octobre",
    '11' => "Novembre",
    '12' => "Décembre",
  ];
  
  $all_jours = [
      1 => "Lundi",
      2 => "Mardi",
      3 => "Mercredi",
      4 => "Jeudi",
      5 => "Vendredi",
      6 => "Samedi",
      7 => "Dimanche",
    ];

if (isset($_POST['ville']) && (isset($_POST['mode']) && $_POST['mode'] == 'live')) {
    $ville = $_POST['ville'];
    $json_source_jour = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q='.str_to_noaccent($ville).'&units=metric&appid=440f016b31b5d48aedb7b0c26ea62112');
    $data = json_decode($json_source_jour);

    
    $meteo_id = $data->weather[0]->id;
    settype($meteo_id, "string");
    $meteo_id_p = $meteo_id[0];
    $temps = get_temps_current($meteo_id, $meteo_id_p);


    echo 'À '.ucfirst($ville).', en ce moment il fait '.round($data->main->temp).'°C et '.$temps.'.';

} else if(isset($_POST['ville']) && (isset($_POST['mode']) && $_POST['mode'] == 'previsions')) {
    $ville = $_POST['ville'];
    $json_ville = file_get_contents('https://api.opencagedata.com/geocode/v1/json?q='.str_to_noaccent($ville).'&key=4ab148eaf30d4dbeb0bcd409a9d65241');
    $data_ville = json_decode($json_ville);


    $json_source_jour = file_get_contents('http://api.openweathermap.org/data/2.5/onecall?lat='.$data_ville->results[0]->geometry->lat.'&lon='.$data_ville->results[0]->geometry->lng.'&exclude=hourly&units=metric&appid=440f016b31b5d48aedb7b0c26ea62112');
    $data = json_decode($json_source_jour);


    $phrase = 'Voici les prévisions des 7 prochains jours pour la ville de '.ucfirst($ville).'. ';
    $pre_temps = '';
    $has_interval = false;
    foreach ($data->daily as $nb => $day) {
        //Date
        if ($nb == 0) {
            $date = get_date($nb, $day->dt, $all_mois, $all_jours);
        }

        //Météo
        $meteo_id = $day->weather[0]->id;
        settype($meteo_id, "string");
        $meteo_id_p = $meteo_id[0];
        $temps = get_temps_prevision($meteo_id, $meteo_id_p);

        //Température
        $temp_day = round($day->temp->day);
        $temp_night = round($day->temp->night);
        $temp_max = round($day->temp->max);
        $temp_min = round($day->temp->min);

        if ($temps == $pre_temps) {
            if ($pre_temp_max < $temp_max) {
                $pre_temp_max = $temp_max;
            }
            if ($pre_temp_min > $temp_min) {
                $pre_temp_min = $temp_min;
            }
            $has_interval = true;
        } else {
            if ($nb != 0) {
                if ($has_interval) {
                    $phrase_temp = get_temp_sentence($pre_temp_min, $pre_temp_max);
                    $phrase .= $pre_prefix.' '.$pre_date.' '.$pre_suffix.' '.$date.' '.$pre_temps.'. '.$phrase_temp;
                    $has_interval = false;
                } else {
                    $phrase_temp = get_temp_sentence_v2($pre_temp_min, $pre_temp_max, $pre_temp_day, $pre_temp_night);
                    $phrase .= $date.' '.$pre_temps.'. '.$phrase_temp;
                }
                $date = get_date($nb, $day->dt, $all_mois, $all_jours);
            }
            $pre_prefix = ($nb < 4 ? 'De' : 'Du');
            $pre_date = $date;
            $pre_temps = $temps;
            $pre_temp_max = $temp_max;
            $pre_temp_min = $temp_min;
        }
        
        //Date
        $pre_suffix = ($nb < 4 ? 'à' : 'au');
        $date = get_date($nb, $day->dt, $all_mois, $all_jours);
        $pre_temp_day = $temp_day;
        $pre_temp_night = $temp_night;
    }
    if ($has_interval) {
        $phrase_temp = get_temp_sentence($pre_temp_min, $pre_temp_max);
        $phrase .= $pre_prefix.' '.$pre_date.' '.$pre_suffix.' '.$date.' '.$pre_temps.'. '.$phrase_temp;
    } else {
        $phrase_temp = get_temp_sentence_v2($pre_temp_min, $pre_temp_max, $pre_temp_day, $pre_temp_night);
        $phrase .= $date.' '.$pre_temps.'. '.$phrase_temp;
    }
    echo $phrase;

} else if (isset($_POST['ville']) && isset($_POST['moment']) && (isset($_POST['mode']) && $_POST['mode'] == 'previsions_moment')) {
    $ville = $_POST['ville'];
    $json_ville = file_get_contents('https://api.opencagedata.com/geocode/v1/json?q='.str_to_noaccent($ville).'&key=4ab148eaf30d4dbeb0bcd409a9d65241');
    $data_ville = json_decode($json_ville);
    

    $json_source_jour = file_get_contents('http://api.openweathermap.org/data/2.5/onecall?lat='.$data_ville->results[0]->geometry->lat.'&lon='.$data_ville->results[0]->geometry->lng.'&exclude=hourly&units=metric&appid=440f016b31b5d48aedb7b0c26ea62112');
    $data = json_decode($json_source_jour);


    $moment = strtolower($_POST['moment']);
    switch($moment){
        case 'demain':
            $nb = 1;
            break;
        case 'après demain':
        case 'apres demain':
        case 'après-demain':
        case 'apres-demain':
            $nb = 2;
            break;
        default:
            $nb = 0;
            break;
    }

    //Météo
    $meteo_id = $data->daily[$nb]->weather[0]->id;
    settype($meteo_id, "string");
    $meteo_id_p = $meteo_id[0];
    $temps = get_temps_prevision($meteo_id, $meteo_id_p);
    $temp_day = round($data->daily[$nb]->temp->day);
    $temp_night = round($data->daily[$nb]->temp->night);
    $temp_max = round($data->daily[$nb]->temp->max);
    $temp_min = round($data->daily[$nb]->temp->min);

    echo ucfirst($moment).' à '.ucfirst($ville).', '.$temps.'. La température en journée sera de '.$temp_day.'°, avec une maximale de '.$temp_max.'° et une minimale de '.$temp_min.'°C. Pendant la nuit il fera aux alentours de '.$temp_night.'°C.';


} else {
    echo 'pas de réponse';
}


/*FUNCTION*/
  function str_to_noaccent($str)
  {
      $url = $str;
      $url = preg_replace('#Ç#', 'C', $url);
      $url = preg_replace('#ç#', 'c', $url);
      $url = preg_replace('#è|é|ê|ë#', 'e', $url);
      $url = preg_replace('#È|É|Ê|Ë#', 'E', $url);
      $url = preg_replace('#à|á|â|ã|ä|å#', 'a', $url);
      $url = preg_replace('#@|À|Á|Â|Ã|Ä|Å#', 'A', $url);
      $url = preg_replace('#ì|í|î|ï#', 'i', $url);
      $url = preg_replace('#Ì|Í|Î|Ï#', 'I', $url);
      $url = preg_replace('#ð|ò|ó|ô|õ|ö#', 'o', $url);
      $url = preg_replace('#Ò|Ó|Ô|Õ|Ö#', 'O', $url);
      $url = preg_replace('#ù|ú|û|ü#', 'u', $url);
      $url = preg_replace('#Ù|Ú|Û|Ü#', 'U', $url);
      $url = preg_replace('#ý|ÿ#', 'y', $url);
      $url = preg_replace('#Ý#', 'Y', $url);
      $url = str_replace('_', ' ', $url);
      $url = str_replace(' ', '%20', $url);
      return ($url);
  }
  
  function get_temps_current($meteo_id, $meteo_id_p)
  {
      $meteo_temps = '';
      switch (true) {
          case ($meteo_id_p == '2'):
              $meteo_temps = 'le temps est orageux';
              break;
          case ($meteo_id_p == '3'):
              $meteo_temps = 'il y a une légère bruine';
              break;
          case ($meteo_id_p == '5'):
              $meteo_temps = 'le temps est pluvieux';
              break;
          case ($meteo_id_p == '6'):
              $meteo_temps = 'de la neige tombe';
              break;
          case ($meteo_id_p == '7'):
              $meteo_temps = 'il y a du brouillard';
              break;
          case ($meteo_id_p == '8'):
              switch (true) {
                  case ($meteo_id == '800'):
                      $meteo_temps = 'le temps est ensoleillé';
                      break;
                  case ($meteo_id == '801'):
                      $meteo_temps = 'le temps est nuageux';
                      break;
                  case ($meteo_id >= '802' && $meteo_id <= '804'):
                      $meteo_temps = 'le temps est couvert';
                      break;
              }
              break;
      }
      return $meteo_temps;
  }
  
  function get_temps_prevision($meteo_id, $meteo_id_p)
  {
      $meteo_temps = '';
      switch (true) {
          case ($meteo_id_p == '2'):
              $meteo_temps = 'il y aura majoritairement de l\'orage';
              break;
          case ($meteo_id_p == '3'):
              $meteo_temps = 'une bruine sera presente dans la journée';
              break;
          case ($meteo_id_p == '5'):
              $meteo_temps = 'le temps sera pluvieux';
              break;
          case ($meteo_id_p == '6'):
              $meteo_temps = 'de la neige tombera';
              break;
          case ($meteo_id_p == '7'):
              $meteo_temps = 'du brouillard sera présent';
              break;
          case ($meteo_id_p == '8'):
              switch (true) {
                  case ($meteo_id == '800'):
                      $meteo_temps = 'le temps sera ensoleillé';
                      break;
                  case ($meteo_id == '801'):
                      $meteo_temps = 'le temps sera nuageux';
                      break;
                  case ($meteo_id >= '802' && $meteo_id <= '804'):
                      $meteo_temps = 'le temps sera couvert';
                      break;
              }
              break;
      }
      return $meteo_temps;
  }
  
  function get_date($nb, $time, $all_mois, $all_jours)
  {
      switch($nb){
          case 0:
              $date = 'Aujourd\'hui';
              break;
          case 1:
              $date = 'Demain';
              break;
          case 2:
              $date = 'Après-demain';
              break;
          default:
              $jour = $all_jours[strftime("%u", $time)];
              $num = strftime("%e", $time);
              $mois = $all_mois[strftime("%m", $time)];
              $date = $jour.' '.$num.' '.$mois;
              break;
      }
      return $date;
  }
  
  function get_temp_sentence($temp_min, $temp_max)
  {
      $phrase_temperatures = [
          0 => 'Pour les températures la minimale sera de '.$temp_min.'° et la maximale de '.$temp_max.'°C. ',
          1 => 'Durant ces jours les températures se trouveront entre '.$temp_min.'° et '.$temp_max.'°C. ',
          2 => 'La température minimale sera de '.$temp_min.'° et la maximale de '.$temp_max.'°C. ',
      ];
      return $phrase_temperatures[rand(0,2)];
  }
  
  function get_temp_sentence_v2($temp_min, $temp_max, $temp_day, $temp_night)
  {
      $phrase_temperatures = [
          0 => 'Pendant la journée la température moyenne sera de '.$temp_day.'°C. ',
          1 => 'La température durant la journée sera de '.$temp_day.'° et durant la nuit de '.$temp_night.'°C. ',
          2 => 'La température minimale sera de '.$temp_min.'° et la maximale de '.$temp_max.'°C. ',
      ];
      return $phrase_temperatures[rand(0,2)];
  }
```

---

# index.js - Meteo monde / Skill Alexa
```
const Alexa = require('ask-sdk-core');
const http = require('http');
const querystring = require('querystring');
var fs = require('fs');

//Météo du moment
function meteo_ville(ville) {
    return new Promise(((resolve, reject) => {
        
    var post_data = querystring.stringify({
      'ville' : ville,
      'mode' : 'live',
    });
  
    var options = {
        host: '195.83.128.21',
        port: 80,
        //path: '/~dev1905/API/alexa.php?ville='+ville,
        path: '/~dev1905/API/alexa.php',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)
        }
    };
   
    const request = http.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';
      console.log(response);

      response.on('data', (chunk) => {
        returnData += chunk;
      });

      response.on('end', () => {
        resolve(returnData);
      });

      response.on('error', (error) => {
        reject(error);
      });
    });
    request.write(post_data);
    request.end();
  }));
}

//Prévision météo
function prevision_meteo_ville(ville) {
    return new Promise(((resolve, reject) => {
        
    var post_data = querystring.stringify({
      'ville' : ville,
      'mode' : 'previsions',
    });
  
    var options = {
        host: '195.83.128.21',
        port: 80,
        //path: '/~dev1905/API/alexa.php?ville='+ville,
        path: '/~dev1905/API/alexa.php',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)
        }
    };
   
    const request = http.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';
      console.log(response);

      response.on('data', (chunk) => {
        returnData += chunk;
      });

      response.on('end', () => {
        resolve(returnData);
      });

      response.on('error', (error) => {
        reject(error);
      });
    });
    request.write(post_data);
    request.end();
  }));
}

//Prévision moment météo
function prevision_moment_meteo_ville(ville, moment) {
    return new Promise(((resolve, reject) => {
        
    var post_data = querystring.stringify({
      'ville' : ville,
      'moment' : moment,
      'mode' : 'previsions_moment',
    });
  
    var options = {
        host: '195.83.128.21',
        port: 80,
        path: '/~dev1905/API/alexa.php',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)
        }
    };
   
    const request = http.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';
      console.log(response);

      response.on('data', (chunk) => {
        returnData += chunk;
      });

      response.on('end', () => {
        resolve(returnData);
      });

      response.on('error', (error) => {
        reject(error);
      });
    });
    request.write(post_data);
    request.end();
  }));
}

//Démarrage 
const monpremiermessage = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
  },
  handle(handlerInput) {
    const speechText = 'Bonjour, je vous écoute';

    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .withSimpleCard('Hello World', speechText)
      .getResponse();
  }
};

//Météo du moment
const meteovillenow = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'meteo_ville';
    },
    async handle(handlerInput) {
        var ville = Alexa.getSlotValue(handlerInput.requestEnvelope, 'ville');
        //ville = ville.replace(' ','_');
        const lareponse = await meteo_ville(ville);
        return handlerInput.responseBuilder
          .speak(lareponse)
          .reprompt(lareponse)
          .withSimpleCard('Hello World', lareponse)
          .getResponse();
    }
};

//Prévision météo
const previsionmeteoville = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'prevision_meteo_ville';
    },
    async handle(handlerInput) {
        var ville = Alexa.getSlotValue(handlerInput.requestEnvelope, 'ville');
        //ville = ville.replace(' ','_');
        const lareponse = await prevision_meteo_ville(ville);
        return handlerInput.responseBuilder
          .speak(lareponse)
          .reprompt(lareponse)
          .withSimpleCard('Hello World', lareponse)
          .getResponse();
    }
};

//Prévision moment météo
const previsiontimemeteoville = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'prevision_time_meteo_ville';
    },
    async handle(handlerInput) {
        var ville = Alexa.getSlotValue(handlerInput.requestEnvelope, 'ville');
        var moment = Alexa.getSlotValue(handlerInput.requestEnvelope, 'moment');
        const lareponse = await prevision_moment_meteo_ville(ville, moment);
        return handlerInput.responseBuilder
          .speak(lareponse)
          .reprompt(lareponse)
          .withSimpleCard('Hello World', lareponse)
          .getResponse();
    }
};

//Quitter le Skill
const CancelAndStopIntentHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'IntentRequest'
        && Alexa.getIntentName(handlerInput.requestEnvelope) === 'quitter_meteo';
  },
  handle(handlerInput) {
    const speechText = 'Ok, au revoir';

    return handlerInput.responseBuilder
      .speak(speechText)
      .withSimpleCard('Hello World', speechText)
      .withShouldEndSession(true)
      .getResponse();
  }
};

exports.handler = Alexa.SkillBuilders.custom().addRequestHandlers(  monpremiermessage, meteovillenow, previsionmeteoville, previsiontimemeteoville, CancelAndStopIntentHandler ).lambda();
```