YouTube .NET API - 创建聊天消息时的权限问题

时间:2016-07-21 06:18:32

标签: c# youtube-api google-api-dotnet-client youtube-data-api

我正在使用Winforms和C#开发自己的ChatBot for YouTube。它已经在Twitch上工作,我正在尝试使用C#API复制Youtube的功能。我可以下载聊天消息没问题,但创建聊天消息让我头疼,因为我得到403,权限不足错误。完整的错误消息是

Google.Apis.Requests.RequestError
Insufficient Permission [403]
Errors [
    Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]

经过一番搜索,我已经尝试了大多数我能找到的东西,并且仍然是空的,究竟究竟是什么导致了这一点。我觉得这是一个许可问题,我显然需要设置一些内容,但我无法弄清楚是什么。我的代码在下面,绝对适用于阅读数据...但我不知道为什么它不适用于写作。

  public class YouTubeDataWrapper
    {
        private YouTubeService youTubeService;
        private string liveChatId;
        private bool updatingChat;
        private int prevResultCount;

        public List<YouTubeMessage> Messages { get; private set; }
        public bool Connected { get; private set; }
        public bool ChatUpdated { get; set; }
        //public Authorisation Authorisation { get; set; }
        //public AccessToken AccessToken { get; set; }

        public YouTubeDataWrapper()
        {
            this.Messages = new List<YouTubeMessage>();
        }

        public async void Connect()
        {
            Stream stream = new FileStream("client_secrets.json", FileMode.Open);
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, new[] { YouTubeService.Scope.YoutubeForceSsl }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()));
            stream.Close();
            stream.Dispose();

            this.youTubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });

            var res = this.youTubeService.LiveBroadcasts.List("id,snippet,contentDetails,status");
            res.BroadcastType = LiveBroadcastsResource.ListRequest.BroadcastTypeEnum.Persistent;
            res.Mine = true;

            //res.BroadcastStatus = LiveBroadcastsResource.ListRequest.BroadcastStatusEnum.Active;
            var resListResponse = await res.ExecuteAsync();

            IEnumerator<LiveBroadcast> ie = resListResponse.Items.GetEnumerator();
            while (ie.MoveNext() && string.IsNullOrEmpty(this.liveChatId))
            {
                LiveBroadcast livebroadcast = ie.Current;
                string id = livebroadcast.Snippet.LiveChatId;
                if (!string.IsNullOrEmpty(id))
                {
                    this.liveChatId = id;
                    this.Connected = true;
                }

                bool? def = livebroadcast.Snippet.IsDefaultBroadcast;
                string title = livebroadcast.Snippet.Title;
                LiveBroadcastStatus status = livebroadcast.Status;
            }
        }

        public async void UpdateChat()
        {
            if (!this.updatingChat)
            {
                if (!string.IsNullOrEmpty(this.liveChatId) && this.Connected)
                {
                    this.updatingChat = true;
                    var livechat = this.youTubeService.LiveChatMessages.List(this.liveChatId, "id,snippet,authorDetails");
                    var livechatResponse = await livechat.ExecuteAsync();

                    PageInfo pageInfo = livechatResponse.PageInfo;

                    this.ChatUpdated = false;

                    if (pageInfo.TotalResults.HasValue)
                    {
                        if (!this.prevResultCount.Equals(pageInfo.TotalResults.Value))
                        {
                            this.prevResultCount = pageInfo.TotalResults.Value;
                            this.ChatUpdated = true;
                        }
                    }

                    if (this.ChatUpdated)
                    {
                        this.Messages = new List<YouTubeMessage>();

                        foreach (var livemessage in livechatResponse.Items)
                        {
                            string id = livemessage.Id;
                            string displayName = livemessage.AuthorDetails.DisplayName;
                            string message = livemessage.Snippet.DisplayMessage;

                            YouTubeMessage msg = new YouTubeMessage(id, displayName, message);

                            string line = string.Format("{0}: {1}", displayName, message);
                            if (!this.Messages.Contains(msg))
                            {
                                this.Messages.Add(msg);
                            }
                        }
                    }
                    this.updatingChat = false;
                }
            }
        }

        public async void SendMessage(string message)
        {
            LiveChatMessage liveMessage = new LiveChatMessage();

            liveMessage.Snippet = new LiveChatMessageSnippet() { LiveChatId = this.liveChatId, Type = "textMessageEvent", TextMessageDetails = new LiveChatTextMessageDetails() { MessageText = message } };

            var insert = this.youTubeService.LiveChatMessages.Insert(liveMessage, "snippet");
            var response = await insert.ExecuteAsync();

            if (response != null)
            {

            }

        }

}

有问题的主要代码是Send Message方法。我已经尝试将UserCredentials的范围更改为我可以尝试无效的所有内容。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

YouTube Data API - Error,您为请求提供的OAuth 2.0令牌中的error 403 or insufficientPermissions错误指定的范围不足以访问请求的数据。

因此,请确保在您的应用中使用正确的Scope。以下是应用程序中所需范围的示例。

https://www.googleapis.com/auth/youtube.force-ssl

https://www.googleapis.com/auth/youtube

有关此错误403的详细信息,您可以查看此相关的SO question

答案 1 :(得分:0)

事实证明,撤销访问权限然后重新执行它会解决问题。错误消息不是很有帮助。