자산뿌울리기/개발일지

[TelegramAlarm] 텔래그램으로 알림 보내기 (3)

narmeee 2023. 5. 1. 00:53

텔레그램 봇 만들기

 

[Node.js] 텔레그램 봇 만들기

준비물 Node.js node-telegram-bot-api telegram account 1. 봇의 아버지에게 귀중한 자식하나만 빌려줍쇼 부탁하기. 검색창에 BotFather 를 검색하면 봇아버지가 등장한다. 우리는 봇을 하나 받으면 된다. /newbot

ssunarme.tistory.com

 

봇을 하나 데려왔으니 열심히 일을 시켜보자!

 

봇과 내가 있을 채널을 하나 파준다. 그리고 채널에 봇을 초대해 준다.

그다음 초대한 채널에 봇이 메시지를 보내게 하는 게 목표다

잘되라 잘되라!!

 

봇이 채널에 메시지를 보내려면 메시지를 보낼 채널의 아이디가 필요하다.

채널 아이디를 알아내기 위해서 getUpdates API를 사용한다.

getUpdates
Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.

https://api.telegram.org/bot <APIToken>/getUpdates

 

요청은 제대로 된것 같은데 result에 아무것도 없는 것을 볼 수 있다.

봇과 한게 없기 때문이다. 채널 번호를 알아내기 위해서 초대한 채널에 아무 메시지를 보낸 뒤 다시 요청한다.

channel_post를 보면 id가 있는데 이게 채널의 아이디다. 채널 id를 통해서 어느 채널에 메시지를 보낼지 결정할 수 있다.

 

{
    "ok": true,
    "result": [{
        "update_id": 204941242,
        "channel_post": {
            "message_id": 4,
            "sender_chat": {
                "id": -123456789,
                "title": "BOT-TEST",
                "type": "channel"
            },
            "chat": {
                "id": -123456789,
                "title": "BOT-TEST",
                "type": "channel"
            },
            "date": 1682880023,
            "text": "hello"
        }
    }]
}

 

 

// npm 모듈 호출
const TelegramBot = require('node-telegram-bot-api');

// `botFather`가 제공한 `token`으로 API 통신에 사용한다
const token= 'TOKEN ID'; // <--- 나의 Token
const channelId = 'CHANNEL ID';
const bot = new TelegramBot(token, {polling: true});
  
String.prototype.format = function() {
	var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};
  
test = {
    "FRONT": {
        "base": "bithumb",
        "kimp": "-0.44",
        "from": "binance",
        "avgBuyPrice": "271.1",
        "to": "bithumb",
        "avgSellPrice": "303.2",
        "qty": 25433.5333,
        "profit": 816416.41893,
        "diff": 11.84
    }
};
coin = 'FRONT';
exr = 1341;
date = new Date();
message = "<b>{0}({1}%)</b>\n".format(coin, test[coin].diff.toFixed(2));
message += "<b>{0} -> {1} </b>\n".format(test[coin].from, test[coin].to);
message += "<b>예상 수익 : {0}</b>\n".format(test[coin].profit.toFixed(0));
message += "두 거래소 간 김프(기준 {0}) : {1}\n".format(test[coin].base, test[coin].kimp)
message += "평균 구매가 : {0}(${1})\n".format(test[coin].avgBuyPrice, (test[coin].avgBuyPrice / exr).toFixed(7));
message += "평균 판매가 : {0}(${1})\n".format(test[coin].avgSellPrice, (test[coin].avgSellPrice / exr).toFixed(7));
message += "구매 금액 : {0}\n".format((test[coin].avgBuyPrice * test[coin].qty).toFixed(0));
message += "수량 : {0}\n".format(test[coin].qty.toFixed(0));
message += date.toLocaleString('ko-kr');

function send(message){
    options = {'parse_mode' : 'HTML'};
    bot.sendMessage(channelId, message, options = options);
}

send(message);
  
module.exports = {
  send,
};

테스트해 보면 잘 도착하는 걸 볼 수 있다. 

API문서를 보면 메세지를 보낼 때 알림 여부, 팝업창여부를 설정할 수도 있다.

사용하면서 개선해야할 점들을 다음 글 주제로 해야겠다...

일단 개발 끝!