Skip to main content

2021년 8월

2021-08-03#

즉시 실행 함수#


  • 함수의 정의와 동시에 실행되는 함수를 즉시 실행 함수(IIFE, Immediately Invoke Function Expression)라고 한다. 최초 한 번만 호출되며 다시 호출할 수는 없다. 이러한 특징을 이용하여 최초 한 번만 실행이 필요한 초기화 처리 등에 사용할 수 있다.

  • 자바스크립트에서 가장 큰 문제점 중의 하나는 파일이 분리되어 있다 하여도 글로벌 스코프가 하나이며 글로벌 스코프에 선언된 변수나 함수는 코드 내의 어디서든지 접근이 가능하다. 따라서 다른 스크립트 파일 내에서 동일한 이름으로 명명된 변수나 함수가 같은 스코프 내에 존재할 경우 원치 않는 결과를 가져올 수 있다.

즉시 실행 함수 내에 처리 로직을 모아 두면 혹시 있을 수도 있는 변수명 또는 함수 명의 충돌을 방지할 수 있어 이를 위한 목적으로 즉시 실행 함수를 사용되기도 한다.

익명 즉시 실행 함수#

(function () {
var a = 3;
var b = 5;
return a * b;
})();

기명 즉시 실행 함수#

  • 함수 내부에서 자신을 호출 할 경우 사용한다.
(function myFunction() {
var a = 3;
var b = 5;
return a * b;
})();

Error#

// SyntaxError: Unexpected token (
// 함수선언문은 자바스크립트 엔진에 의해 함수 몸체를 닫는 중괄호 뒤에 ;가 자동 추가된다.
function () { // ...
}(); // => };();

다른 방식#

!(function () {
var a = 3;
var b = 5;
return a * b;
})();
+(function () {
var a = 3;
var b = 5;
return a * b;
})();
-(function () {
var a = 3;
var b = 5;
return a * b;
})();
~(function () {
var a = 3;
var b = 5;
return a * b;
})();
~~(function () {
var a = 3;
var b = 5;
return a * b;
})();

2021-08-10#

구조 분해 할당(destructuring assignment)#


  • 객체나 배열을 변수로 분해할 수 있게 해주는 특별한 문법

배열 분해하기#

let arr = ['홍', '길동'];
let [surname, givenName] = arr;
console.log(surname); // "홍"
console.log(givenName); // "길동"
  • 문자열 분해 해서 할당하기
let [surname, givenName] = '홍 길동'.split(' ');
console.log(surname); // "홍"
console.log(givenName); // "길동"
  • 쉼표를 사용하여 요소 무시하기
let [a, , b, c] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(a); // 1
console.log(b); // 3
console.log(c); // 4
  • 변수 교환 트릭
let guest = 'Jane';
let admin = 'Pate';
[guest, admin] = [admin, guest];
console.log(admin); // "Pate"
console.log(guest); // "Jane"
  • ...로 나머지 요소 가져오기
let [A, B, C, ...D] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(D); // [4,5,6,7,8,9,10]
  • 할당하고자 하는 변수의 개수가 분해하고자 하는 배열의 길이보다 많은 경우
let [A, B] = [];
console.log(A); // undefined
console.log(B); // undefined
  • 할당할 값이 없을 때 기본으로 할당해 줄 값 설정하기
let [name = 'Guest', surname = 'Anonymous'] = ['Julius'];
console.log(name); // "Julius"
console.log(surname); // "Anonymous"

객체 분해하기#

let options = {
title: 'Menu',
width: 100,
height: 200,
};
let { title, width, height } = options;
console.log(title); // "Menu"
console.log(width); // 100
console.log(height); // 200
  • 변수의 순서는 중요하지 않다.
let options = {
title: 'Menu',
width: 100,
height: 200,
};
let { width, height, title } = options;
// {options.width, options.height, options.title}
console.log(title); // "Menu"
console.log(width); // 100
console.log(height); // 200
  • 객채 프로퍼티를 프로퍼티 키와 다른 이름을 가지는 변수에 할당 하는법
let options = {
title: 'Menu',
width: 100,
height: 200,
};
let { width: w, height: h, title } = options;
console.log(title); // "Menu"
console.log(w); // 100
console.log(h); // 200
  • 프로퍼티가 없는 경우를 대비하여 =을 사용해 기본값을 설정하기
