如何使用google-api-client-ruby日历stop_channel

How to use google-api-client-ruby calendar stop_channel

我正在尝试使用 google-api-client-ruby gem 与 Google 日历交互。

我已经成功设置了一个频道来监视事件,但是我正在努力使用 stop_channel 方法来停止监视事件。

源代码看起来需要一个通道对象,但如果我创建一个通道对象并将其传递给 stop_channel 方法,我会得到:

Error - Google::Apis::ClientError: required: Required

我的代码..

channel = Google::Apis::CalendarV3::Channel.new(address: "https://www.google.com/", id: 1, type: "web_hook")
begin
  calendar_service.stop_channel(channel)
rescue => error
  puts error
end

是我做错了什么还是 gem 不工作?..

您的错误Google::Apis::ClientError: required: Required表示请求无效,不应在不修改的情况下重试。

此外,我看到这个 sample code 使用 stop_channel 方法。

def stop_channel(channel_id, resource_id)
    channel = Google::Apis::CalendarV3::Channel.new(
      id: channel_id,
      resource_id: resource_id
    )
    service.stop_channel(channel)
end

这个问题在这一点上已经很老了,但我在较新的 google-apis-calendar_v3 gem 中遇到了完全相同的问题,所以我想我会 post 我的答案。

为了让我的代码正常工作,我必须先创建带有 id 和 resource_id 的通道对象。您可能认为只有 id 就足够了,但显然事实并非如此。

这是对我有用的代码片段。

# Handle Google OAuth
# I'm not sure you need both of these scopes to stop watching a channel but
# my application needed both for other things it had to handle.
client_id = Google::Auth::ClientId.from_file("#{ROOT_DIR}/client_secret.json")
scopes = [Google::Apis::CalendarV3::AUTH_CALENDAR_EVENTS,
          Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY]
token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
authorizer = Google::Auth::WebUserAuthorizer.new(client_id,
                                                 scopes,
                                                 token_store,
                                                 '/oauth2callback')

# Create the CalendarService object
service = Google::Apis::CalendarV3::CalendarService.new
service.client_options.application_name = "Quickstart"

if service.authorization.nil?
  service.authorization = authorizer.get_credentials(user_id, request)
end

# Instantiate the channel we want to stop watching using the channel id and
# resource id passed in as request parameters.
channel = Google::Apis::CalendarV3::Channel.new(id: params['cid'],
                                                type: 'web_hook',
                                                resource_id: params['resource_id'])

# Stop watching the channel.
service.stop_channel(channel)

希望这对尝试将 Google 日历与 Ruby 应用程序集成的其他人有用。