我正在查看是否有人在Google Apps脚本中创建了一个聊天机器人来处理视频群聊的环聊?我创建了一个漫游器,但不确定如何将Webhook网址输入漫游器代码,以便将该消息部署到聊天室中。
答案 0 :(得分:1)
我并没有完全创建您要寻找的内容,但是我相信您可以找到here的答案。基本上,只要您的机器人进入一个空间,就会发生一个事件。触发该事件后,您可以将空间ID添加到存储在某处的列表中。(Spreadsheet,PropertiesService等)
列表存储后,您可以将应用程序部署为Web应用程序。您可以阅读有关网络应用here的更多信息,但您需要了解两件事,那就是google为您提供了向Web请求发送网址的网址,以及一对名为doGet(当有人发出get请求时)和doPost(当有人发出发布请求时)。您可以创建发布函数,并在将Web应用发布到该函数时获取参数。
最后,您可以通过对每个ID进行api fetch调用,对Google api进行提取调用,以将刚刚从请求中收到的消息发布到您所在的所有空间中。
下面的代码将直接从API的第一个链接中发布。
// Example bot for Hangouts Chat that demonstrates bot-initiated messages
// by spamming the user every minute.
//
// This bot makes use of the Apps Script OAuth2 library at:
// https://github.com/googlesamples/apps-script-oauth2
//
// Follow the instructions there to add the library to your script.
// When added to a space, we store the space's ID in ScriptProperties.
function onAddToSpace(e) {
PropertiesService.getScriptProperties()
.setProperty(e.space.name, '');
return {
'text': 'Hi! I\'ll post a message here every minute. ' +
'Please remove me after testing or I\'ll keep spamming you!'
};
}
// When removed from a space, we remove the space's ID from ScriptProperties.
function onRemoveFromSpace(e) {
PropertiesService.getScriptProperties()
.deleteProperty(e.space.name);
}
// Add a trigger that invokes this function every minute via the
// "Edit > Current Project's Triggers" menu. When it runs, it will
// post in each space the bot was added to.
function onTrigger() {
var spaceIds = PropertiesService.getScriptProperties()
.getKeys();
var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
for (var i = 0; i < spaceIds.length; ++i) {
postMessage(spaceIds[i], message);
}
}
var SCOPE = 'https://www.googleapis.com/auth/chat.bot';
// The values below are copied from the JSON file downloaded upon
// service account creation.
var SERVICE_ACCOUNT_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE
KEY-----\n';
var SERVICE_ACCOUNT_EMAIL = 'service-account@project-id.iam.gserviceaccount.com';
// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {
var service = OAuth2.createService('chat')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
.setClientId(SERVICE_ACCOUNT_EMAIL)
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(SCOPE);
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}
var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
UrlFetchApp.fetch(url, {
method: 'post',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json',
payload: JSON.stringify(message),
});
}