[RÉFÉRENTIEL] - Les scripts

referentiel
scripts

#1

Référentiel des scripts

Ce topic est dédié au référencement des scripts partagé par la communauté sur le forum.
Cette liste n’est bien entendu pas exhaustive et elle sera mise a jour le plus régulièrement possible.
Certains scripts sont déjà présent sur la page de configuration des modules, ils ne seront donc pas repris ici.

Notification


Notification Telegram

gladys.modules.telegram.notify({text:“Lampe Salon allumée”},{id:1});

Notification aléatoire Telegram
let message = ['Bienvenu à la maison monsieur :)',
               'Content de vous revoir monsieur ! ',
               'Je vous attendais :)',
               'Je suis heureuse de vous retrouvez monsieur !'];

var min = 0;
var max = 4;
var index;

function getRandom(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  index = Math.floor(Math.random() * (max - min)) + min;
  return index;
}

function getText(){
    getRandom(min, max);
    return message[index];
}

gladys.modules.telegram.notify({text:getText()},{id:1});
Notification Pushbullet

gladys.modules.pushbullet.notify({text:‘Lampe Salon allumée’},{id:1});

Notification Météo
var options1 = {
    latitude: XX.XX,
    longitude: X.XX
};

gladys.weather.get(options1).then((result) => {

var temp = result.temperature;
var wea = result.weather;
var humi = 100 * result.humidity;
var wind = result.windSpeed;

switch (wea){
    case "snow":
        wea = "Il neige.";
        break;
    case "rain":
        wea = "Il pleut.";
        break;
    case "clear":
        wea = "Le ciel est dégagé.";
        break;
    case "cloud":
        wea = "Le ciel est couvert.";
        break;
    case "fog":
        wea = "Il y a du brouillard";
        break;
    case "sleet":
        wea = "Il grêle.";
        break;
    case "wind":
        wea = "Le mistral est de sortie.";
        break;
    default:
        wea = 'Le ciel est :'+ wea+'.';
    }

var text = ‘Il fait ’ + temp+ ’ degrés à Salon. \n’+ wea+’ \nVent : ‘+ wind+’ Km/h. \nHumidité :’+humi+’%.’;
gladys.modules.telegram.notify({text:text},{id:1}); });

Utilisateur


Connaitre la dernière position d'un utilisateur
// Get the last location of the user
// Location can be tracked with OwnTracks (iOS/Android) or Tasker (Android)
gladys.location.getUser({ id: 1})
    .then((location) => {
        console.log(`User 1 has been last seen at ${location.latitude}, ${location.longitude}`);
    });
Connaitre le prochain événement d'un utilisateur
// Print the next event of the user 1
// (Calendar can be sync with Google Calendar for example)
gladys.calendar.getNextEventUser({id: 1})
    .then((event) => {
        console.log(`Your next event is "${event.name}", and start at ${event.start}.`);
    });
Envoyer un message à l'utilisateur 1
// Send a message to user 1 from Gladys (null)
var message = `Hey, human, it's Gladys !`;
gladys.message.send({id: null}, {text: message, receiver: 1});
Déclencher l’événement "back-at-home" pour l'utilisateur 1 dans la maison 1
// Save that user just got back at home 
// in house ID 1
// Full event list here => https://github.com/GladysProject/gladys-data/blob/master/events/en.json
var params = {
    code: 'back-at-home',
    house: 1,
    user: 1
};
gladys.event.create(params)
    .then(() => {
        console.log(`Event was created with success !`);
    });
Savoir si l'utilisateur 1 est dans la maison 1
// Just to check if user of ID 1 is in house 1 ! :)
var options = {
    house: 1,
    user: 1
};

gladys.house.isUserAtHome(options)
    .then((userAtHome) => {
        if(userAtHome) {
            console.log(`User is at home !`);
        } else {
            console.log(`User is not at home !`);
        }
    });

Manipuler les devices


Changer la valeur d'un devicetype
gladys.deviceType.exec({
    devicetype: ID_DU_DEVICETYPE,
    value: VALEUR_A_AFFECTER
})
.then((result) => console.log(result))
.catch((err) => console.log(err));
Insérer un device avec devicetype
var my_device = {            
    device: {        
            name: 'Temperature',        
            protocol: 'ethernet',   
            service: 'temperature',
            room: 1
        },        
        types: [{   type:'multilevel',            
                    unit: 'degré', 
                    sensor: true,
                    min: 0,            
                    max: 40, 
                    value: 12,
                }]   
};
        
gladys.device.create(my_device)
    .then(() => {
        console.log(`Device created with success !`);
    });
Tester la valeur d'un devicetype
gladys.deviceType.getById({ id: ID_DEVICETYPE})
  .then((result) => {
     if(result.lastValue == 0) {
       //do something
     } else {
       //do something
    }
   });
Connaitre la dernière valeur d'un devicetype
// Display DeviceType with it last state
// Useful if you want to know value of a sensor
// Or just to know if TV is still On ;)
gladys.deviceType.getById({id: 1})
    .then((deviceType) => {
        console.log(`Last deviceType value is ${deviceType.lastValue} !`); 
    });

Divers


Effectuer une requête HTTP
 gladys.utils.request('YOUR_REQUEST')
 .then((response) => 
 { 
     console.log(response);

     }).catch((err) => {

         console.log(err);
         
         });
Créer une box test

(obsolète depuis la version 3.8.0)

