Variables Twilio-使用经典函数如何创建和更新持久的变量?
下面是我使用NodeJS的代码的开始 现在我想知道如何创建变量,修改变量,并以在调用和会话之间保持不变的方式更新变量 我希望能够有不同的用户给我发短信,我会用不同的递增索引回复每个用户 我不需要完整的解决方案,我只需要知道如何创建、调用、更改和保存持久变量,以备将来使用Variables Twilio-使用经典函数如何创建和更新持久的变量?,variables,twilio,sms,Variables,Twilio,Sms,下面是我使用NodeJS的代码的开始 现在我想知道如何创建变量,修改变量,并以在调用和会话之间保持不变的方式更新变量 我希望能够有不同的用户给我发短信,我会用不同的递增索引回复每个用户 我不需要完整的解决方案,我只需要知道如何创建、调用、更改和保存持久变量,以备将来使用 /* global module, exports, require, process, console */ 'use strict' // Configure necessary Twilio objects const
/* global module, exports, require, process, console */
'use strict'
// Configure necessary Twilio objects
const twilio = require('twilio')
const client = twilio(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN)
const notify = client.notify.services(process.env.TTK_BROADCAST_NOTIFY_SERVICE_SID)
// List of admin phone numbers should be in the system environment
const adminNumbers = process.env.TTK_BROADCAST_ADMIN_NUMBERS
所以有点像
// Helper class for commands
class Command {
// Create a new instance with necessary arguments from the incoming SMS
constructor(event, context) {
this.fromNumber = event.From
this.body = event.Body || ''
this.event = event
this.context = context
// Occassionally, US numbers will be passed without the preceding
// country code - check for this eventuality and fix it
if (this.fromNumber.indexOf('+') !== 0) {
this.fromNumber = `+1${this.fromNumber}`
}
}
// Get an array of arguments after the first word for a command
get commandArguments() {
return this.body.trim().split(' ').slice(1)
}
// Get the full text after the command with spaces reinserted
get commandText() {
return this.commandArguments.join(' ')
}
// Execute command async (to be overridden by subclasses)
run(callback) {
callback(null, 'Command not implemented.')
}
}
/* Subclasses for supported commands */
class HelpCommand extends Command {
run(callback) {
callback(null, helpMessage)
}
}
// INCOMING MESSAGES SIGN UP ##########################
class SubscribeCommand extends Command {
run(callback) {
// Create a new SMS Notify binding for this user's phone number
notify.bindings.create({
identity: this.fromNumber,
bindingType: 'sms',
address: this.fromNumber,
tag: ['subscribe']
}).then((response) => {
/***
1. Increment a variable here.
2. inject the variable into subscrubeSuccessMessage as the subscriber index.
***/
callback(null, subscribeSuccessMessage)
}).catch(err => {
callback(err, subscribeFailMessage)
})
}
}
现在我找到了这个文档
我面临的主要问题是,我不知道这些环境SID来自哪里????。我可以忽略它吗
我能不能这样做,把环境留空
client.serverless.services('ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.environments
.variables
.create({key: 'key', value: 'value'})
.then(variable => console.log(variable.sid));
您可以看下面的示例,这是持久化数据的一个选项。Sync有详细的特定约束,但它可能满足您的用例 函数环境变量不是用来存储动态数据的。有一个这样使用的例子
仅适用于任何试图解决此类问题的其他人 我最终通过使用Axios解决了这个问题,并根据本文建立了到我的web服务器的远程连接 在使用了这个之后,我可以选择使用一个数据库或者仅仅使用平面文件来持久化数据。因为我不需要太复杂的东西,所以我用平面文件快速解决了这个问题 在我的应用程序中,管理员广播即将发生的事件的公告,并为该事件分配一个新ID“eventid”。服务器端PHP代码被设置为响应Create命令,该命令将在文件夹中创建一组新记录并刷新索引(此处不包括) 收到后,用户可以选择RSVP,但他们还必须输入eventid。”RSVP事件ID' 我需要持久性,因为每个RSVP都需要一个唯一的席位ID,我不希望系统创建重复的席位ID或为每个电话号码(用户)分配超过1个席位ID 因此,管理员创建一个事件,然后用户通过RSVP EVENTID响应,每个人都会得到一个唯一的座位 axios只允许使用GET/POST和JSON来回传递数据 服务器端PHP,持久数据的快速测试。这将为每个电话号码创建一个唯一的索引,从11开始。(因此我可以预订0-10个座位)
TLDR;持久计数器通过一点PHP代码在远程服务器上的平面文件记录中维护。axios允许通过JSON和webhooks传递数据。谢谢alan,我在同步方面遇到的唯一问题是不清楚同步服务SID的来源。syncServiceSid='???'我很幸运没有找到创建这些ID所需的依赖项或进程的相关信息?这包括环境和其他服务的ID。代码中的注释中包含了这一点:``//查看同步服务-//设置为特定的同步服务SID```
<?PHP
//count.php (needs local read/write permissions)
$number= isset($_GET['number']) ? $_GET['number'] : "555-123-4567";
$number= cleanInput($number);
$eventid= isset($_GET['eventid']) ? $_GET['eventid'] : 127;
$eventid= cleanInput($eventid);
if(!file_exists($eventid)){
mkdir($eventid);
$status="Unknown Event";
}else{
$status="Ok";
}
$uniqueness = intval(file_get_contents("{$eventid}/" . $number ));
if(!$uniqueness){
$seat = intval(file_get_contents("{$eventid}/count.txt"));
$seat = $seat<11 ? 11 : $seat+1;
file_put_contents("{$eventid}/count.txt", $seat . "");
file_put_contents("{$eventid}/" . $number , $seat . "");
}else{
$seat=$uniqueness;
}
/*
populate the other data, however you like
*/
$output= "{";
$output.= " \"seat\": \"" . $seat . "\"";
$output.= " \"status\": \"" . $status . "\"";
$output.= ",\"eventid\": \"" . $eventid . "\"";
$output.= ",\"number\": \"" . $number . "\"";
$output.= "}";
echo $output;
function cleanInput($cleanme){
$cleaned=str_replace("+","",$cleanme);
$cleaned=str_replace(".","",$cleaned);
$cleaned=str_replace('\\',"",$cleaned);
$cleaned=str_replace('/',"",$cleaned);
return $cleaned;
}
/*
This application is part of the Twilio.org Toolkit for Nonprofits.
For complete documentation on how to use this function, please visit:
https://github.com/Twilio-org/toolkit/blob/master/docs/broadcast.md
*/
// Configure necessary Twilio objects
const twilio = require('twilio');
const axios = require('axios');
...
class RSVPCommand extends Command {
run(callback) {
// Reply to RSVP with a unique seat #
axios
.get('https://MY_SERVER.com/smsapi/count.php?number=' + this.fromNumber + '&eventid=' + eventid)
.then((response) => {
let { seat, eventid } = response.data;
let msg = "Thank you! Seat #%seat% has been reserved for you for Event#%eventid% Present this message for entry. See you there!"
msg = msg.replace("%seat%",seat);
msg = msg.replace("%eventid%",eventid);
callback(null, msg)
}).catch(err => {
callback(err, subscribeFailMessage)
})
}
}
//The export handler looks something like
// Handle incoming SMS commands ####################
exports.handler = (context, event, callback) => {
// Get command text from incoming SMS body
let body = event.Body || ''
//EXTRACT THE COMMAND AND eventid ARGUMENT
cmd = body.trim().split(' ')[0].toLowerCase()
//assuming an RSVP or EVENT command, capture the event ID
eventid = body.trim().split(' ')[1].toLowerCase()
// Default to help command
let cmdInstance = new HelpCommand(event, context)
// Choose other commands as appropriate
switch(cmd) {
case 'subscribe': cmdInstance = new SubscribeCommand(event, context); break;
case 'broadcast': cmdInstance = new BroadcastCommand(event, context); break;
//this is where we send a special create command to initiate the event.
//(not included)
case 'event': cmdInstance = new BroadcastEventCommand(event, context); break;
case 'rsvp': cmdInstance = new RSVPCommand(event, context); break;
}
// Execute command
cmdInstance.run((err, message) => {
let twiml = new twilio.twiml.MessagingResponse()
if (err) {
console.log(err)
message = 'There was a problem with your request. Try again!'
}
twiml.message(message)
callback(null, twiml)
})
}