在 Google Cloud 上安排 Twillio 消息

问题描述

我想要实现的是,一旦我通过 Twilio 收到一条消息,我想安排在 5 分钟后回复它。我正在使用 Google Cloud Functions 生成回复,但我不确定如何安排它。我已经完成了 Cloud 任务、Pub/Sub 和 Scheduler,但我仍然对如何实现它感到困惑。我正在使用 Python。

我在想的是以下工作流程:Twilio -> 云函数接收消息并在 5 分钟后设置任务 o-> 5 分钟后调用一个云函数。我不知道如何在 5 分钟后安排它。

解决方法

在 AWS 中,您可以将 SQS 与 delay queues 结合使用,这非常方便。

相当于 AWS SQS 的 Google Cloud Pub/Sub 不支持任何类型的延迟,因此您需要使用 Google Cloud Tasks。

creating a task 时,您可以指定一个 schedule time 来标识应执行任务的时间:

scheduleTime 字符串(时间戳格式)

计划尝试或重试任务的时间。

从 Google 文档中复制和粘贴的快速示例代码,省略了不相关的部分:

from google.cloud import tasks_v2
from google.protobuf import timestamp_pb2
import datetime
[...]
client = tasks_v2.CloudTasksClient()
parent = client.queue_path(project,location,queue)
in_seconds = 5*60  # After 5 minutes...
d = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)
timestamp = timestamp_pb2.Timestamp()
timestamp.FromDatetime(d)
task = {
    "http_request": {
        "http_method": tasks_v2.HttpMethod.POST,"url": url,"schedule_time": timestamp,}
}
# Need to add payload,headers and task name as necessary here...
[...]
response = client.create_task(request={"parent": parent,"task": task})