서민정

fix dialogflow launch error

......@@ -4,36 +4,36 @@ This project was bootstrapped with [Create React App](https://github.com/faceboo
In the project directory, you can run:
### `yarn start`
### `npm start`
Runs the app in the development mode.<br />
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `yarn test`
### `npm test`
Launches the test runner in the interactive watch mode.<br />
Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
### `npm run build`
Builds the app for production to the `build` folder.<br />
Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
......@@ -63,6 +63,6 @@ This section has moved here: https://facebook.github.io/create-react-app/docs/ad
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
......
This diff could not be displayed because it is too large.
......@@ -4,14 +4,13 @@
"private": true,
"dependencies": {
"antd": "^3.26.5",
"axios": "^0.18.0",
"axios": "^0.18.1",
"prop-types": "^15.7.2",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.0.0",
"react-scripts": "2.1.8",
"redux": "^4.0.5",
"redux-promise": "^0.6.0",
"redux-thunk": "^2.3.0",
......
No preview for this file type
......@@ -2,19 +2,29 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta
name="description"
content="Web site created using create-react-app"
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!-- <script charset="utf-8" src="//cdn.iframe.ly/embed.js?api_key=3d0d059e07f98dcecefab2"></script>
<script>
document.querySelectorAll( 'oembed[url]' ).forEach( element => {
iframely.load( element, element.attributes.url.value );
} );
</script> -->
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
......@@ -24,7 +34,7 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
......@@ -40,4 +50,9 @@
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
<!-- Include your favorite highlight.js stylesheet -->
</html>
......
......@@ -6,16 +6,6 @@
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
......
import React from "react";
import { Typography, Icon } from 'antd';
import chatbot from './chatbot/chatbot';
import Chatbot from './Chatbot/Chatbot';
const { Title } = Typography;
function App() {
......
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
import React, {useEffect} from 'react';
import React, { useEffect } from 'react';
import Axios from 'axios';
import {useDispatch, useSelector} from 'react-redux';
import {saveMessage} from '../_actions/message_actions';
import Message from './sections/msg';
import Card from './sections/card';
import {List, Icon, Avatar} from 'antd';
function chatbot(){
import { useDispatch, useSelector } from 'react-redux';
import { saveMessage } from '../_actions/message_actions';
import Message from './Sections/Message';
import { List, Icon, Avatar } from 'antd';
import Card from "./Sections/Card";
function Chatbot() {
const dispatch = useDispatch();
const messageFromRedux = useSelector(state => state.message.messages)
const messagesFromRedux = useSelector(state => state.message.messages)
useEffect(() => {
eventQuery('') //처음 시작했을 때 시작할 쿼리 설정
eventQuery('welcomeToMyWebsite')
}, [])
const textQuery = async(text) => {
const textQuery = async (text) => {
// First Need to take care of the message I sent
let conversation = {
who: 'user',
content: {
......@@ -25,7 +29,174 @@ function chatbot(){
}
dispatch(saveMessage(conversation))
// console.log('text I sent', conversation)
var inputString = conversation.content.text.text
// We need to take care of the message Chatbot sent
const textQueryVariables = {
text
}
try {
if(inputString[0] === '@'){
const response = await Axios.post('/api/crawling/textQuery', textQueryVariables)
} else {
//I will send request to the textQuery ROUTE
const response = await Axios.post('/api/dialogflow/textQuery', textQueryVariables)
for (let content of response.data.fulfillmentMessages) {
conversation = {
who: 'bot',
content: content
}
dispatch(saveMessage(conversation))
}
}
} catch (error) {
conversation = {
who: 'bot',
content: {
text: {
text: " Error just occured, please check the problem"
}
}
}
dispatch(saveMessage(conversation))
}
}
const eventQuery = async (event) => {
// We need to take care of the message Chatbot sent
const eventQueryVariables = {
event
}
try {
//I will send request to the textQuery ROUTE
const response = await Axios.post('/api/dialogflow/eventQuery', eventQueryVariables)
for (let content of response.data.fulfillmentMessages) {
let conversation = {
who: 'bot',
content: content
}
dispatch(saveMessage(conversation))
}
} catch (error) {
let conversation = {
who: 'bot',
content: {
text: {
text: " Error just occured, please check the problem"
}
}
}
dispatch(saveMessage(conversation))
}
}
const keyPressHanlder = (e) => {
if (e.key === "Enter") {
if (!e.target.value) {
return alert('you need to type somthing first')
}
//we will send request to text query route
textQuery(e.target.value)
e.target.value = "";
}
}
const renderCards = (cards) => {
return cards.map((card,i) => <Card key={i} cardInfo={card.structValue} />)
}
const renderOneMessage = (message, i) => {
console.log('message', message)
// we need to give some condition here to separate message kinds
// template for normal text
if (message.content && message.content.text && message.content.text.text) {
return <Message key={i} who={message.who} text={message.content.text.text} />
} else if (message.content && message.content.payload.fields.card) {
const AvatarSrc = message.who === 'bot' ? <Icon type="robot" /> : <Icon type="smile" />
return <div>
<List.Item style={{ padding: '1rem' }}>
<List.Item.Meta
avatar={<Avatar icon={AvatarSrc} />}
title={message.who}
description={renderCards(message.content.payload.fields.card.listValue.values)}
/>
</List.Item>
</div>
}
// template for card message
}
const renderMessage = (returnedMessages) => {
if (returnedMessages) {
return returnedMessages.map((message, i) => {
return renderOneMessage(message, i);
})
} else {
return null;
}
}
return (
<div style={{
height: 500, width: 700,
border: '3px solid black', borderRadius: '7px'
}}>
<div style={{ height: 444, width: '100%', overflow: 'auto' }}>
{renderMessage(messagesFromRedux)}
</div>
<input
style={{
margin: 0, width: '100%', height: 50,
borderRadius: '4px', padding: '5px', fontSize: '1rem'
}}
placeholder="Send a message..."
onKeyPress={keyPressHanlder}
type="text"
/>
</div>
)
}
export default chatbot;
\ No newline at end of file
export default Chatbot;
......
import React from 'react'
import { List, Icon, Avatar } from 'antd';
function Message(props) {
const AvatarSrc = props.who ==='bot' ? <Icon type="robot" /> : <Icon type="smile" />
return (
<List.Item style={{ padding: '1rem' }}>
<List.Item.Meta
avatar={<Avatar icon={AvatarSrc} />}
title={props.who}
description={props.text}
/>
</List.Item>
)
}
export default Message
import React from 'react'
import { Card, Icon } from 'antd';
const { Meta } = Card;
function CardComponent(props) {
return (
<Card
style={{ width: 300 }}
cover={
<img
alt={props.cardInfo.fields.description.stringValue}
src={props.cardInfo.fields.image.stringValue} />
}
actions={[
<a target="_blank" rel="noopener noreferrer" href={props.cardInfo.fields.link.stringValue}>
<Icon type="ellipsis" key="ellipsis" />
</a>
]}
>
<Meta
title={props.cardInfo.fields.stack.stringValue}
description={props.cardInfo.fields.description.stringValue}
/>
</Card>
)
}
export default CardComponent
......
import React from 'react';
import ReactDOM from 'react-dom';
import React from "react";
import ReactDOM from "react-dom";
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import "antd/dist/antd.css";
import App from "./App";
import Reducer from './_reducers';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import ReduxThunk from 'redux-thunk';
import { BrowserRouter } from "react-router-dom";
import * as serviceWorker from "./serviceWorker";
const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, ReduxThunk)(createStore);
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
<Provider
store={createStoreWithMiddleware(
Reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
)}
>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
......
......@@ -14,7 +14,7 @@ const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
......@@ -100,9 +100,7 @@ function registerValidSW(swUrl, config) {
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
......@@ -130,12 +128,8 @@ function checkValidServiceWorker(swUrl, config) {
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
......
This diff could not be displayed because it is too large.
......@@ -4,26 +4,31 @@ const bodyParser = require("body-parser");
const app = express();
const config = require("./server/config/keys");
// const mongoose = require("mongoose");
// mongoose.connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
// .then(() => console.log('MongoDB Connected...'))
// .catch(err => console.log(err));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api/dialogflow', require('./server/routes/dialogflow'));
// Serve static assets if in production
if (process.env.NODE_ENV === "production") {
// Set static folder
app.use(express.static("client/build"));
// Set static folder
app.use(express.static("client/build"));
// index.html for all page routes
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
// index.html for all page routes
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server Running at ${port}`)
console.log(`Server Running at ${port}`)
});
......
1. dialogflow로 기본 기능 구현
2. React로 프론트엔드 구현
3. routing으로 @가수명 입력하면 해당 라우팅(크롤링) 함수로 들어가게 구현
4. 크롤링 구현 (네이버TV 최신 영상 3개 json으로 가져오기)
5. json파일 카드로 넘겨주기
node 서버: localhost: 5000
프론트엔드/ localhost: 3000
---- 정리
리덕스 참고: https://velopert.com/3528
dialogflow
화자의 의도 intent ,사용자가 말하는 것과 dialogflow가 수행해야할 작업간의 매핑을 나타내는 것.
fallback intent : 사용자의 대화가 어떤 intent 와도 매칭되지 않을 때 선택되어지는 intent
화자의 속성 entity
ex. 내일 오후 2시 되나요? 에서 '내일', '오후 2시'를 파라미터로 뽑아내는 것.
문맥 context
내일 오후 2시 되나요? 에서 무엇을 위한 내일 오후 2시인가를 파악하기 위해서 그 전에 대화가 되었던 '수리'라는 것을 기억하는 것을 의미함
-----
001 - welcome
002 - 인사
003 - @'가수명'
-> 해당 가수명으로 크롤링을 했을 때 null이 3개이상 나오면 가수명이 없다고 판단함.
-> 만약 가수가 아니더라도 크롤링 시 해당되는 내용이 3개 이상 나오면 해당 내용을 리턴함.
-----
This diff could not be displayed because it is too large.
{
"name": "chatbot-app",
"version": "1.0.0",
"description": "chatbot-app",
"main": "index.js",
"engines": {
"node": "12.16.1",
"npm": "6.13.4"
},
"scripts": {
"start": "node index.js"
},
"author": "Minjeong Seo",
"dependencies": {
"actions-on-google": "^2.6.0",
"body-parser": "^1.18.3",
"dialogflow": "^0.8.2",
"dialogflow-fulfillment": "^0.6.1",
"express": "^4.16.4"
}
"name": "chatbot-app",
"version": "1.0.0",
"description": "chatbot-app",
"main": "index.js",
"engines": {
"node": "10.15.0",
"npm": "6.9.0"
},
"scripts": {
"start": "node index.js",
"backend": "nodemon index.js",
"frontend": "npm run front --prefix client",
"dev": "concurrently \"npm run backend\" \"npm run start --prefix client\""
},
"author": "Jaewon Ahn",
"license": "ISC",
"dependencies": {
"actions-on-google": "^2.12.0",
"body-parser": "^1.18.3",
"dialogflow": "^0.8.2",
"dialogflow-fulfillment": "^0.6.1",
"express": "^4.16.4",
"mongoose": "^5.4.20"
},
"devDependencies": {
"concurrently": "^4.1.0",
"nodemon": "^1.18.10"
}
\ No newline at end of file
}
......
1. dialogflow로 기본 기능 구현
2. React로 프론트엔드 구현
3. routing으로 @가수명 입력하면 해당 라우팅(크롤링) 함수로 들어가게 구현
4. 크롤링 구현 (네이버TV 최신 영상 3개 json으로 가져오기)
5. json파일 카드로 넘겨주기
---- 정리
리덕스 참고: https://velopert.com/3528
const mongoose = require('mongoose');
const opinionSchema = mongoose.Schema({
name: String,
opinion: String,
email: String,
registerDate: Date
});
const Opinion = mongoose.model('Opinion', opinionSchema);
module.exports = { Opinion }
const express = require('express');
const router = express.Router();
const dialogflow = require('dialogflow');
const structjson = require('./structjson.js');
const dialogflow = require('dialogflow');
const uuid = require('uuid');
const config = require('../config/keys');
......@@ -10,51 +10,74 @@ const projectId = config.googleProjectID
const sessionId = config.dialogFlowSessionID
const languageCode = config.dialogFlowSessionLanguageCode
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
//Text Query Route
router.post('/textQuery',async (req,res) => {
// We will make two routes
// Text Query Route
router.post('/textQuery', async (req, res) => {
//We need to send some information that comes from the client to Dialogflow API
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// dialogflow agent에 보내는 query
// The query to send to the dialogflow agent
text: req.body.text,
// 사용자언어 (ko)
// The language used by the client (en-US)
languageCode: languageCode,
},
},
};
const response = await sessionClient.detectIntent(request);
console.log('Detected Intent');
const result = response[0].queryResult;
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
res.send(result)
});
})
//Event Query Route
// Event Query Route
router.post('/eventQuery',async (req,res) => {
router.post('/eventQuery', async (req, res) => {
//We need to send some information that comes from the client to Dialogflow API
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
name: req.body.text,
// 사용자언어 (ko)
event: {
// The query to send to the dialogflow agent
name: req.body.event,
// The language used by the client (en-US)
languageCode: languageCode,
},
},
};
const response = await sessionClient.detectIntent(request);
console.log('Detected Intent');
const result = response[0].queryResult;
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
res.send(result)
});
})
module.exports = router;
\ No newline at end of file
module.exports = router;
......