首页 > 解决方案 > 如何使用 cron 作业将事件插入谷歌日历?

问题描述

我编写了一个 Python 脚本,允许我从外部连接的源中检索日历事件并将它们插入到我的 Google 日历中,这要归功于 Google Calendar 的 API。当我从命令行执行脚本时,它在本地工作,但我想让它自动发生,以便外部添加的事件自动在我的 Google 日历中弹出。

似乎 cron 作业是执行此操作的最佳方式,并且鉴于我使用了 Google Calendar 的 API,我认为将 Cloud Functions 与 Cloud Scheduler 一起使用可能会有所帮助。但是,我真的不知道从哪里开始,如果这甚至可能,因为访问 API 需要使用 Google 对我的个人 Google 帐户进行 OAuth,这是我认为服务帐户(我认为我需要)做不到的代表我。

我需要采取哪些步骤才能允许我手动运行并使用 Google 日历对我进行身份验证的脚本每 60 秒在云中运行一次,这样我就不需要一直打开我的计算机?

我试图做的事情:

我创建了一个具有完全权限的服务帐户,并尝试创建一个 http-trigger 事件,理论上该事件会在创建的 URL 被命中时运行脚本。但是,它只返回一个 HTTP 500 错误。我尝试做 Pub/Sub 事件目标来监听和执行脚本,但这也不起作用。

我对此感到困惑:

使用任一帐户,都需要有一个credentials.json文件才能登录;这个文件如何与主函数一起“部署”?token.pickle以及第一次进行身份验证时创建的文件。

标签: pythongoogle-cloud-functionsgoogle-calendar-apigoogle-oauthgoogle-cloud-scheduler

解决方案


The way a service account works is that it needs to be preauthorized. You would take the service account email address and share a calendar with it like you would with any other user. The catch here being that you should only be doing this with calendars you the developer control. If these are calendars owned by others you shouldnt be using a service account.

The way Oauth2 works is that a user is displayed a consent screen to grant your application access to their data. Once the user has granted you access and assuming you requested offline access you should have a refresh token for that users account. Using the refresh token you can request a new access token at anytime. So the trick here would be storing the users refresh tokens in a place that your script can access it then when the cron job runs the first thing it needs to do is request a new access token using its refresh token.

So the only way you will be able to do this as a cron job is if you have a refresh token stored for the account you want to access. Other wise it will require it to open a web browser to request the users consent and you cant do that with a cron job.


推荐阅读