티스토리 뷰

Github에 소스좀 정리를 했는데 이참에 하나씩 설명을 한다.

V1 버전 앱이다.


어떤게 교보재로 좋을까 싶은데 아무래도 가상화폐-업비트 시세 앱이 좋을거같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
  "name""Stratos Heavy Industry",
  "engines": {
    "node"">= 7.6"
  },
  "description""BitCoin",
  "main""index.js",
  "devDependencies": {
    "@google-cloud/storage""^1.4.0",
    "actions-on-google""^1.6.1",
    "package""^1.0.1",
    "package.json""^2.0.1",
    "promise""^8.0.1",
    "request""^2.83.0"
  },
  "scripts": {
    "deploy""gcloud app deploy",
    "start""node app.js",
    "lint""samples lint",
    "pretest""npm run lint",
    "system-test""samples test app",
    "test""npm run system-test",
    "e2e-test""samples test deploy"
  },
  "private""true",
  "license""ISC",
  "dependencies": {
    "@google-cloud/storage""^1.4.0",
    "actions-on-google""^1.6.1",
    "package""^1.0.1",
    "package.json""^2.0.1",
    "promise""^8.0.1",
    "request""^2.83.0"
  }
}
cs


이런 형태이다. 

다른건 안 중요한데 "actions-on-google" 부분은 1.xx이다. 만약 2 버전 넣으면 에러난다. V2만 지원하는 거 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
'use strict';
 
process.env.DEBUG = 'actions-on-google:*';
const DialogFlow = require('actions-on-google').DialogflowApp; // apiai
const requests = require('request'); // request
const Promise = require('promise');
 
let endText = " 다음 질문을 해 주세요.";
 
