Created
February 2, 2022 22:21
-
-
Save dsemenko-habr/533f86444765e262a19a73d060617427 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SHEET_NAME = "Копилка челлендж"; | |
const TABLE_RANGE = "A2:E27"; | |
const SHEET = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME); | |
const PAYMENT_MESSAGES = { | |
0: "Напоминалка: сегодня тебе надо внести %amount₽ в копилку для челленджа", | |
1: "Напоминалка: завтра тебе надо внести %amount₽ в копилку для челленджа", | |
} | |
class Payment { | |
constructor(date, week, amount, paid) { | |
this.date = date; | |
this.week = week; | |
this.amount = amount; | |
this.paid = paid; | |
} | |
daysBeforePayment() { | |
let today = new Date(); | |
return Math.ceil((this.date - today) / 86400000); | |
} | |
isPaid() { | |
return this.paid; | |
} | |
getAmount() { | |
return this.amount; | |
} | |
} | |
function getCurrentPayment() { | |
let data = SHEET.getRange(TABLE_RANGE).getValues(); | |
for (line of data) { | |
let payment = new Payment(line[0], line[1], line[2], line[4]); | |
if (!payment.isPaid()) { | |
return payment; | |
} | |
} | |
} | |
function paymentScheduler() { | |
let payment = getCurrentPayment(); | |
let daysLeft = payment.daysBeforePayment(); | |
let messageToSend = PAYMENT_MESSAGES[daysLeft]; | |
if (messageToSend != null) { | |
messageToSend = messageToSend.replace("%amount", payment.getAmount()); | |
tgBot.sendMessage(messageToSend); | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const BOT_TOKEN = "SECRET"; | |
const MY_CHAT_ID = 1234567; | |
class TelegramBot { | |
constructor(token) { | |
this.token = token; | |
this.api_url = `https://api.telegram.org/bot${BOT_TOKEN}/`; | |
} | |
sendMessage(message) { | |
Logger.log(`Sending message to telegram: ${message}`); | |
try { | |
let isRequestSuccessful = this._apiSendMessage(message); | |
if (isRequestSuccessful) { | |
Logger.log("Message was sent successful!"); | |
} else { | |
Logger.log("Message wasn't sent"); | |
} | |
} catch (error) { | |
Logger.log(`An error occurred while sending the request: ${error}`) | |
} | |
} | |
_apiSendMessage(message) { | |
let response = UrlFetchApp.fetch(`${this.api_url}sendMessage?chat_id=${MY_CHAT_ID}&text=${message}`); | |
Logger.log(`Telegram response: ${response.getContentText()}`); | |
return JSON.parse(response.getContentText())["ok"]; | |
} | |
} | |
const tgBot = new TelegramBot(BOT_TOKEN); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment