【发布时间】:2021-02-14 09:44:47
【问题描述】:
所以我使用this 源代码在 GAS 中构建了我的电报机器人,还使用消息处理程序在 Google 电子表格中获取了message.message.chat.id
所以现在我想要的是:
- 删除重复的
chat_ids,因为它在每次用户发送消息时都会重复 - 给
chat_ids 发消息
我尝试过的:
我使用了这个功能,它运行良好,但问题是手动更改 chat_id 值将是一场噩梦!
function SendTest() {
var token = "xxx";
var telegramUrl = "https://api.telegram.org/bot" + token;
var url = telegramUrl + "/sendMessage?chat_id=xxx&text=Hello+World";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
这是一张我的电子表格的照片
“如您所见,在第 3、4、5 行中有一个重复的 chat_ids,我只想要其中一个,所以当我向他们发送消息时,它不会发送多次 - 我想要第 1 个"
这是我使用的消息处理程序
function saveMessage(message) {
let file = SpreadsheetApp.openById(sheetLogId);
// first tab of the file
let sheet = file.getSheets()[0];
// get last row
let lastRow = sheet.getLastRow() + 1;
sheet.setActiveSelection('A' + lastRow).setValue(Date(message.message.date)); // date
sheet.setActiveSelection('B' + lastRow).setValue(message.message.chat.id); // chat id
sheet.setActiveSelection('C' + lastRow).setValue(message.message.from.username); // username
sheet.setActiveSelection('E' + lastRow).setValue(message.message.text); // message
sheet.setActiveSelection('D' + lastRow).setValue(message.message.chat.first_name+ " " + message.message.chat.last_name); // message
}
-- 编辑--
所以我使用 Nikko J.editd 函数 saveMessage(message) 来解决我的第一个问题(不再重复 chat_id!)
在那之后我发现this 表单谈到了检索行,所以我用它来选择电子表格中的所有chat_id 并将其循环到我的发送文本函数中
它在这里代表:
function sendtext(){
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var botSecret = "the bot token";
rows.forEach(function(row, index) {
Logger.log(row[1] + ":" + index)
var id = row[1];
UrlFetchApp.fetch("https://api.telegram.org/bot" + botSecret + "/sendMessage?text=" + "the text that you want " + "&chat_id=" + id + "&parse_mode=HTML");
});
}
【问题讨论】:
标签: javascript google-apps-script google-sheets telegram-bot