exports.cryptocurrencyUpBit = (request, response) => {
    //dialogflowFirebaseFulfillment cryptocurrency
 
    //switch : policy가 없으면 deny되기 때문에 policy페이지 만들어야 함.
    // 구글 문서로도 만들수는 있다.
    //console.log('Request body: ' + JSON.stringify(request.body));
    let jsonLang = request.body.lang;
    let actions = request.body.result.action; //input.welcome
 
 
    switch (request.method) {
        case 'GET'// policy를 위한 페이지임
            response.writeHead(200, {
                "Content-Type""text/html; charset=utf-8"
            });
 
            var title = '전자화폐 가격  Private Policy';
            var body = '<p>전자화폐 가격  Private Policy</p>\n \
  <p>아무것도 저장하지 않습니다.</p>\n \
  <p>그냥 즐기세요</p>\n \
  <p> - Stratos Heavy Industy</p>';
 
            var code = [
        '<!DOCTYPE html>',
        '<html>',
        '<head>',
        '<meta charset="utf-8" />',
        '<title>' + title + '</title>',
        '</head>',
        '<body>',
        body,
        '</body>',
        '</html>'
      ].join('\n');
 
            response.write(code, "utf8");
            response.end();
            break;
 
        default// post
            const app = new DialogFlow({
                request,
                response
            });
            const lastSeen = app.getLastSeen();
            console.log(app.getIntent());
 
            // 여기서부터 시작
 
            // 코인정보 업비트서버에서 가져오기
            function getBitsumJson(code, callback) {
                var url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/1?code=CRIX.UPBIT.KRW-" + code;
                var hanName = '';
                var imageLink = '';
                console.log(code);
                //BTC, ETH, DASH, LTC, ETC, XRP, BCH, XMR, ZEC, QTUM, BTG, EOS (기본값: BTC), ALL(전체)
                //https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/10?code=CRIX.UPBIT.KRW-
                switch (code) {
                    case 'BTC':
                        hanName = "비트코인";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/bitcoin.jpg";
                        break;
                    case 'ETH':
                        hanName = "이더리움";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/ethereum.jpg";
                        break;
                    case 'DASH':
                        hanName = "대쉬";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/dash.jpg";
                        break;
                    case 'LTC':
                        hanName = "라이트 코인";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/litecoin.jpg";
                        break;
                    case 'ETC':
                        hanName = "이더리움 클래식";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/ethereumclassic.jpg";
                        break;
                    case 'XRP':
                        hanName = "리플";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/ripple.jpg";
                        break;
                    case 'BCC':
                        hanName = "비트코인 캐쉬";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/bitcoincash.jpg";
                        break;
                    case 'XMR':
                        hanName = "모네로";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/moenro.jpg";
                        break;
                    case 'ZEC':
                        hanName = "제트캐쉬";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/zcash.png";
                        break;
                    case 'QTUM':
                        hanName = "퀀텀";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/quantum.png";
                        break;
                    case 'BTG':
                        hanName = "비트코인 골드";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/bitgold.jpg";
                        break;
                    case 'XLM':
                        hanName = "스텔라루멘";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/stellar.png";
                        break;
                    case 'SNT':
                        hanName = "스테이터스 네트쿼크 토큰";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/SNT.jpeg";
                        break;
                    case 'NEO':
                        hanName = "네오";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/neo.jpg";
                        break;
                    case 'STEEM':
                        hanName = "스팀";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/steem.jpg";
                        break;
                    case 'SBD':
                        hanName = "스팀달러";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/SBD.png";
                        break;
                    case 'STRAT':
                        hanName = "스트라티스";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/STRAT.png";
                        break;
                    case 'XEM':
                        hanName = "뉴 이코노미 무브먼트";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/XEM.png";
                        break;
                    case 'KMD':
                        hanName = "코모도";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/KMD.png";
                        break;
                    case 'LSK':
                        hanName = "리스크";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/LSK.jpg";
                        break;
                    case 'OMG':
                        hanName = "오미세고";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/OMG.png";
                        break;
                    case 'MER':
                        hanName = "머큐리";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/mer.png";
                        break;
                    case 'ARDR':
                        hanName = "아더";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/ARDR.png";
                        break;
                    case 'EMC2':
                        hanName = "아인스타이늄";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/EMC2.png";
                        break;
                    case 'PIVX':
                        hanName = "피벡스";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/PIVX.png";
                        break;
                    case 'TIX':
                        hanName = "블록틱스";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/TIX.png";
                        break;
                    case 'POWR':
                        hanName = "파워렛저";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/POWR.png";
                        break;
                    case 'ARK':
                        hanName = "아크";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/ARK.jpg";
                        break;
                    case 'GRS':
                        hanName = "그로스톨코인";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/GRS.png";
                        break;
                    case 'STORJ':
                        hanName = "스토리지";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/STORJ.jpg";
                        break;
                    case 'MTL':
                        hanName = "메탈";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/MTL.jpg";
                        break;
                    case 'WAVES':
                        hanName = "웨이브";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/WAVES.jpeg";
                        break;
                    case 'REP':
                        hanName = "어거";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/REP.png";
                        break;
                    case 'VTC':
                        hanName = "버트코인";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/VTC.png";
                        break;
                    case 'STORM':
                        hanName = "스톰";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/storm.jpg";
                        break;
                    case 'ICX':
                        hanName = "아이콘";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/icon.JPG";
                        break;
                    case 'ALL':
                        url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/1?code=CRIX.UPBIT.KRW-BTC";
                        hanName = "전체";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/main.jpg";
                        break;
                    default// 기본은 모든 정보를 가져온다
                        url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/1?code=CRIX.UPBIT.KRW-BTC";
                        hanName = "전체";
                        imageLink = "https://storage.googleapis.com/finalrussianroulette.appspot.com/coinimage/main.jpg";
                        break;
                }
                console.log(url);
 
                // Get data
                requests({
                    url: url,
                    encoding: null,
                    headers: {
                        'User-Agent''Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.1.1 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7'
                    }
                }, function (err, resp, body) {
                    if (err) {
                        callback(err, {
                            code: 400,
                            name''
                        });
                        return;
                    }
 
                    var original = JSON.parse(body.toString());
                    callback(null, {
                        code: 200,
                        data: original[0],
                        name: hanName,
                        imageLink: imageLink
                    });
                });
 
            }
 
 
            function getBitFlyerJson(callback) {
                var url = "https://api.bitflyer.jp/v1/ticker?product_code=BTC_JPY";
 
                // Get data
                requests({
                    url: url,
                    encoding: null,
                    headers: {
                        'User-Agent''Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.1.1 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7'
                    }
                }, function (err, resp, body) {
                    if (err) {
                        callback(err, {
                            code: 400,
                            name''
                        });
                        return;
                    }
 
                    var original = body;
                    callback(null, {
                        code: 200,
                        data: original
                    });
                });
 
            }
 
            function getJPYKRW(callback) {
                var url = "http://api.manana.kr/exchange/rate.json";
 
                // Get data
                requests({
                    url: url,
                    encoding: null,
                    headers: {
                        'User-Agent''Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.1.1 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7'
                    }
                }, function (err, resp, body) {
                    if (err) {
                        callback(err, {
                            code: 400,
                            name''
                        });
                        return;
                    }
 
                    var original = body;
                    callback(null, {
                        code: 200,
                        data: original
                    });
                });
 
            }
 
            function promiseJsonConnect(currency) {
                return new Promise(function (resolved, rejected) {
                    getBitsumJson(currency, function (err, result) {
                        if (err) {
                            rejected(err);
                        } else {
                            resolved(result);
                        }
                    });
                });
            }
 
            function kimchiPromiseJsonConnect() {
                return new Promise(function (resolved, rejected) {
                    getBitFlyerJson(function (err, result) {
                        if (err) {
                            rejected(err);
                        } else {
                            resolved(result);
                        }
                    });
                });
            }
 
            function getJPYKRWJsonConnect() {
                return new Promise(function (resolved, rejected) {
                    getJPYKRW(function (err, result) {
                        if (err) {
                            rejected(err);
                        } else {
                            resolved(result);
                        }
                    });
                });
            }
 
            // 선택된 코인 가격 출력
            function select_coin_func(app) {
                app.data.fallbackCount = 0;
                var currency = app.getArgument('currency');
                Promise.all([promiseJsonConnect(currency)]).then(result => {
                    let displayText = '';
                    let speechText = '';
                    if (result[0].code != 200) {
                        //문제있음
                        app.ask(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText,
                                displayText: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText
                            }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                        );
                    } else {
 
                        let results = result[0].data;
 
                        let opening_price = parseInt(results.openingPrice);
 
                        let min_price = parseInt(results.highPrice);
                        let max_price = parseInt(results.lowPrice);
                        let average_price = parseInt(results.tradePrice);
 
                        let imageLink = result[0].imageLink; // 이미지 주소 복사
 
                        let name = result[0].name// 사용자 경험을 위한 이름 한글
 
                        let texttemp = '현재 ' + name + '의 가격은 평균' + average_price + '원 입니다. 최저가는 ' + min_price + '원 이며 최고가는 ' + max_price + '원 입니다. ' + endText;
 
                        displayText = '현재 ' + name + '의 가격은 평균' + average_price + '원 입니다. 최저가는 ' + min_price + '원 이며 최고가는 ' + max_price + '원 입니다. ' + endText;
 
                        speechText = displayText;
 
                        app.data.repeatText = displayText;
                        app.data.repeatSound = speechText;
                        app.data.repeatImage = imageLink;
                        app.data.repeatTitle = '현재 ' + name + '의 가격';
                        app.data.repeatChip = ['메뉴얼''다시듣기''비트코인''리플''이더리움'];
 
                        app.ask(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: speechText,
                                displayText: displayText
                            }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                            .addBasicCard(app.buildBasicCard('')
                                .setSubtitle('평균 ' + average_price + '원 입니다.')
                                .setTitle('현재 ' + name + '의 가격')
                                .setImage(imageLink, name))
                        );
 
                    }
 
 
                });
 
            } // 선택된 코인 가격 출력
 
            // 현재 코인 시세
            function nowall_coin_func(app) {
                app.data.fallbackCount = 0;
                let currency = "BTC";
                Promise.all([promiseJsonConnect(currency)]).then(result => {
 
                    let displayText = '';
                    let speechText = '';
                    console.log(result);
                    if (parseInt(result[0].code) != 200) {
                        //문제있음
                        app.ask(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText,
                                displayText: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText
                            }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                        );
                    } else { // code 200
 
                        let BTC = parseInt(result[0].data.tradePrice);
                        let calculatorComma = numberWithCommas(BTC);
 
                        let imageLink = result[0].imageLink;
 
                        let textinsert = '';
 
                        //자세한 화폐 시세는 추가적인 데이터를 부른다.
                        if (actions != "input.welcome") {
                            displayText += '비트코인 ' + calculatorComma + '원 \n' + ' 입니다. ';
                            textinsert += '비트코인 ' + calculatorComma + '원 \n' + ' 입니다. ';
                        } else {
                            app.data.fallbackCount = 0;
                            if (lastSeen != null) { // re visit.
                                displayText += '가상화폐 시세에 다시 오신 것을 환영합니다. 기준점인 ';
                                textinsert += '가상화폐 시세에 다시 오신 것을 환영합니다. 기준점인 ';
                            } else { // first
                                displayText += '가상화폐 시세에 오신것을 환영합니다. 현재 기준점인 ';
                                textinsert += '가상화폐 시세에 오신것을 환영합니다. 현재 기준점인 ';
                            }
                            displayText += '비트코인은 ' + calculatorComma + '원 \n' + ' 입니다. 지원되는 코인질문을 해주시면 언제든지 답해드립니다.';
                            textinsert += '\n' + '비트코인은 ' + calculatorComma + '원 \n' + ' 입니다. 지원되는 코인질문을 해주시면 언제든지 답해드립니다.';
                        }
 
                        displayText += endText;
                        speechText = displayText;
 
                        app.data.repeatText = displayText;
                        app.data.repeatSound = speechText;
                        app.data.repeatImage = imageLink;
                        app.data.repeatTitle = '기준점 비트코인 시세';
                        app.data.repeatChip = ['메뉴얼''다시듣기''비트코인''리플''이더리움'];
 
                        app.ask(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: speechText,
                                displayText: displayText
                            }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                            .addBasicCard(app.buildBasicCard('')
                                .setSubtitle("기준점 비트코인 시세")
                                .setTitle("기준점 비트코인 시세")
                                .setImage(imageLink, "화폐 시세"))
                        );
                    }
                });
 
            }
 
            // 코인수를 계산해주는 메소드
            function coin_cal_func(app) {
                app.data.fallbackCount = 0;
                let currency = app.getArgument('currency');
                let number = app.getArgument('number');
 
                Promise.all([promiseJsonConnect(currency)]).then(result => {
 
                    let displayText = '';
                    let speechText = '';
 
                    if (result[0].code != 200) {
                        //문제있음
 
                        app.ask(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText,
                                displayText: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText
                            }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                            .addBasicCard(app.buildBasicCard('')
                                .setImage('https://storage.googleapis.com/finalrussianroulette.appspot.com/lottoImage/dogeza.jpg''죄송합니다')
                            )
                        );
                    } else {
 
                        let results = result[0].data;
 
                        let average_price = parseInt(results.openingPrice);
                        let imageLink = result[0].imageLink;
                        let name = result[0].name;
 
                        let calculator = parseInt(average_price * number); // 계산
                        let calculatorComma = numberWithCommas(calculator);
                        displayText = name + '의 ' + number + '개 가격은 현재 ' + calculatorComma + '원 입니다.' + endText;
                        speechText = displayText;
 
                        app.data.repeatText = displayText;
                        app.data.repeatSound = speechText;
                        app.data.repeatImage = imageLink;
                        app.data.repeatTitle = name + '의 ' + number + '개 가격';
                        app.data.repeatChip = ['메뉴얼''다시듣기''비트코인''리플''이더리움'];
 
                        app.ask(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: speechText,
                                displayText: displayText
                            }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                            .addBasicCard(app.buildBasicCard('')
                                .setSubtitle(calculator.toString())
                                .setTitle(name + '의 ' + number + '개 가격')
                                .setImage(imageLink, name))
                        );
                    }
                });
 
 
 
            }
 
            function bye_func(app) {
                app.data.fallbackCount = 0;
                let displayText = '앱을 종료합니다. 이용해 주셔서 감사합니다.';
                let speechText = displayText;
                app.tell(app.buildRichResponse()
                    .addSimpleResponse({
                        speech: speechText,
                        displayText: displayText
                    })
                );
 
            }
 
            // fallback count & method.
            const FALLBACK_NUMBER = "fallbacks";
 
            function fallback_func(app) {
                let count = app.data.fallbackCount;
                count++;
                app.data.fallbackCount = count;
 
                let speechText = '';
                let displayText = '';
 
                if (count === 1) {
                    displayText = '지원되지 않는 명령어 입니다. 지원되는 명령어 중 하나는 저는 "20 비트코인 가격"을 말하면 계산이 가능합니다. 자 다시 말해주세요.';
                    speechText = displayText;
                    app.ask(app.buildRichResponse()
                        .addSimpleResponse({
                            speech: speechText,
                            displayText: displayText
                        }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                        .addBasicCard(app.buildBasicCard('')
                            .setImage('https://storage.googleapis.com/finalrussianroulette.appspot.com/lottoImage/dogeza.jpg''죄송합니다')
                        )
                    );
 
                } else if (count === 2) {
                    displayText = '지원되지 않는 명령어 입니다. 지원되는 명령어 중 하나는 저는 "현재 시세를 알려줘" 를 말하면 현재 12개의 비트코인 시세를 알려줍니다. 자 다시 말해주세요.';
                    speechText = displayText;
                    app.ask(app.buildRichResponse()
                        .addSimpleResponse({
                            speech: speechText,
                            displayText: displayText
                        }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                        .addBasicCard(app.buildBasicCard('')
                            .setImage('https://storage.googleapis.com/finalrussianroulette.appspot.com/lottoImage/dogeza2.jpg''정말로 죄송합니다')
                        )
                    );
 
                } else if (count > 2) {
                    displayText = '더이상 앱은 사용자님의 말을 이해하지 못했습니다. 종료하겠습니다.';
                    speechText = displayText;
                    app.tell(app.buildRichResponse()
                        .addSimpleResponse({
                            speech: speechText,
                            displayText: displayText
                        })
                    );
                }
 
            }
 
            // repeat반복 재생.
            function repeat_func(app) {
                app.data.fallbackCount = 0;
 
                let TextDisplay = app.data.repeatText;
                let TextSpeech = app.data.repeatSound;
                let repeatImage = app.data.repeatImage;
                let repeatTitle = app.data.repeatTitle;
 
                app.ask(app.buildRichResponse()
                    .addSimpleResponse({
                        speech: TextSpeech,
                        displayText: TextDisplay
                    }).addSuggestions(app.data.repeatChip)
                    .addBasicCard(app.buildBasicCard('')
                        .setImage(repeatImage, repeatTitle)
                    )
                );
 
            }
 
            // 비트코인 시세한테 말하기 전용 메소드
 
            function bitcoinprice_func(app) {
 
                Promise.all([promiseJsonConnect("BTC")]).then(result => {
 
                    let displayText = '';
                    let speechText = '';
                    if (parseInt(result[0].code) != 200) {
                        //문제있음
                        app.tell(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText,
                                displayText: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText
                            })
                        );
                    } else { // code 200
 
                        let BTC = parseInt(result[0].data.tradePrice);
                        let calculatorComma = numberWithCommas(BTC);
                        let imageLink = result[0].imageLink;
                        let textinsert = '';
 
                        //자세한 화폐 시세는 추가적인 데이터를 부른다.
 
                        if (lastSeen != null) { // re visit.
                            displayText += '비트코인 시세에 다시 오신 것을 환영합니다. 기준점인 ';
                            textinsert += '비트코인 시세에 다시 오신 것을 환영합니다. 기준점인 ';
                        } else { // first
                            displayText += '비트코인 시세에 오신것을 환영합니다. 현재 기준점인 ';
                            textinsert += '비트코인 시세에 오신것을 환영합니다. 현재 기준점인 ';
                        }
                        displayText += '비트코인은 ' + calculatorComma + '원 \n' + ' 입니다. 그럼 앱을 종료합니다.';
                        textinsert += '\n' + '비트코인은 ' + calculatorComma + '원 \n' + ' 입니다. 그럼 앱을 종료합니다.';
 
                        speechText = displayText;
 
                        app.tell(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: speechText,
                                displayText: displayText
                            })
                            .addBasicCard(app.buildBasicCard('')
                                .setSubtitle("비트코인 시세")
                                .setTitle("비트코인 시세")
                                .setImage(imageLink, "비트코인 시세"))
                        );
                    }
                });
 
            }
 
            function kimchiPrice_func(app) {
 
                Promise.all([promiseJsonConnect("BTC"), kimchiPromiseJsonConnect(), getJPYKRWJsonConnect()]).then(([rows1, rows2, row3]) => {
 
                    let displayText = '';
                    let speechText = '';
 
                    if (parseInt(rows1[0].code) != 200) {
                        //문제있음
                        app.tell(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText,
                                displayText: "현재 서버에 문제가 있어서 연결할 수 없습니다. 다음에 다시 시도해 주세요. " + endText
                            })
                        );
                    } else { // code 200
                        console.log(JSON.stringify(rows1[0]));
                        console.log(JSON.stringify(rows2[0]));
                        console.log(JSON.stringify(rows3[0]));
 
                        let BTCKR = parseInt(rows1[0].data.tradePrice);
                        let BitflyerBTC = parseInt(rows2[0].data.ltp);
                        let JPYKRW = parseInt(rows3[0].data.rate);
                        let calKimchiPrice = 100 - (BitflyerBTC * JPYKRW) / BTCKR;
                        let imageLink = rows1[0].imageLink;
                        let textinsert = '';
 
                        //자세한 화폐 시세는 추가적인 데이터를 부른다.
 
                        if (lastSeen != null) { // re visit.
                            displayText += '김치 프리미넘에 다시 오신 것을 환영합니다. 기준점인 ';
                            textinsert += '비트코인 시세에 다시 오신 것을 환영합니다. 기준점인 ';
                        } else { // first
                            displayText += '비트코인 시세에 오신것을 환영합니다. 현재 기준점인 ';
                            textinsert += '비트코인 시세에 오신것을 환영합니다. 현재 기준점인 ';
                        }
                        displayText += '김치 프리미엄은 ' + calKimchiPrice + '% \n' + ' 입니다. ';
                        textinsert += '\n' + '김치 프리미엄은  ' + calKimchiPrice + '% \n' + ' 입니다.';
 
                        speechText = displayText;
 
                        app.ask(app.buildRichResponse()
                            .addSimpleResponse({
                                speech: speechText,
                                displayText: displayText
                            })
                            .addBasicCard(app.buildBasicCard('')
                                .setSubtitle("비트코인 시세")
                                .setTitle("비트코인 시세")
                                .setImage(imageLink, "비트코인 시세"))
                        );
                    }
                });
 
            }
 
            function help_func(app) {
 
                let displayText = '이 앱은 2가지 기능이 있습니다. "20 비트코인은 얼마"와 같이 말하면 계산된 액수를 말합니다. "리플의 가격을 알려줘" 같이 말을 하면 특정 화폐의 가격을 알 수 있습니다. 앱을 종료하고 싶다면 "끝내기"를 말하시면 됩니다. 다음질문을 해 주세요.';
                let speechText = displayText;
 
                app.ask(app.buildRichResponse()
                    .addSimpleResponse({
                        speech: speechText,
                        displayText: displayText
                    }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                    .addBasicCard(app.buildBasicCard('')
                        .setSubtitle("비트코인 메뉴얼")
                        .setTitle("비트코인 메뉴얼")
                        .setImage('https://storage.googleapis.com/finalrussianroulette.appspot.com/image/menu.jpg'"비트코인 메뉴얼"))
                );
 
            }
 
            // 콤마 찍기
            function numberWithCommas(x) {
                return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }
 
 
            // intend get
            const actionMap = new Map();
 
            // intent name
            const WELCOME = 'input.welcome';
            const BYE = 'intent.exit';
            const SELECTCOINPRICE = 'intent.selectcoinprice'//
            const COINCAL = 'intent.cal'//
            const FALLBACK = 'input.unknown'//
            const REPEATFUNC = 'intent.repeat'//
            const HELPFUNC = 'intent.menual'//
            const KIMCHIPRICE = 'intent.kimchi';
            //exit
            actionMap.set(WELCOME, nowall_coin_func);
 
            //exit
            actionMap.set(BYE, bye_func);
 
            // intend fucntion
            actionMap.set(SELECTCOINPRICE, select_coin_func);
            actionMap.set(WELCOME, nowall_coin_func);
            actionMap.set(COINCAL, coin_cal_func);
            actionMap.set(KIMCHIPRICE, kimchiPrice_func);
 
 
            actionMap.set(FALLBACK, fallback_func);
 
            actionMap.set(REPEATFUNC, repeat_func);
            actionMap.set(HELPFUNC, help_func);
 
            //비트코인 시세 앱에서 사용하는 부분 건드리지 말것.
            const BITCOINPRICE = 'input.bitcoinprice';
            actionMap.set(BITCOINPRICE, bitcoinprice_func);
 
 
            // go!
            app.handleRequest(actionMap);
 
            break// default end
    }
 
}
 