let options = {
title: 'Menu',
};
let { width = 100, height = 200, title } = options;
console.log(title); // "Menu"
console.log(width); // 100
console.log(height); // 200
  • 콜론과 할당 연산자를 동시에 사용할 수 있다.
let options = {
title: 'Menu',
};
let { width: w = 100, height: h = 200, title } = options;
console.log(title); // "Menu"
console.log(w); // 100
console.log(h); // 200
  • 나머지 패턴...를 사용하여 나머지 프로퍼티를 할당하기
  • IE를 비롯한 몇몇 구식 브라우저는 나머지 패턴을 지원하지 않으므로 주의해서 사용해야 한다. 바벨(Babel)을 이용할 경우 사용 가능
let options = {
title: 'Menu',
width: 100,
height: 200,
};
let { title, ...rest } = options;
console.log(rest); // {width: 100, height: 200}
  • 기존 변수에 할당하기
  • ( )를 생략하면 코드 블록으로 인식하여 에러 발생
let title, width, height;
let options = {
title: 'Menu',
width: 100,
height: 200,
};
({ title, width, height } = options);
console.log(title); // "Menu"
console.log(width); // 100
console.log(height); // 200
  • 중첩 구조 분해
let options = {
size: {
width: 100,
height: 200,
},
items: ['Cake', 'Donut'],
extra: true,
};
// 코드를 여러 줄에 걸쳐 작성해 의도하는 바를 명확히 드러냄
let {
size: {
// size는 여기,
width,
height,
},
items: [item1, item2], // items는 여기에 할당함
title = 'Menu', // 분해하려는 객체에 title 프로퍼티가 없으므로 기본값을 사용함
} = options;
console.log(title); // "Menu"
console.log(width); // 100
console.log(height); // 200
console.log(item1); // "Cake"
console.log(item2); // "Donut"
  • 함수 매개변수에 사용하기
// 함수에 전달할 객체
let options = {
title: 'My menu',
items: ['Item1', 'Item2'],
};
// 함수는 전달받은 객체를 분해해 변수에 즉시 할당함
function showMenu({ title = 'Untitled', width = 200, height = 100, items = [] }) {
// title, items – 객체 options에서 가져옴
// width, height – 기본값
console.log(`${title} ${width} ${height}`); // My Menu 200 100
console.log(items); // Item1, Item2
}
showMenu(options);

2021-08-24#

discord bot 만들기#


  1. bot 생성하고 초대하기
  2. discord.js 패키지 설치하기
  3. discord bot 온라인 상태로 만들기

bot 생성하고 초대하기#

디스코드 개발자 포털 https://discord.com/developers/applications

  1. 어플리케이션 생성 newapplication.png

  2. 이름설정 create-an-application.png

  3. bot 생성하기 add-bot.png

  4. token 확인하기 token.png

  5. bot 초대 url 만들기 url.png

  6. 봇 권한 설정하기 bot.png

  7. 개발자모드 설정하기 image.png

discord.js 패키지 설치하기#

discord.js 공식 페이지 https://discord.js.org/#/

npm install npm-install.png

discord.js 13버전은 Node 16.6 이상이 필요함.

discord bot 온라인 상태로 만들기#

package.json

{
"dependencies": {
"@discordjs/builders": "^0.5.0",
"@discordjs/rest": "^0.1.0-canary.0",
"@discordjs/voice": "^0.6.0",
"discord-api-types": "^0.22.0",
"discord.js": "^13.1.0"
},
"name": "discord-bot",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js",
"serve": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}

index.js

const { Client, Intents} = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
const { token } = require("./config.json");
client.once('ready', () => {
console.log("준비 완료!")
})
client.login(token);

2021-08-31#

Papago API를 활용한 번역기 bot 만들기#


Papago API 활용하기#

Papago API를 사용하기 위해서는 NAVER Developers 사이트에서 어플리케이션 등록을 해야 한다.

NAVER Developers: https://developers.naver.com/main/

00.png

애플리케이션 등록 방법은 아래 링크에서 확인할수 있다.

사전 준비사항: https://developers.naver.com/docs/common/openapiguide/appregister.md

000.png