var box = {
	"uuid": "81afa4ed-c084-45b3-be8e-a9a28c9753ae",
	"title": "TEST BOX",
	"ngcontroller": "",
	"html": "<!--The TEST --><div id=\"TEST\" style=\"width: 100%\"></div>",
	"footer": "<div class=\"row\"> <div class=\"col-sm-6\"> TEST </div><!-- /.col --> </div><!-- /.row --> ",
	"icon": "fa fa-user",
	"type": "box box-solid bg-green-gradient",
	"view": "dashboard"
}
gladys.boxType.create(box);
Ajouter une phrase au brain
var data = {
    uuid = 'un uuid v4',
    text = ' ta phrase',
    label = 'command associée',
    service = 'le service associé',
    language = 'le language'
}

gladys.sentence.create(data);
gladys.brain.train();
Effectuer une requête SQL pour récupérer les Event
var date = [];

gladys.utils.sql('SELECT datetime FROM event WHERE eventtype = 10 ORDER BY datetime')
.then((rows) => {
    show(rows);
})
.catch((err) => console.log(err));

function show(r){
    for(i = 0; i < r.length; i++){
        date.push(r[i].datetime)
    }
    //date = r;
    console.log("date:")
    console.log(date);
}
Jouer de la musique dans une pièce
// Starting playing music in room 2
gladys.music.play({
    room: 2
});

// Pausing music in room 2
gladys.music.pause({
    room: 2
});
Connaitre le temps à un emplacement précis
// Get weather at a specific location
// (Need Forecast module)
var options = {
    latitude: 34.031266, 
    longitude: -118.682286
};

gladys.weather.get(options)
    .then((result) => {
        console.log(result);
        console.log(result.temperature);
        console.log(result.weather);
        console.log(result.humidity);
    })
    .catch(console.log);
Savoir si il fait jour à l'emplacement de la maison 1
// Useful to know if it's the day in house 1 
// (Your house must have latitude and longitude specified)
gladys.sun.isItDay({house: 1})
    .then((isDay) => {
        if(isDay) {
            console.log(`Yes, it's the day in house 1 !`);
        } else {
            console.log(`It's the night...`);
        }
    });
Créer une alarme
// Create an alarm that will ring  
// at 15:02 every monday for user 1
var options = {
    name: 'My great alarm',
    dayofweek: 1,
    time: '15:02',
    user: 1
};

gladys.alarm.create(options)
    .then(() => {
        console.log(`Alarm created with success !`);
    });
Obtenir le temps de trajet entre deux endroits
// Wants to get travel time between two points ?
// Need a direction module configurated in Gladys (Like google-direction)
var options = {
    origin: '10880 Malibu Point, 90265',
    destination: 'Golden Gate Bridge, San Francisco, CA, United State'
};

gladys.direction.travelTime(options)
    .then((result) => {
        console.log(`You need ${result.duration} seconds !`);
    });
Savoir si la maison 1 est vide
// Wants to know if your house is empty or someone is at home ?
gladys.house.isEmpty({house: 1})
    .then((empty) => {
        if(empty) {
            console.log('Nobody is at home !');
        } else {
            console.log('Home is safe. Someone is at home.');
        }
    });

Fun


Connaitre la valeur courante du BitCoin
// Make an HTTP request to get Bitcoin price
gladys.utils.request('https://api.coindesk.com/v1/bpi/currentprice.json')
    .then((result) => {
        
        var currentPrice = result.bpi.EUR.rate_float;
        var message = `BitCoin Current price is ${currentPrice} !`;
    });
Obtenir une recette aléatoire de cocktail
// Want a random cocktail ? Ask the right API for that !
// Check https://forum.kodi.tv/showthread.php?tid=235298&pid=2079513#pid2079513 for more informations
gladys.utils.request('http://www.thecocktaildb.com/api/json/v1/1/random.php')
    .then((result) => {
        var cocktail = result.drinks[0];
        console.log(`Today, we are going to drink a ${cocktail.strDrink}. It's a ${cocktail.strCategory} !`);
        console.log(`Ingredients are : 
            ${cocktail.strIngredient1}, 
            ${cocktail.strIngredient2}, 
            ${cocktail.strIngredient3}
        `);
    });
Obtenir une blague
// Want a dad Joke ?
// Use this API => https://icanhazdadjoke.com/
var options = {
  url: 'https://icanhazdadjoke.com',
  headers: {
    'Accept': 'application/json'
  }
};

gladys.utils.request(options)
    .then((result) => {
        console.log(`I have a joke. ${result.joke}`);
    });
Obtenir les coordonnées de la station ISS
// Wants the position of the ISS right now ?
// There is an API for that !
gladys.utils.request('http://api.open-notify.org/iss-now.json')
    .then((result) => {
       console.log(`Right now, the ISS is (${result.iss_position.latitude}, ${result.iss_position.longitude})`);
    });


Débuter dans la création d'un script dans gladys
[Module] Télévision connectée LG WebOs3
New EnOcean module soon available in the store
[RESOLU] Suppression de box via scripts + Bibliothèque scripts
Erreur dans le référentiel de script Telegram
[RESOLU] gladys.deviceType.getByIdentifier : comment s'en servir?
Tuto d'utilisation des modules après installation
Retour depart maison message
Requete http pour camera IP
Scénarios à conditions multiples, interrupteurs virtuels
closed #2

pinned #3