PHP:API-Webhook 记住变量

问题描述 投票:0回答:2

我正在 Telegram Bot API 上构建一个机器人。对于特定功能,我的机器人在使用 webhook 重新发送数据时应该记住变量。

简言之;每次我发送消息时,都会加载 PHP 文件(在 Google App Engine 上运行),这是由 Telegram Bot API 调用的。

每次 API 向 Webhook 发送数据时,机器人都会“重新加载”,当然所有变量都会重置。我正在考虑使用 $_SESSION

-变量,但这也行不通。

除了将数据保存在 MySQL 数据库中或写入文件之外,是否还有其他方法可以

临时将数据存储在某处?

php bots
2个回答
1
投票
你可以使用

文件获取内容

file_put_contents

将您的状态保存到文件中,并在您再次需要时加载它。


1
投票
除非 Telegram API Webhooks 尊重 cookie,否则您将需要在某处保留您的状态。在这种情况下,保存到文件似乎是最好的选择。

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);
    
© www.soinside.com 2019 - 2024. All rights reserved.