-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathCode.gs
1718 lines (1540 loc) · 58.3 KB
/
Code.gs
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*************************************************************************************************
* Naver News Fetching Bot (v3.0.1)
* ***********************************************************************************************
* 원하는 검색어가 포함된 최신 네이버 뉴스를 업무용 채팅 솔루션으로 전송합니다.
* 슬랙(Slack), 디스코드(Discord), 잔디(JANDI), 구글챗(Google Chat Space)을 지원합니다.
* Google Apps Script와 네이버 검색 오픈 API를 이용합니다.
*
* config.gs에서 뉴스봇 구동에 필요한 설정값들을 미리 삽입하신 뒤에 이용해주세요.
*
* - Github : https://github.com/seongjinme/naver-news-fetching-bot
* - 문의사항 : [email protected]
* ***********************************************************************************************/
/**
* 네이버 뉴스봇의 메인 실행 함수입니다.
* Google Apps Script 환경에서 실행 트리거를 설정하실 때 이 함수를 실행 대상으로 설정해 주세요.
*/
function runNewsFetchingBot() {
try {
const controller = new NewsFetchingBotController();
if (controller.isFirstRun()) {
controller.initiateFirstRun();
return;
}
if (controller.isKeywordsChanged()) {
controller.handleKeywordsChange();
}
if (CONFIG.DEBUG) {
controller.runDebug();
return;
}
if (controller.fetchNewsItems().length > 0) {
controller.deliverNewsItems();
controller.archiveNewsItems();
}
controller.updateProperties();
controller.printResults();
} catch (error) {
Logger.log(`[ERROR] 에러로 인해 뉴스봇 구동을 중지합니다. 아래 메시지를 참고해 주세요.`);
if (error instanceof PropertyError) {
Logger.log(`[ERROR] Google Apps Script 환경 오류 발생: ${error.message}`);
return;
}
if (error instanceof ConfigValidationError) {
Logger.log(`[ERROR] 뉴스봇 설정값 오류 발생: ${error.message}`);
return;
}
if (error instanceof NewsFetchError) {
Logger.log(`[ERROR] 뉴스 수신 중 오류 발생: ${error.message}`);
return;
}
if (error instanceof ProcessError) {
Logger.log(`[ERROR] 뉴스봇 실행 중 오류 발생: ${error.message}`);
return;
}
if (error instanceof InitializationError) {
Logger.log(`[ERROR] 뉴스봇 초기 설정 중 오류 발생: ${error.message}`);
return;
}
Logger.log(`[ERROR] 예상치 못한 오류 발생: ${error.message}`);
}
}
/**
* 뉴스봇 컨트롤러 클래스입니다.
*/
class NewsFetchingBotController {
/**
* NewsFetchingBotController의 생성자입니다.
*/
constructor() {
validateConfig(CONFIG);
const { searchKeywords, lastDeliveredNewsHashIds, lastDeliveredNewsPubDate, isFirstRun } =
this._getControllerProperties();
this._searchKeywords = searchKeywords || [...CONFIG.KEYWORDS];
this._lastDeliveredNewsHashIds = lastDeliveredNewsHashIds;
this._lastDeliveredNewsPubDate = lastDeliveredNewsPubDate || new Date().getTime();
this._isFirstRun = isFirstRun;
this._fetchingService = new FetchingService({
apiUrl: "https://openapi.naver.com/v1/search/news.json",
clientId: CONFIG.NAVER_API_CLIENT.ID,
clientSecret: CONFIG.NAVER_API_CLIENT.SECRET,
newsSource: NEWS_SOURCE,
lastDeliveredNewsHashIds: this._lastDeliveredNewsHashIds,
lastDeliveredNewsPubDate: this._lastDeliveredNewsPubDate,
});
this._messagingService = new MessagingService({
webhooks: this._getWebhooksByServices(),
newsCardGenerator: NewsCardGenerator,
messageGenerator: MessageGenerator,
});
this._archivingService = new ArchivingService({
isEnabled: CONFIG.ARCHIVING.IS_ENABLED,
sheetInfo: CONFIG.ARCHIVING.SHEET_INFO,
});
this._isArchivingOnlyMode =
Object.values(CONFIG.WEBHOOK).every(({ IS_ENABLED, _ }) => !IS_ENABLED) && CONFIG.ARCHIVING.IS_ENABLED;
}
/**
* 뉴스봇 최초 실행 여부를 반환합니다.
* @returns {boolean} 뉴스봇 최초 실행 여부
*/
isFirstRun() {
return this._isFirstRun;
}
/**
* 뉴스 검색 키워드가 변경되었는지 확인합니다.
* @returns {boolean} 키워드 변경 여부
*/
isKeywordsChanged() {
return this._searchKeywords && !isTwoArraysEqual(this._searchKeywords, CONFIG.KEYWORDS);
}
/**
* 뉴스 검색 키워드 변경을 처리합니다.
*/
handleKeywordsChange() {
this._searchKeywords = [...CONFIG.KEYWORDS];
PropertyManager.setProperty("searchKeywords", JSON.stringify(this._searchKeywords));
const message = `검색어 변경이 완료되었습니다. 이제부터 '${this._searchKeywords.join(", ")}' 키워드를 포함한 뉴스를 전송합니다.`;
Logger.log(`[INFO] ${message}`);
this._messagingService.sendMessage(`[네이버 뉴스봇] ${message}`);
}
/**
* 최초 실행 시 초기화 작업을 수행합니다.
* @throws {InitializationError} 초기화 중 오류 발생 시
*/
initiateFirstRun() {
try {
Logger.log("[INFO] 뉴스봇 초기 설정을 시작합니다.");
this._deliverSampleNews();
this._saveInitialProperties();
this._deleteAllTriggers();
this._initializeTriggerWithInterval();
this._sendWelcomeMessage();
} catch (error) {
throw new InitializationError(error.message);
}
}
/**
* 뉴스봇을 디버그 모드로 실행합니다.
*/
runDebug() {
try {
Logger.log(
"[INFO] DEBUG 모드가 켜져 있습니다.\n- 뉴스를 가져와 로깅하는 작업만 수행합니다.\n- 최근 뉴스 목록, 최종 게재 시각 등의 정보는 별도로 저장되지 않습니다.",
);
const fetchedNewsItems = this._fetchingService.fetchNewsItems({
searchKeywords: this._searchKeywords,
});
this._printFetchedNewsItems(fetchedNewsItems);
} catch (error) {
Logger.log(`[ERROR] DEBUG 모드 구동 중 오류 발생: ${error.message}`);
} finally {
Logger.log("[INFO] DEBUG 모드 구동이 완료되었습니다.");
}
}
/**
* 뉴스 항목을 가져옵니다.
* @returns {NewsItem[]} 가져온 뉴스 항목 목록
* @throws {NewsFetchError} 뉴스 가져오기 중 오류 발생 시
*/
fetchNewsItems() {
try {
return this._fetchingService.fetchNewsItems({
searchKeywords: this._searchKeywords,
});
} catch (error) {
throw new NewsFetchError(error.message);
}
}
/**
* 뉴스 데이터를 새로 받아온 뒤 채팅 서비스로 전송합니다.
*/
deliverNewsItems() {
try {
if (!this._isWebhookConfigured()) {
Logger.log("[INFO] 뉴스를 전송할 채팅 서비스가 설정되어 있지 않습니다. 다음 단계로 넘어갑니다.");
return;
}
const fetchedNewsItems = this._fetchingService.getNewsItems({ sortByDesc: false });
this._sendNewsItems(fetchedNewsItems);
Logger.log("[SUCCESS] 뉴스 항목 전송이 완료되었습니다.");
} catch (error) {
Logger.log(
`[ERROR] 뉴스 항목 전송 중 오류가 발생했습니다. 현재 작업을 종료하고 다음 단계로 넘어갑니다.\n오류 내용: ${error.message}`,
);
}
}
/**
* 인자로 받은 뉴스 항목들을 채팅 서비스로 전송합니다.
* @param {NewsItem[]} newsItems - 전송할 뉴스 항목들
* @private
*/
_sendNewsItems(newsItems) {
if (newsItems.length === 0) {
Logger.log("[INFO] 전송할 새 뉴스 항목이 없습니다.");
return;
}
this._messagingService.sendNewsItems(newsItems);
}
/**
* 뉴스 항목을 구글 시트로 전송하여 저장합니다.
*/
archiveNewsItems() {
if (!CONFIG.ARCHIVING.IS_ENABLED) {
Logger.log("[INFO] 뉴스를 저장할 구글 시트 정보가 설정되어 있지 않습니다. 다음 단계로 넘어갑니다.");
return;
}
try {
const newsItems = this._isArchivingOnlyMode
? this._fetchingService.getNewsItems({ sortByDesc: true })
: this._messagingService.getNewsItems({ sortByDesc: true });
if (newsItems.length === 0) {
Logger.log("[INFO] 저장할 새 뉴스 항목이 없습니다.");
return;
}
this._archivingService.archiveNewsItems(newsItems);
Logger.log("[SUCCESS] 뉴스 항목 저장이 완료되었습니다.");
} catch (error) {
Logger.log(
`[ERROR] 뉴스 항목 저장 중 오류가 발생했습니다. 현재 작업을 종료하고 다음 단계로 넘어갑니다.\n오류 내용: ${error.message}`,
);
}
}
/**
* 뉴스봇 구동에 필요한 설정값들을 업데이트하여 저장합니다.
*/
updateProperties() {
const newHashIds = this._isArchivingOnlyMode
? this._archivingService.newsHashIds
: this._messagingService.newsHashIds;
const newPubDate = this._isArchivingOnlyMode
? this._archivingService.latestNewsPubDate
: this._messagingService.latestNewsPubDate;
const lastDeliveredNewsHashIds =
newHashIds.length > 0 && newPubDate && newPubDate > this._lastDeliveredNewsPubDate
? newHashIds
: [...this._lastDeliveredNewsHashIds, ...newHashIds];
this.savePropertiesWithParams({
searchKeywords: this._searchKeywords,
lastDeliveredNewsHashIds,
lastDeliveredNewsPubDate: newPubDate ?? this._lastDeliveredNewsPubDate,
});
}
/**
* 개별 설정값을 {key: value} 형태로 받아 GAS의 PropertiesService를 경유하여 저장합니다.
* @param {Record<string, T>} params - 저장할 속성 객체
*/
savePropertiesWithParams(params) {
Object.entries(params).forEach(([key, value]) => {
PropertyManager.setProperty(key, JSON.stringify(value));
});
}
/**
* 뉴스봇 스크립트의 실행 결과를 출력합니다.
*/
printResults() {
if (CONFIG.DEBUG) {
Logger.log("[RESULT] DEBUG 모드 구동이 완료되었습니다.");
return;
}
if (this._fetchingService.newsItemsSize === 0) {
Logger.log("[RESULT] 새로 게재된 된 뉴스 항목이 없습니다. 작업을 종료합니다.");
return;
}
const resultNumber = this._isArchivingOnlyMode
? this._archivingService.newsItemsSize
: this._messagingService.newsItemsSize;
Logger.log(`[RESULT] 총 ${resultNumber}건의 뉴스 작업이 완료되었습니다.`);
}
/**
* 뉴스봇 컨트롤러 구동에 필요한 속성들을 PropertiesService로부터 가져옵니다.
* @typedef {Object} ControllerProperties
* @property {Array<string>|null} searchKeywords - 저장된 검색 키워드 목록
* @property {Array<string>} lastDeliveredNewsHashIds - 마지막으로 전달된 뉴스 항목의 해시 ID 목록
* @property {Date|null} lastDeliveredNewsPubDate - 마지막으로 전달된 뉴스의 발행 날짜
* @property {boolean} isFirstRun - 최초 실행 여부
* @returns {ControllerProperties}
* @private
*/
_getControllerProperties() {
const savedSearchKeywords = PropertyManager.getProperty("searchKeywords");
const savedLastDeliveredNewsHashIds = PropertyManager.getProperty("lastDeliveredNewsHashIds");
const savedLastDeliveredNewsPubDate = PropertyManager.getProperty("lastDeliveredNewsPubDate");
const savedInitializationCompleted = PropertyManager.getProperty("initializationCompleted");
return {
searchKeywords: savedSearchKeywords ? JSON.parse(savedSearchKeywords) : null,
lastDeliveredNewsHashIds: savedLastDeliveredNewsHashIds ? JSON.parse(savedLastDeliveredNewsHashIds) : [],
lastDeliveredNewsPubDate: savedLastDeliveredNewsPubDate
? new Date(JSON.parse(savedLastDeliveredNewsPubDate))
: null,
isFirstRun: !(savedInitializationCompleted && savedInitializationCompleted === "true"),
};
}
/**
* 뉴스를 전송할 채팅 서비스들의 웹훅 구성이 존재하는지 확인합니다.
* @returns {boolean} 웹훅 구성 여부
* @private
*/
_isWebhookConfigured() {
return Object.keys(this._getWebhooksByServices()).length > 0;
}
/**
* 웹훅 서비스 목록을 가져옵니다.
* @returns {Object} 웹훅 서비스 목록
* @private
*/
_getWebhooksByServices() {
return Object.entries(CONFIG.WEBHOOK)
.filter(([_, config]) => config.IS_ENABLED && config.URL.trim() !== "")
.reduce((webhooks, [key, config]) => {
webhooks[key] = config.URL;
return webhooks;
}, {});
}
/**
* 뉴스봇 스크립트 설치 과정에서 샘플 뉴스를 받아 전송합니다.
* @private
*/
_deliverSampleNews() {
const sampleNewsItems = this._fetchingService.fetchNewsItems({
searchKeywords: this._searchKeywords,
display: 1,
filterByPubDate: false,
});
if (sampleNewsItems.length <= 0) {
Logger.log("[INFO] 등록된 키워드로 기존에 게재된 뉴스가 아직 없습니다. 뉴스봇 설치를 계속 진행합니다.");
return;
}
const sampleNewsDeliverMessage =
"등록된 키워드별 샘플 뉴스를 전송합니다. 만약 기존에 게재된 뉴스가 아직 없다면 별도로 표시되지 않습니다.";
Logger.log(`[INFO] ${sampleNewsDeliverMessage}`);
this._messagingService.sendMessage(`[네이버 뉴스봇] ${sampleNewsDeliverMessage}`);
this._printFetchedNewsItems(sampleNewsItems);
if (!CONFIG.DEBUG) {
this._sendNewsItems(sampleNewsItems);
}
}
/**
* 뉴스봇의 첫 구동때 설정된 초기 설정값을 저장합니다.
* @private
*/
_saveInitialProperties() {
this.savePropertiesWithParams({
searchKeywords: this._searchKeywords,
lastDeliveredNewsHashIds: this._fetchingService.newsHashIds,
lastDeliveredNewsPubDate: this._fetchingService.latestNewsPubDate ?? this._lastDeliveredNewsPubDate,
initializationCompleted: true,
});
}
/**
* 뉴스 항목들을 GAS 환경의 Logger로 로깅하여 프린트합니다.
* @param {Object} params - 매개변수
* @param {NewsItem[]} params.newsitems - 뉴스 항목들
* @private
*/
_printFetchedNewsItems(newsItems) {
if (newsItems && newsItems.length > 0) {
newsItems.forEach((newsItem, index) => {
const { pubDateText, title, source, link, description, keywords } = newsItem.data;
Logger.log(`----- ${newsItems.length}개 항목 중 ${index + 1}번째 -----`);
Logger.log(
`게재시각: ${pubDateText}\n기사제목: ${title}\n기사출처: ${source}\n원문링크: ${link}\n본문내용: ${description}\n검색어: ${keywords.join(", ")}`,
);
});
Logger.log(`[INFO] ${newsItems.length}개 항목에 대한 로깅 작업을 완료했습니다.`);
return;
}
Logger.log("[INFO] 모든 키워드에 대해 검색된 뉴스가 없습니다. 로깅 작업을 종료합니다.");
}
/**
* GAS 프로젝트에 남아있는 기존 트리거를 제거하고, 뉴스봇 스크립트의 자동 실행 트리거를 설정합니다.
* @param {number} [intervalMinutes] - 분 단위 실행 간격 (1, 5, 10, 15, 30 중 택일)
* @throws {InitializationError} 트리거 설정 중 오류 발생 시
*/
_initializeTriggerWithInterval(intervalMinutes = 1) {
try {
ScriptApp.newTrigger("runNewsFetchingBot").timeBased().everyMinutes(intervalMinutes).create();
} catch (error) {
throw new InitializationError(error.message);
}
}
/**
* GAS 프로젝트에 남아있는 기존 트리거들을 모두 제거합니다.
* @throws {InitializationError} 트리거 제거 중 오류 발생 시
*/
_deleteAllTriggers() {
try {
const existingTriggers = ScriptApp.getProjectTriggers();
if (existingTriggers.length > 0) {
existingTriggers.forEach((trigger) => ScriptApp.deleteTrigger(trigger));
}
} catch (error) {
throw new InitializationError(error.message);
}
}
/**
* 뉴스봇 첫 구동 후 설치가 성공적으로 완료되었을 경우, 환영 메시지를 전송합니다.
* @private
*/
_sendWelcomeMessage() {
const welcomeMessage = `네이버 뉴스봇이 설치되었습니다. 앞으로 '${this._searchKeywords.join(", ")}' 키워드에 대한 최신 뉴스가 전송됩니다.`;
Logger.log(`[INFO] ${welcomeMessage}`);
if (!CONFIG.DEBUG) {
this._messagingService.sendMessage(`[네이버 뉴스봇] ${welcomeMessage}`);
}
}
}
/**
* NewsItem은 개별 뉴스 기사의 정보를 다루고 관리합니다.
*/
class NewsItem {
/**
* NewsItem 클래스의 생성자입니다.
* @param {Object} newsData - 뉴스 기사 정보
* @param {string} newsData.title - 기사 제목
* @param {string} newsData.link - 기사 링크
* @param {string} newsData.source - 기사 출처
* @param {string} newsData.description - 기사 설명
* @param {Date} newsData.pubDate - 기사 게재 시각
* @param {string} newsData.keyword - 기사 검색어
*/
constructor({ title, link, source, description, pubDate, keyword }) {
this._title = title;
this._link = link;
this._source = source;
this._description = description;
this._pubDate = pubDate;
this._keywords = [keyword];
this._hashId = this._createHashId({ newsItemUrl: link });
}
/**
* 뉴스 기사의 고유한 해시 ID값을 생성합니다.
* @param {Object} params - 매개변수
* @param {string} newsItemUrl - 뉴스 기사 URL 주소
* @param {number} hashIdLength - 생성할 해시 ID값의 길이
* @returns {string} 생성된 해시 ID값
*/
_createHashId({ newsItemUrl, hashIdLength = 8 }) {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 해싱 연산용 소수 및 모듈러 설정
const prime = 31;
const mod = 1e9 + 9;
let hash = Array.from({ length: newsItemUrl.length }).reduce((acc, _, index) => {
return (acc * prime + newsItemUrl.charCodeAt(index)) % mod;
}, 0);
return Array.from({ length: hashIdLength }).reduce((hashId) => {
const index = Math.abs(hash % characters.length);
hashId += characters[index];
hash = (hash * prime + index) % mod;
return hashId;
}, "");
}
/**
* 뉴스 기사에 대한 검색 키워드를 추가합니다.
* @param {string[]} keywords - 추가할 검색 키워드 항목
*/
addSearchKeyword(keywords) {
this._keywords = [...this._keywords, ...keywords];
}
/**
* 뉴스 기사의 고유한 해시 ID값을 반환합니다.
* @returns {string} 뉴스 기사의 해시 ID값
*/
get hashId() {
return this._hashId;
}
/**
* 뉴스 기사에 대한 검색 키워드 목록을 반환합니다.
* @returns {string[]} 뉴스 기사의 검색 키워드 목록
*/
get keywords() {
return [...this._keywords];
}
/**
* 뉴스 기사가 게재된 시각을 반환합니다.
* @returns {Date} 뉴스 기사의 게재 시각
*/
get pubDate() {
return this._pubDate;
}
/**
* 뉴스 기사의 데이터를 반환합니다.
* @typedef {Object} NewsItemData
* @property {string} title - 기사 제목
* @property {string} link - 기사 링크
* @property {string} source - 기사 출처
* @property {string} description - 기사 설명
* @property {string} pubDateText - 기사 발행일 문자열
* @property {string[]} keywords - 기사 검색어 목록
* @returns {NewsItemData}
*/
get data() {
return {
title: this._title,
link: this._link,
source: this._source,
description: this._description,
pubDateText: Utilities.formatDate(this._pubDate, "GMT+9", "yyyy-MM-dd HH:mm:ss"),
keywords: this.keywords,
};
}
/**
* 뉴스 기사의 데이터를 아카이빙용 포맷으로 반환합니다.
* @returns {string[]}
*/
get archivingData() {
const { pubDateText, title, source, link, description, keywords } = this.data;
return [pubDateText, title, source, link, description, keywords.join(", ")];
}
}
/**
* NewsItem 항목들을 관리하는 맵 클래스입니다.
*/
class NewsItemMap {
/**
* NewsItemMap 클래스의 생성자입니다.
*/
constructor() {
this._newsItemsMap = new Map();
}
/**
* 뉴스 항목을 맵에 추가합니다. 이미 존재하는 항목의 경우 검색 키워드만 업데이트합니다.
* @param {NewsItem} newsItem - 추가할 뉴스 항목
*/
addNewsItem(newsItem) {
const existingItem = this._newsItemsMap.get(newsItem.hashId);
if (existingItem) {
existingItem.addSearchKeyword(newsItem.keywords);
return;
}
this._newsItemsMap.set(newsItem.hashId, newsItem);
}
/**
* 여러 뉴스 항목을 한 번에 맵에 추가합니다.
* @param {NewsItem[]} newsItems - 추가할 뉴스 항목 배열
*/
addNewsItems(newsItems) {
newsItems.forEach((newsItem) => this.addNewsItem(newsItem));
}
/**
* 맵에 저장된 모든 뉴스 항목을 조건에 따라 정렬된 배열로 반환합니다.
* @param {Object} params - 정렬 조건
* @param {boolean} [params.sortByDesc] - 시간 역순 정렬 여부
* @returns {NewsItem[]} 모든 뉴스 항목의 정렬된 배열
*/
getNewsItems({ sortByDesc }) {
if (this._newsItemsMap.size === 0) {
return [];
}
const compareFunction = sortByDesc ? (a, b) => b.pubDate - a.pubDate : (a, b) => a.pubDate - b.pubDate;
return [...this._newsItemsMap.values()].sort(compareFunction);
}
/**
* 맵에 저장된 모든 뉴스 항목의 해시 ID를 배열로 반환합니다.
* @returns {string[]} 모든 뉴스 항목의 해시 ID 배열
*/
get newsHashIds() {
return [...this._newsItemsMap.keys()];
}
/**
* 맵에 저장된 뉴스 항목의 개수를 반환합니다.
* @returns {number} 저장된 뉴스 항목의 개수
*/
get size() {
return this._newsItemsMap.size;
}
/**
* 맵에 저장된 뉴스 항목들로부터 가장 최근의 pubDate를 추출합니다.
* @returns {Date|null} 가장 최근의 pubDate, 만약 Map이 비어있을 경우는 null
*/
get latestNewsPubDate() {
if (this._newsItemsMap.size === 0) return null;
return [...this._newsItemsMap.values()].reduce(
(latest, newsItem) => (newsItem.pubDate > latest ? newsItem.pubDate : latest),
new Date(0),
);
}
/**
* 맵에 저장된 모든 뉴스 항목을 제거합니다.
*/
clear() {
this._newsItemsMap.clear();
}
}
/**
* BaseNewsService는 뉴스 관련 서비스들의 기본 클래스로, 뉴스 데이터 관리를 위한 공통 기능을 제공합니다.
* FetchingService, MessagingService, ArchivingService가 이 클래스를 상속받아 사용합니다.
*/
class BaseNewsService {
/**
* BaseNewsService의 생성자입니다.
* NewsItemMap 인스턴스를 초기화합니다.
*/
constructor() {
/**
* 뉴스 아이템들을 저장하고 관리하는 NewsItemMap 인스턴스입니다.
* @protected
* @type {NewsItemMap}
*/
this._newsItems = new NewsItemMap();
}
/**
* 저장된 뉴스 아이템들을 반환합니다.
* @param {Object} options - 정렬 옵션
* @param {boolean} [options.sortByDesc] - true일 경우 내림차순으로 정렬
* @returns {NewsItem[]} 뉴스 아이템 배열
*/
getNewsItems({ sortByDesc }) {
return this._newsItems.getNewsItems({ sortByDesc });
}
/**
* 저장된 뉴스 아이템들의 해시 ID 배열을 반환합니다.
* @returns {string[]} 뉴스 아이템 해시 ID 배열
*/
get newsHashIds() {
return this._newsItems.newsHashIds;
}
/**
* 저장된 뉴스 아이템 중 가장 최근의 발행 날짜를 반환합니다.
* @returns {Date|null} 가장 최근 뉴스의 발행 날짜, 또는 뉴스가 없는 경우 null
*/
get latestNewsPubDate() {
return this._newsItems.latestNewsPubDate;
}
/**
* 저장된 뉴스 아이템의 개수를 반환합니다.
* @returns {number} 뉴스 아이템 개수
*/
get newsItemsSize() {
return this._newsItems.size;
}
}
/**
* FetchingService는 네이버 오픈 API를 통해 검색어가 포함된 뉴스 기사를 가져와 처리합니다.
*/
class FetchingService extends BaseNewsService {
/**
* FetchingService 클래스의 생성자입니다.
* @param {Object} params - 생성자 매개변수
* @param {string} params.apiUrl - 네이버 뉴스 검색 API URL
* @param {string} params.clientId - 네이버 API 클라이언트 ID
* @param {string} params.clientSecret - 네이버 API 클라이언트 시크릿
* @param {Object} params.newsSource - 뉴스 소스 목록
* @param {string[]} lastDeliveredNewsHashIds - 마지막으로 전송 완료된 뉴스 항목들의 해시 ID 배열
* @param {Date} lastDeliveredNewsPubDate - 마지막으로 전송 완료된 뉴스 항목의 게재 시각
*/
constructor({ apiUrl, clientId, clientSecret, newsSource, lastDeliveredNewsHashIds, lastDeliveredNewsPubDate }) {
super();
this._apiUrl = apiUrl;
this._fetchOptions = {
method: "get",
headers: {
"X-Naver-Client-Id": clientId,
"X-Naver-Client-Secret": clientSecret,
},
};
this._newsSourceFinder = new NewsSourceFinder(newsSource);
this._lastDeliveredNewsHashIds = [...lastDeliveredNewsHashIds];
this._lastDeliveredNewsPubDate = lastDeliveredNewsPubDate;
}
/**
* 검색어들이 포함된 최신 뉴스 항목들을 가져옵니다.
* @param {Object} params - 최신 뉴스 검색 옵션
* @param {string[]} params.searchKeywords - 검색어 목록
* @param {number} [params.display] - 각 검색어별 뉴스 검색 수
* @param {boolean} [params.sortByDesc] - 뉴스 항목들의 시간 역순 정렬 여부
* @param {boolean} [params.filterByPubDate] - 최근 뉴스 전송 시간에 따른 필터링 여부
* @returns {NewsItem[]} 새로 가져온 뉴스 항목들
*/
fetchNewsItems({ searchKeywords, display, sortByDesc, filterByPubDate = true }) {
searchKeywords.forEach((searchKeyword) => {
this._fetchNewsItemsForEachKeyword({ searchKeyword, display, filterByPubDate });
});
return this.getNewsItems({ sortByDesc });
}
/**
* 단일 검색어에 대한 뉴스 항목들을 가져옵니다.
* @param {Object} params - 단일 검색어 뉴스 검색 옵션
* @param {string} params.searchKeyword - 검색어
* @param {number} [params.display] - 검색어에 대한 뉴스 검색 수
* @param {boolean} [params.filterByPubDate] - 최근 뉴스 전송 시간에 따른 필터링 여부
* @private
*/
_fetchNewsItemsForEachKeyword({ searchKeyword, display, filterByPubDate }) {
const fetchUrl = this._createFetchUrl({ searchKeyword, display });
const fetchedNewsItems = this._fetchNewsItemsFromAPI(fetchUrl);
if (fetchedNewsItems.length === 0) return;
const newsItems = fetchedNewsItems
.map((newsItem) => this._createNewsItem({ newsItem, searchKeyword }))
.filter(
(newsItem) =>
!this._lastDeliveredNewsHashIds.includes(newsItem.hashId) &&
(!filterByPubDate || this._isAfterLatestNewsItem({ newsPubDate: newsItem.pubDate })),
);
if (newsItems.length === 0) return;
this._newsItems.addNewsItems(newsItems);
}
/**
* API에서 데이터를 가져오고 파싱합니다.
* @param {string} fetchUrl - API 요청 URL
* @returns {Object[]} 파싱된 JSON 응답 데이터
* @throws {Error} API 요청이 실패하거나 응답 코드가 200번대가 아닐 경우
* @private
*/
_fetchNewsItemsFromAPI(fetchUrl) {
const fetchedData = UrlFetchApp.fetch(fetchUrl, this._fetchOptions);
const fetchedDataResponseCode = fetchedData.getResponseCode();
if (fetchedDataResponseCode < 200 || fetchedDataResponseCode > 299) {
throw new NewsFetchError(fetchedData.getContentText());
}
return JSON.parse(fetchedData).items || [];
}
/**
* 뉴스 기사의 발행일이 지정된 시간 이후인지 확인합니다.
* @param {Object} params - 매개변수
* @param {Date} newsPubDate - 뉴스 게재 시각
* @param {number} [subsetTime] - 발행일 기준 시각에서 추가로 뺄 밀리초 단위 시간 (선택)
* @returns {boolean} 뉴스 기사의 발행일이 지정된 시간 이후인 경우 true, 그렇지 않은 경우 false
*/
_isAfterLatestNewsItem({ newsPubDate, subsetTime }) {
const subsetTimeAmount = subsetTime && !Number.isNaN(subsetTime) ? subsetTime : 0;
return newsPubDate.getTime() >= this._lastDeliveredNewsPubDate.getTime() - subsetTimeAmount;
}
/**
* 뉴스 항목 객체를 생성합니다.
* @param {Object} params - 매개변수
* @param {Object} params.newsItem - API로부터 받아온 뉴스 항목 데이터
* @param {string} params.searchKeyword - 해당 뉴스 항목의 검색어
* @returns {NewsItem} 생성된 NewsItem 객체
* @private
*/
_createNewsItem({ newsItem, searchKeyword }) {
return new NewsItem({
title: getBleachedText(newsItem.title),
link: newsItem.link,
source: this._newsSourceFinder.getSourceByLink(newsItem.originallink),
description: getBleachedText(newsItem.description),
pubDate: new Date(newsItem.pubDate),
keyword: searchKeyword,
});
}
/**
* API 요청을 위한 URL을 생성합니다.
* @param {Object} params - 매개변수
* @param {string} params.searchKeyword - 검색어
* @param {number} [params.startIndex=1] - 검색 시작 인덱스
* @param {number} [params.display=100] - 한 번에 가져올 뉴스 항목 수
* @returns {string} 생성된 API 요청 URL
* @private
*/
_createFetchUrl({ searchKeyword, startIndex = 1, display = 100 }) {
const searchParams = objectToQueryParams({
query: searchKeyword,
start: startIndex,
display,
sort: "date",
});
return `${this._apiUrl}?${searchParams}`;
}
}
/**
* 다양한 채널로 메시지와 뉴스 아이템을 전송하는 서비스 클래스입니다.
*/
class MessagingService extends BaseNewsService {
/**
* MessagingService 클래스의 생성자입니다.
* @param {Object} params - 설정 객체
* @param {Object.<string, string>} params.webhooks - 채널별 웹훅 URL 객체
* @param {Object} params.newsCardGenerator - 뉴스 카드 생성기 객체
* @param {Object} params.messageGenerator - 메시지 생성기 객체
*/
constructor({ webhooks, newsCardGenerator, messageGenerator }) {
super();
this._webhooks = { ...webhooks };
this._newsCardGenerator = newsCardGenerator;
this._messageGenerator = messageGenerator;
this._defaultParams = {
method: "post",
contentType: "application/json",
};
}
/**
* 여러 채널로 뉴스를 전송하고, 전송 완료된 뉴스 항목을 저장합니다.
* @param {NewsItem[]} newsItems - 전송할 뉴스 아이템 배열
*/
sendNewsItems(newsItems) {
newsItems.forEach(async (newsItem) => {
this._sendNewsItemToChannels(newsItem);
this._newsItems.addNewsItem(newsItem);
// 채팅 솔루션별 초당/분당 request 횟수 제한을 고려하여 다음 항목 처리 전에 일시 중지 시간을 부여합니다.
await sleep(50);
});
}
/**
* 여러 채널로 개별 뉴스 아이템을 전송합니다.
* @param {NewsItem} newsItem - 전송할 뉴스 아이템
* @private
*/
_sendNewsItemToChannels(newsItem) {
Object.entries(this._webhooks).forEach(([channel, webhookUrl]) => {
const payload = this._newsCardGenerator[toCamelCase(channel)](newsItem.data);
this._sendToChannel({ channel, webhookUrl, payload });
});
}
/**
* 여러 채널로 메시지를 전송합니다.
* @param {string} message - 전송할 메시지
*/
sendMessage(message) {
Object.entries(this._webhooks).forEach(([channel, webhookUrl]) => {
const payload = this._messageGenerator[toCamelCase(channel)](message);
this._sendToChannel({ channel, webhookUrl, payload });
});
}
/**
* 특정 채널로 페이로드를 전송합니다.
* @param {Object} params - 매개변수 객체
* @param {string} params.channel - 채널 이름
* @param {string} params.webhookUrl - 웹훅 URL
* @param {Object} params.payload - 전송할 페이로드
* @private
*/
_sendToChannel({ channel, webhookUrl, payload }) {
const params = {
...this._defaultParams,
payload: JSON.stringify(payload),
};
if (channel === "JANDI") {
params.header = {
Accept: "application/vnd.tosslab.jandi-v2+json",
};
}
const fetchResponse = UrlFetchApp.fetch(webhookUrl, params);
const fetchResponseCode = fetchResponse.getResponseCode();
if (fetchResponseCode < 200 || fetchResponseCode > 299) {
throw new ProcessError(fetchResponse.getContentText());
}
}
}
/**
* 뉴스 아이템을 구글 시트에 저장하는 서비스 클래스입니다.
*/
class ArchivingService extends BaseNewsService {
/**
* ArchivingService 클래스의 생성자입니다.
* @param {Object} params - 생성자 매개변수
* @param {boolean} params.isEnabled - 구글 시트 저장 기능 사용 여부
* @param {Object} params.sheetInfo - 구글 시트 설정 정보
* @param {string} params.sheetInfo.URL - 스프레드시트 URL
* @param {string} params.sheetInfo.NAME - 워크시트 이름
*/
constructor({ isEnabled, sheetInfo }) {
super();
this._isEnabled = isEnabled;
this._spreadSheet = isEnabled ? this._getSpreadSheet(sheetInfo.URL) : null;
this._workSheet = this._spreadSheet && isEnabled ? this._getOrCreateWorkSheet(sheetInfo.NAME || "뉴스피드") : null;
this._workSheetTargetCell = `${sheetInfo.NAME || "뉴스피드"}!A2`;
}
/**
* 스프레드시트 객체를 가져옵니다.
* @param {string} spreadSheetUrl - 스프레드시트 문서 URL
* @returns {GoogleAppsScript.Spreadsheet.Spreadsheet|null} 스프레드시트 객체 (없을 경우 null)
* @private
*/
_getSpreadSheet(spreadSheetUrl) {
try {
const spreadSheetId = getSpreadSheetId(spreadSheetUrl);
if (!spreadSheetId) return null;
return SpreadsheetApp.openById(spreadSheetId);
} catch (error) {
throw new ProcessError(error.message);
}
}
/**
* 워크시트를 가져오거나 새로 생성합니다.
* @param {string} workSheetName - 워크시트 이름
* @returns {GoogleAppsScript.Spreadsheet.Sheet} 워크시트 객체
* @private
*/
_getOrCreateWorkSheet(workSheetName) {