Обязательно подпишитесь на меня на Github
Посмотрите ниже репозиторий Github для кода

Задача

Разработайте чат-бота с Node.JS, который может взаимодействовать с человеком через терминал и может информировать пользователя о погоде.

Построен с

Инструкции:

1. инициализировать файл Node JS

npm init

2. Создайте app.js и введите следующий код:

"use strict";
const Readline = require("readline");
const rl = Readline.createInterface({
    input:process.stdin,
    output:process.stdout,
    terminal:false
});
const matcher = require("./matcher");
rl.setPrompt("> ");
rl.prompt();
rl.on("line", reply => {
    matcher(reply, data => {
        switch(data.intent){
            case "Hello": 
                console.log("Hello from Espresso");
                rl.prompt();
                break;
            case "Exit":
                console.log("See you later!");
                process.exit(0);
            default: {
                console.log("I'm sorry I did not understand that");
                rl.prompt();                
            }
        }
    });
}); 

3.Установите следующий пакет узлов

npm install -g nodemon

npm i [email protected] --save --save-exact

npm i [email protected] --save --save-exact

4.Сделайте четыре папки

mkdir patterns

mkdir matcher

mkdir weather

mkdir parser

5. в каждую из папок положить по index.js файлу внутри них

touch patterns/index.js

touch matcher/index.js

touch weather/index.js

touch parser/index.js

6. Скопируйте и вставьте следующий код уважаемого файла

шаблоны / index.js

const patternDict = [{
    pattern: "\\b(?<introduction>Hi|Hello|Hey|What's up)\\b",
    intent: "Hello"
}, {
    pattern: "\\b(bye|exit)\\b",
    intent: "Exit"
}, {
    pattern: "like\\sin\\s\\b(?<city>.+)",
    intent: "CurrentWeather"
}];
module.exports = patternDict;

сопоставитель / index.js

"use strict";
const patterns = require("../patterns");
const XRegExp = require("xregexp");
let createEntities = (str, pattern) => {
    return XRegExp.exec(str, XRegExp(pattern, "i"));
}
let matchPattern = (str, callBack) => {
    let getResults = patterns.find(item => {
        if(XRegExp.test(str, XRegExp(item.pattern, "i"))){
            return true;
        }
    });
    if(getResults){
        return callBack({
            intent: getResults.intent,
            entities: createEntities(str, getResults.pattern)
        });
    } else{
        return callBack({});
    }
}
module.exports = matchPattern;

погода / index.js

"use strict";
const YQL = require("yql");
let getWeather = (location, type = "forecast") => {
    return new Promise((resolve, reject) => {
        let query = new YQL(`select ${type === "current" ? "item.condition, location" : "*"} from weather.forecast where woeid in (select woeid from geo.places(1) where text = "${location}") and u="f"`);
    
        query.exec((error, response) => {
            if(error){
                reject(error);
            } else{
                resolve(response);
            }
        });
    });
}
module.exports = getWeather;

парсер / index.js

let getFeel = temp => {
    if(temp < 5) {
		return "shivering cold";
	} else if(temp >= 5 && temp < 15) {
		return "pretty cold";
	} else if(temp >= 15 && temp < 25) {
		return "moderately cold";
	} else if(temp >= 25 && temp < 32) {
		return "quite warm";
	} else if(temp >= 32 && temp < 40) {
		return "very hot";
	} else {
		return "super hot";
	}
}
let currentWeather = response => {
    if(response.query.results){
        let resp = response.query.results.channel;
        let location = `${resp.location.city}, ${resp.location.country}`;
        let {text, temp} = resp.item.condition;
        return `Right now, it is ${text.toLowerCase()} in ${location}. It is ${getFeel(Number(temp))} at ${temp} degrees Fahrenheit.`
    }
}
module.exports = {
    currentWeather
}

7.Запустите приложение, которое вы можете использовать:

nodemon app.js (рекомендуется)

node app.js

8. Задайте боту несколько вопросов, у которых like in {Name of the City} через терминал. Ниже приведены некоторые тестовые примеры.

Прецедент

Примеры: (Обратите внимание, что эти примеры могут не указывать точную временную задержку в другое время)

Пользовательский ввод: What is the weather like in Los Angeles

Выход: Right now, it is sunny in Los Angeles, United States. It is super hot at 62 degrees Fahrenheit.

Пользовательский ввод: What is the weather like in New York

Выход: Right now, it is cloudy in New York, United States. It is super hot at 49 degrees Fahrenheit.

Пользовательский ввод: What is the weather like in Chicago

Выход: Right now, it is breezy in Chicago, United States. It is super hot at 43 degrees Fahrenheit.

Автор

Кристофер Ким

Как и было обещано, вот репозиторий Github