> Tesilio's Blog
기록하는 공간
기록하는 공간
Bot이나 bot으로 끝나야 한다.TestBot 혹은 test_bot사용자의 메세지를 받아 처리하여 응답하는 봇을 만들고 싶다면 서버가 필요하다. 요즘 대세는 서버리스니까 AWS API Gateway + Lambda 를 이용하여 엔드포인트(URL)를 하나 생성한다.
# \<token\> 부분을 봇 등록 시 발급받은 토큰으로 대치한다.
# 웹훅 URL 등록
curl -F "url=https://test.execute-api.ap-northeast-2.amazonaws.com/bot/" https://api.telegram.org/bot\<token\>/setWebhook
# 등록되어 있는 모든 웹훅 URL 삭제
curl https://api.telegram.org/bot\<token\>/setWebhook
필요 모듈
node-telegram-bot-api
특정 메세지를 받으면 응답하는 예제이다.
응답 http status code가 200이 아니면 성공할때까지 요청이 들어온다. 그러니 에러핸들링을 잘 해야 한다.
"use strict";
const TelegramBotApi = require("node-telegram-bot-api");
const bot = TelegramBotApi(\<token\>);
exports.handler = async (event, context) => {
let response;
response.statusCode = 200;
const requestBody = JSON.parse(event.body);
try {
const message = requestBody.message;
if (message.text === "반갑다") {
const chatId = message.chat.id;
await bot.sendMessage(chatId, "저도 반가워요");
}
} catch (e) {
console.error(`Error: $\{e\}`);
const chatId = requestBody.message.chat.id;
await bot.sendMessage(chatId, "잘못된 요청이거나 서버 에러입니다!");
}
return response;
}