애플리케이션 등록하기#

https://developers.naver.com/apps/#/wizard/register

01.png

  1. 애플리케이션 이름 부분에 자신의 애플리케이션 이름을 작성하면 됩니다.

02.png

  1. 사용할 API를 목록에서 고르면 됩니다. 중복 선택 가능!

03.png

  1. 오픈 API 서비스 환경을 설정해 주시면 됩니다.

04.png

Client ID와 Client Secret는 API를 호출할 때 사용하기 때문에 따로 잘 적어둬야 합니다.

Papago API를 사용하여 번역기 Bot 만들기#

메시지가 입력되면 발생되는 이벤트 확인해보기#

client.on('messageCreate', (msg) => {
if (msg.content === 'ping') {
msg.channel.send({ content: 'pong' });
}
});

메시지가 생성될 때마다 messageCreate 이벤트가 발생합니다. mssageCreate 이벤트는 많은 정보를 가지고 있습니다.

다양한 API들은 https://discord.js.org/#/docs/main/stable/general/welcome에서 확인할 수 있습니다.

메시지 창에 hello 라 입력할 경우

Message {
channelId: '882114126015496212',
guildId: '879514647730999357',
deleted: false,
id: '882123964833464362',
type: 'DEFAULT',
system: false,
content: 'hello',
author: User {
id: '879513306090590238',
bot: false,
system: false,
flags: UserFlags { bitfield: 0 },
username: '박병규',
discriminator: '4378',
avatar: null
},
pinned: false,
tts: false,
nonce: '882123964548120576',
embeds: [],
components: [],
attachments: Collection(0) [Map] {},
stickers: Collection(0) [Map] {},
createdTimestamp: 1630385142287,
editedTimestamp: null,
reactions: ReactionManager { message: [Circular *1] },
mentions: MessageMentions {
everyone: false,
users: Collection(0) [Map] {},
roles: Collection(0) [Map] {},
_members: null,
_channels: null,
crosspostedChannels: Collection(0) [Map] {},
repliedUser: null
},
webhookId: null,
groupActivityApplication: null,
applicationId: null,
activity: null,
flags: MessageFlags { bitfield: 0 },
reference: null,
interaction: null
}

이런 객체가 반환이 되는데 이걸 활용하여 간단한 응답을 해주는 코드를 작성해 보겠습니다.

client.on('messageCreate', (msg) => {
console.log(msg);
if (msg.content === 'ping') {
msg.channel.send({ content: 'pong' });
}
});

위 코드는 채팅창에 ping이라고 입력을 해주면 bot이 pong이라고 답장을 해주는 코드입니다.

이걸 활용해서 번역을 해주는 코드를 작성해 보도록 하겠습니다.

Papago API 사용하기#

const request = require('request');
// api 요청 변수
const api_url = 'https://openapi.naver.com/v1/papago/n2mt';
const client_id = 'your-client-id';
const client_secret = 'your-client-secret-key';
const query = 'papago open api translation success!';
// api 요청 옵션 (번역: 영어 -> 한글)
const options = {
url: api_url,
form: { source: 'en', target: 'ko', text: query },
headers: {
'X-Naver-Client-Id': client_id,
'X-Naver-Client-Secret': client_secret,
},
};
// api 요청 보내고 콜백으로 결과 받기
request.post(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body));
} else {
console.log('error = ' + response.statusCode);
}
});

Papago API를 활용해 메시지 번역해주기#

transelate(api_url, msg.content, papagoId, papagoSecret, msg);
function transelate(api_url, content, client_id, client_secret, msg) {
// api 요청 옵션 (번역: 영어 -> 한글) // https://developers.naver.com/docs/papago/papago-nmt-api-reference.md 에서 API래퍼런스 확인 가능
let translatedText;
const options = {
url: api_url,
form: { source: 'en', target: 'ko', text: content },
headers: {
'X-Naver-Client-Id': client_id,
'X-Naver-Client-Secret': client_secret,
},
};
// api 요청 보내고 콜백으로 결과 받기
request.post(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
translatedText = JSON.parse(body).message.result.translatedText;
msg.channel.send({ content: `result: ${translatedText}` }); // 결과값 메시지로 출력해주기
} else {
console.log('error = ' + response.statusCode);
}
});
}