0

Winforms 및 C#의 YouTube 용 자체 ChatBot에서 작업하고 있습니다. 이미 Twitch에서 작동하며 C# API를 사용하여 Youtube의 기능을 복제하려고합니다. 채팅 메시지는 아무 문제없이 다운로드 할 수 있지만 채팅 메시지를 작성하면 403, 불충분 한 권한 오류가 발생하여 두통이 생깁니다. 전체 오류 메시지는 내가 찾을 수 있습니다 아직 정확히 원인이 무엇인지에 빈 올라와있다 대부분의 일을 시도했습니다 약간의 검색 후YouTube .NET API - 채팅 메시지를 만들 때 권한 문제가 발생했습니다.

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) 
      { 

      } 

     } 

}

문제의 주요 코드는 메시지 전송 방법이다. UserCredentials의 범위를 내가 쓸모없는 곳으로 변경하려고 시도했습니다. 어떤 아이디어?

+0

사용자가 Google 계정으로 로그인 했습니까? – Bobby

+0

코드를 처음 실행했을 때 프로세스를 거쳤다는 것을 의미합니다. (이것이 의미하는 것이면, 그렇지 않으면 확실하지 않습니다.) – mikelomaxxx14

+0

"프로세스를 통해?" 글쎄, 대개의 경우 누구나 애플리케이션을 열고 (아직 로그인하지 않은 상태입니다.) Google은 사용자에게 신원을 요청해야하며 사용자는 Google 서비스에 사용자 이름과 비밀번호를 제공해야합니다. 구현 되었습니까? – Bobby

답변

0

error 403 or insufficientPermissions에서 요청에 제공된 OAuth 2.0 토큰에 오류가있어 요청한 데이터에 액세스하기에 충분하지 않은 범위를 지정합니다.

응용 프로그램에 적절한 Scope을 사용해야합니다. 다음은 응용 프로그램에 필요한 범위의 예입니다.

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

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

이 오류 403에 대한 자세한 내용은이 관련 SO question을 확인할 수 있습니다.

+0

코드에서 알 수 있듯이 적절한 범위를 사용하고 있습니다. YouTube와 YouTubeForceSSL을 모두 시도했지만 어느 것도 작동하지 않습니다. 어쩌면 내가 어떻게 알아낼 수 있다면, 나는 그 접근을 철회하고 그것을 다시 할 것이다. – mikelomaxxx14

+1

좋아, 취소하고 다시 시도해 ... 고정 이유는 모르겠다! – mikelomaxxx14

0

액세스 권한 취소 후 문제가 해결되었다고 밝혀졌습니다. 오류 메시지는별로 도움이되지 않았습니다.