我正在 Telegram Bot API 上构建一个机器人。对于特定功能,我的机器人在使用 webhook 重新发送数据时应该记住变量。
简言之;每次我发送消息时,都会加载 PHP 文件(在 Google App Engine 上运行),这是由 Telegram Bot API 调用的。
每次 API 向 Webhook 发送数据时,机器人都会“重新加载”,当然所有变量都会重置。我正在考虑使用 $_SESSION
-变量,但这也行不通。除了将数据保存在 MySQL 数据库中或写入文件之外,是否还有其他方法可以
临时将数据存储在某处?
Google App Engine 提供了一种使用 PHP 流的方法,使其易于读取和写入 Google Cloud Storage。
https://cloud.google.com/appengine/docs/php/googlestorage/
实现此目的的一种方法是将需要持久保存的任何变量放入数组中,然后在保存之前编码为 JSON。然后,当您读取文件时,只需将 JSON 解码为关联数组即可继续。
$path = 'gs://my_bucket/my_vars.json';
// read the variables - you'll want to check for existence, etc.
$myVarsJson = file_get_contents($path);
$myVarsArr = json_decode($myVarsJson,true);
// now you can access and modify the values of $myVarsArray
// DO SOMETHING...
// then save them
$myVarsJson = json_encode($myVarsArr);
file_put_contents($path);