(4)에서 Telegram Webhook를 이용해 사용자가 메시지를 보냈을 때 봇이 바로 응답할 수 있게 만들었습니다.
그러나 그대로 사용한다면 이 봇은 영원히 BTCUSDT만 응답할 것입니다. 그래서 사용자가 요청하는 코인의 현재가를 요청할 수 있게 만들어야 합니다.
Binance만 요청받기에는 부족한 부분이 있어 국내 대표코인 거래소인 Upbit도 함께 사용할 것입니다.
먼저 커맨드와 문자열을 분리하려면 정규식을 사용해도 되지만 저는 간단하게 String.substring()을 이용할 것입니다. 또한 Upbit와 Binance와 요청하는 방식이 다르기 때문에 분류되어야합니다. 그래서 String.includes()도 함께 사용하겠습니다.
Upbit GET
Upbit에 GET방식으로 요청하는 방식은 다음과 같습니니다.
'https://api.upbit.com/v1/ticker?markets=KRW-BTC'
먼저 Apps Script를 열고 doPost(e)에서 진행합니다.
function doPost(e) {
let contents = JSON.parse(e.postData.contents)
let id = contents.message.from.id
let msg = contents.message.text
let response = ''
let text = ''
let coin = ''
}
사용자가 예를들어 /binance BTCUSDT라고 요청했을 때 doPost(e)에서 먼저 해당 메시지를 JSON형태로 contents에 저장합니다. 그리고 id와 msg는 저장된 contents에서 각각 보낸 아이디와 text를 가져옵니다. 그리고 /binance가 포함되었는지 확인하기 위해 String.includes()를 사용해 조건문을 설정합니다.
if (msg.includes('/binance')) {
coin = msg.substring(9).toUpperCase()
}
/binance가 포함되어있다면 coin은 사용자가 보낸 text에서 9번째부터 끝까지 해당될 것입니다.
그리고 해당 코인을 Binance_get_Request() 함수에 요청합니다.
response = Binance_get_Request(coin)
Binance_get_Request() 함수는 다음과 같이 이루어져있습니다.
function Binance_get_Request(coin) {
let response = JSON.parse(UrlFetchApp.fetch('https://data.binance.com/api/v3/ticker/24hr?symbol=' + coin))
return response
}
반환된 데이터를 확인하고 필요한 부분에 대해 저는 봇이 응답할 메시지를 다음과 같이 정의했습니다.
text = (response['market'] + '(' + (response['signed_change_rate'] * 100).toFixed(2) + '%)'
+ '\n──────────────\n └현재가 : ' + String(response['trade_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW'
+ '\n └최고가 : ' + String(response['high_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW'
+ '\n └최저가 : ' + String(response['low_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW'
+ '\n └변동폭 : ' + String(response['signed_change_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW')
그리고 이를 Telegram_send() 함수를 호출해 메시지를 응답합니다.
Telegram_send(id, text)
주의.
Apps Script 웹 앱은 수정된 코드를 반영하고 싶다면 버전을 업데이트 해야합니다. 그렇다면 Webhook 역시 새롭게 배포된 URL 주소로 수정해야합니다.
다음은 /upbit 커맨드도 포함된 전체 소스코드입니다.
if (msg.includes('/binance')) {
coin = msg.substring(9).toUpperCase()
response = Binance_get_Request(coin)
text = (response['symbol'] + '(' + String(parseFloat(response['priceChangePercent']).toFixed(2)).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + '%)'
+ '\n──────────────\n └현재가 : ' + String(parseFloat(response['lastPrice']).toFixed(2)).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + '$'
+ '\n └최고가 : ' + String(parseFloat(response['highPrice']).toFixed(2)).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + '$'
+ '\n └최저가 : ' + String(parseFloat(response['lowPrice']).toFixed(2)).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + '$'
+ '\n └변동폭 : ' + String(parseFloat(response['priceChange']).toFixed(2)).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + '$')
Telegram_send(id, text)
}
else if (msg.includes('/upbit')) {
coin = msg.substring(7).toUpperCase()
response = Upbit_get_Request(coin)
text = (response['market'] + '(' + (response['signed_change_rate'] * 100).toFixed(2) + '%)'
+ '\n──────────────\n └현재가 : ' + String(response['trade_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW'
+ '\n └최고가 : ' + String(response['high_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW'
+ '\n └최저가 : ' + String(response['low_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW'
+ '\n └변동폭 : ' + String(response['signed_change_price']).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") + 'KRW')
Telegram_send(id, text)
}
축하합니다.
Google Sheets에서 제공하는 웹 앱을 이용하여 나만의 Telegram 봇을 만들 수 있게되었습니다.
[Apps Script] Telegram bot (4)
(1) ~ (3)를 통하여 Telegram 봇을 이용하기 위한 기초를 마쳤습니다. 이제는 원하는 봇을 만들 시간입니다. 저는 트레이딩을 하는 사람으로 Telegram을 통해 코인의 실시간 가격을 조회할 수 있는 봇을
soominkim.tistory.com
'Toy Proejct > GoogleSheet' 카테고리의 다른 글
[Apps Script] Telegram bot (4) (0) | 2023.02.22 |
---|---|
[Apps Script] Telegram bot (3) (0) | 2023.02.22 |
[Apps Script] Telegram bot (2) (0) | 2023.02.20 |
[Apps Script] Telegram bot (1) (0) | 2023.02.18 |