private async Task Run(string apiKey) { YouTubeService service = new YouTubeService(initializer: new BaseClientService.Initializer { ApplicationName = "youtube-data-api", ApiKey = apiKey }); var nextPageToken = ""; while (nextPageToken != null) { var commentsList = service.CommentThreads.List("snippet"); commentsList.VideoId = videoId; commentsList.MaxResults = 100; commentsList.PageToken = nextPageToken; CommentThreadListResponse resp = await commentsList.ExecuteAsync(); foreach (var item in resp.Items) { CommentsList.Add(item.Snippet); } nextPageToken = resp.NextPageToken; } string json = JsonConvert.SerializeObject(CommentsList); File.WriteAllText($@"C:\temp\{filename}", json); }
public static async Task Comment(SocketMessage message, string[] arg, string msg) { if (arg.Count() > 1) { try { YouTubeVideo video = YouTubeHelper.Search(msg.Substring(8)); CommentThreadListResponse comments = YouTubeHelper.GetComments(video.Url.Substring(32)); if (comments == null) { await message.Channel.SendMessageAsync($":no_entry: `Could not list comments for this video`"); } else { await message.Channel.SendMessageAsync("", false, genYtComment(comments.Items.ElementAt(new Random().Next(comments.Items.Count)).Snippet.TopLevelComment.Snippet)); } } catch { await message.Channel.SendMessageAsync($":no_entry: `That video doesn't exist n***a`:joy:"); } } else { await message.Channel.SendMessageAsync($":no_entry: `Please include a video link`"); } }
public async Task <List <Models.VideoComment> > ListCommentsAsync(Models.Video video) { var resultList = new List <VideoComment>(); string nextPageToken = ""; while (nextPageToken != null) { var request = _youtubeService.CommentThreads.List("snippet"); request.MaxResults = 100; request.VideoId = video.VideoId; request.TextFormat = CommentThreadsResource.ListRequest.TextFormatEnum.PlainText; request.PageToken = nextPageToken; CommentThreadListResponse response = null; try { _logger.LogInformation("list comment"); response = await request.ExecuteAsync(); } catch (Exception e) { _logger.LogError(e.Message); if (e.Message.Contains("Request had insufficient authentication scope")) { await _credential.RevokeTokenAsync(CancellationToken.None); await Init(); _logger.LogInformation("list comment"); response = await request.ExecuteAsync(); } } if (response == null) { continue; } resultList.AddRange(response.Items.Select(thread => new VideoComment { Id = thread.Snippet.TopLevelComment.Id, AuthorDisplayName = thread.Snippet.TopLevelComment.Snippet.AuthorDisplayName, PublishedAt = thread.Snippet.TopLevelComment.Snippet.PublishedAt, ETag = thread.Snippet.TopLevelComment.Snippet.ETag, TextOriginal = thread.Snippet.TopLevelComment.Snippet.TextOriginal, VideoId = video.VideoId })); nextPageToken = response.NextPageToken; } return(resultList); }
private static string GetRandomCommentFromCommentResponse(CommentThreadListResponse commentResponse, string videoId, bool includeVideo) { if (commentResponse.Items.Count < 1) { return(GetReturnStringWhenVideoHasNoComments(videoId, includeVideo)); } var commentIndex = Util.Rng(commentResponse.Items.Count); var commentSnippet = commentResponse.Items[commentIndex].Snippet.TopLevelComment.Snippet; return(GetReturnStringWhenVideoHasComments(videoId, includeVideo, commentSnippet)); }
public MCommentList(CommentThreadListResponse response) { if (response == null) { return; } NextPageToken = response.NextPageToken; PageInfo = new MPageInfo(response.PageInfo); VisitorId = response.VisitorId; Items = response.Items.Select(c => new MComment(c)); }
private void GetComments_OnClick(object sender, RoutedEventArgs e) { var videoReq = youtubeService.Videos.List("statistics"); videoReq.Id = VideoId.Text; var videoRes = videoReq.Execute(); MessageBox.Show(String.Format("{0} comments", videoRes.Items[0].Statistics.CommentCount)); var list = new List <Comment>(); string nextPageToken = ""; while (nextPageToken != null) { CommentThreadsResource.ListRequest req = youtubeService.CommentThreads.List("snippet"); req.MaxResults = 100; req.Fields = "items(snippet(topLevelComment(snippet(textDisplay,authorDisplayName,authorProfileImageUrl)))),nextPageToken"; req.VideoId = VideoId.Text; req.TextFormat = CommentThreadsResource.ListRequest.TextFormatEnum.PlainText; req.PageToken = nextPageToken; CommentThreadListResponse res = req.Execute(); if (res.Items != null) { foreach (CommentThread re in res.Items) { var data = new Comment { Content = re.Snippet.TopLevelComment.Snippet.TextDisplay, AuthorDisplayName = re.Snippet.TopLevelComment.Snippet.AuthorDisplayName, AvatarUrl = re.Snippet.TopLevelComment.Snippet.AuthorProfileImageUrl }; list.Add(data); } } nextPageToken = String.IsNullOrWhiteSpace(res.NextPageToken) ? null : res.NextPageToken; } MessageBox.Show("pobrane: " + list.Count.ToString()); list = list.Where(a => a.Content.Contains("27")).ToList(); Comments.ItemsSource = list; MessageBox.Show("z liczbÄ…: " + list.Count.ToString()); var t = list.GroupBy(a => a.Content); foreach (var k in t) { if (k.Count() > 1) { //MessageBox.Show(String.Format("{0}: {1}", k.FirstOrDefault().AuthorDisplayName, k.Key)); } } }
private async Task GetCommentsFromVideoIds(IEnumerable <string> videoIds, string apiKey, SyncCounter commentsCnt, SyncCounter updatesCnt, SyncCounter vidCntDown) { using (var api = new YoutubeApi(apiKey)) { foreach (var videoId in videoIds) { CommentThreadListResponse ytComments = null; try { ytComments = await api.GetAllCommentsAndAnswersFromVideo(videoId, _ct); } catch (Google.GoogleApiException e) { _logger.LogError($"error getting comments and answers for videoId={videoId} ({e.Message})"); } if (ytComments == null) { try { ytComments = await api.GetAllCommentsFromVideo(videoId, _ct); } catch (Google.GoogleApiException e) { _logger.LogError($"error getting comments for videoId={videoId} ({e.Message})"); } } vidCntDown.Decrement(); if (ytComments == null) { continue; } var dbComments = new List <Comment>(); foreach (var thread in ytComments.Items) { var hasAnswers = (thread.Snippet.TotalReplyCount ?? 0) > 0; dbComments.Add(thread.Snippet.TopLevelComment.MapToDbEntity(CommentType.Comment, videoId, hasAnswers)); if (hasAnswers && thread.Replies?.Comments != null) { dbComments.AddRange(thread.Replies.Comments.Select(a => a.MapToDbEntity(CommentType.Answer, videoId))); } } commentsCnt.Add(dbComments.Count); var updates = await _repository.SaveOrUpdate(dbComments); updatesCnt.Add(updates); } } }
public static CommentThreadListResponse GetCommentThreadListResponse(string videoId, int maxComments) { // Initialize the youtube service with the API key YouTubeService youtubeService = GetYoutubeService(); // Construct the request CommentThreadsResource.ListRequest commentThreadsListRequest = youtubeService.CommentThreads.List("snippet"); commentThreadsListRequest.MaxResults = maxComments; commentThreadsListRequest.TextFormat = CommentThreadsResource.ListRequest.TextFormatEnum.PlainText; commentThreadsListRequest.VideoId = videoId; // Retrieve the response CommentThreadListResponse commentThreadsListResponse = commentThreadsListRequest.Execute(); // Return the response return(commentThreadsListResponse); }
private static double ParseCommentThreadListResponse(CommentThreadListResponse commentThreadListResponse) { AverageSentiment averageScore = new AverageSentiment(); foreach (CommentThread commentThread in commentThreadListResponse.Items) { var comment = new YoutubeComment(); comment.AuthorName = commentThread.Snippet.TopLevelComment.Snippet.AuthorDisplayName; comment.Content = commentThread.Snippet.TopLevelComment.Snippet.TextDisplay; comment.SentimentScore = SentimentAnalysis.SelectComments(comment.Content); averageScore.CommentList.Add(comment); } averageScore.AverageSentimentScore = averageScore.CommentList.Average(c => c.SentimentScore); averageScore.VideoURL = commentThreadListResponse.Items[0].Snippet.VideoId; return(averageScore.AverageSentimentScore); }
internal async Task <IEnumerable <CommentThread> > GetCommentThreads(Channel channel = null, bool relatedTo = false, Video video = null, string id = null, int maxResults = 1) { return(await this.YouTubeServiceWrapper(async() => { List <CommentThread> results = new List <CommentThread>(); string pageToken = null; do { CommentThreadsResource.ListRequest request = this.connection.GoogleYouTubeService.CommentThreads.List("snippet,replies"); if (channel != null) { if (relatedTo) { request.AllThreadsRelatedToChannelId = channel.Id; } else { request.ChannelId = channel.Id; } } else if (video != null) { request.VideoId = video.Id; } else if (!string.IsNullOrEmpty(id)) { request.Id = id; } request.MaxResults = Math.Min(maxResults, 50); request.PageToken = pageToken; LogRequest(request); CommentThreadListResponse response = await request.ExecuteAsync(); LogResponse(request, response); results.AddRange(response.Items); maxResults -= response.Items.Count; pageToken = response.NextPageToken; } while (maxResults > 0 && !string.IsNullOrEmpty(pageToken)); return results; })); }
private AverageSentiment ParseCommentThreadListResponse(CommentThreadListResponse commentThreadListResponse) { // Construct the empty parsed comment threads list AverageSentiment averageScore = new AverageSentiment(); // Iterate over the comment thread list response and add each comment text foreach (CommentThread commentThread in commentThreadListResponse.Items) { var comment = new YoutubeComment(); comment.AuthorName = commentThread.Snippet.TopLevelComment.Snippet.AuthorDisplayName; comment.Content = commentThread.Snippet.TopLevelComment.Snippet.TextDisplay; comment.SentimentScore = SentimentAnalysis.SelectComments(comment.Content); averageScore.CommentList.Add(comment); } // Set the average sentiment score averageScore.AverageSentimentScore = averageScore.CommentList.Average(c => c.SentimentScore); averageScore.VideoURL = commentThreadListResponse.Items[0].Snippet.VideoId; averageScore.AnalysisDate = DateTime.Now; // Return the parsed comment threads list return(averageScore); }
public static async Task <dynamic> CommentThreads(AppSettings appSettings, JObject requestBody) { string methodName = "CommentThreads"; dynamic result = new ExpandoObject(); try { // https://developers.google.com/youtube/v3/docs/commentThreads/list YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer() { ApiKey = requestBody["apikey"]?.ToString() }); CommentThreadsResource.ListRequest listRequest = youtubeService.CommentThreads.List("id,replies,snippet"); if (requestBody["pagetoken"] != null) { listRequest.PageToken = requestBody["pagetoken"].ToString(); } switch (requestBody["type"]?.ToString()) { case "channel": listRequest.ChannelId = requestBody["id"].ToString(); break; case "video": listRequest.VideoId = requestBody["id"].ToString(); break; default: listRequest.AllThreadsRelatedToChannelId = requestBody["id"].ToString(); break; } listRequest.MaxResults = 100; if (requestBody["order"] != null) { //Accepted values: time, relevance listRequest.Order = Enum.Parse <CommentThreadsResource.ListRequest.OrderEnum>(requestBody["order"].ToString()); } if (requestBody["q"] != null) { listRequest.SearchTerms = requestBody["q"].ToString(); } listRequest.TextFormat = Enum.Parse <CommentThreadsResource.ListRequest.TextFormatEnum>(requestBody["textFormat"]?.ToString() ?? "PlainText"); CommentThreadListResponse listResponse = await listRequest.ExecuteAsync(); Dictionary <string, object> response = new Dictionary <string, object>(); response["totalresults"] = listResponse.PageInfo.TotalResults; response["pagetoken"] = listResponse.NextPageToken; List <Dictionary <string, object> > items = new List <Dictionary <string, object> >(); listResponse.Items.ToList().ForEach(i => { Dictionary <string, object> item = new Dictionary <string, object>(); item["commentid"] = i.Id; item["channelid"] = i.Snippet.ChannelId; item["videoid"] = i.Snippet.VideoId; item["likecount"] = i.Snippet.TopLevelComment.Snippet.LikeCount; item["viewerrating"] = i.Snippet.TopLevelComment.Snippet.ViewerRating; item["userchannelid"] = i.Snippet.TopLevelComment.Snippet.AuthorChannelId.Value; item["userchannelurl"] = i.Snippet.TopLevelComment.Snippet.AuthorChannelUrl; item["username"] = i.Snippet.TopLevelComment.Snippet.AuthorDisplayName; item["userprofileimageurl"] = i.Snippet.TopLevelComment.Snippet.AuthorProfileImageUrl; item["text"] = i.Snippet.TopLevelComment.Snippet.TextDisplay; item["publisheddate"] = i.Snippet.TopLevelComment.Snippet.PublishedAt; item["updateddate"] = i.Snippet.TopLevelComment.Snippet.UpdatedAt; if (i.Replies != null) { List <Dictionary <string, object> > replies = new List <Dictionary <string, object> >(); i.Replies.Comments.ToList().ForEach(c => { Dictionary <string, object> reply = new Dictionary <string, object>(); reply["replyid"] = c.Id; reply["userchannelid"] = c.Snippet.AuthorChannelId.Value; reply["userchannelurl"] = c.Snippet.AuthorChannelUrl; reply["username"] = c.Snippet.AuthorDisplayName; reply["userprofileimageurl"] = c.Snippet.AuthorProfileImageUrl; reply["text"] = c.Snippet.TextDisplay; reply["publisheddate"] = c.Snippet.PublishedAt; reply["updateddate"] = c.Snippet.UpdatedAt; replies.Add(reply); }); item["replies"] = replies; } items.Add(item); }); response["items"] = items; return(response); } catch (Exception e) { Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(requestBody)}"); Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}"); throw e; } }