cs


거 취향참 이상한 소스이지만 암튼 잘 돌아간다. 앱 자체는 context를 쓸 일이 없어서 저런 형태이다.

만약 flow를 만들어야 한다면 context를 써야 하지만... 뭐 그런걸 만들었다간 머리 터지니까.


1
2
3
4
5
6
7
8
9
10
 app.ask(app.buildRichResponse()
                    .addSimpleResponse({
                        speech: speechText,
                        displayText: displayText
                    }).addSuggestions(['메뉴얼''다시듣기''비트코인''리플''이더리움'])
                    .addBasicCard(app.buildBasicCard('')
                        .setSubtitle("비트코인 메뉴얼")
                        .setTitle("비트코인 메뉴얼")
                        .setImage('https://storage.googleapis.com/finalrussianroulette.appspot.com/image/menu.jpg'"비트코인 메뉴얼"))
                );
cs


이 부분은 response부분이다. 레퍼런스 보면 알지만 그림과 chip이라고 하는 선택버튼과 텍스트를 출력하는 형태이다.


결론적으로는 

app.handleRequest(actionMap); -> actionMap.set(action이름, function);

action이름에 맞는 function을 찾고 function에서 로직이 처리되는 형태이다.

앱은 google cloud에서 돌고 있다. 



dialogflow 부분은 소스를 참조하면 될거같다. 임시로 하나프로젝트 만들어서 import하면 되니 말이다.

위에 사진을 보면 알겠지만 export하고 비어있는 프로젝트에서 restore이나 import하면 그대로 볼수 있다.





공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함