C#使用YouTube V3 API添加评论
本文关键字:添加 评论 API V3 使用 YouTube | 更新日期: 2023-09-27 18:28:54
我正在使用C#并使用YouTube V3 API。我正试图在视频中插入评论,但每当我这样做时,我都会收到"{"Object reference not set to an instance of an object."}"
的异常。每当我运行类似于上面代码的东西时,就会发生这种情况:
public void AddComment()
{
CommentThread commentToAdd = new CommentThread();
commentToAdd.Snippet.IsPublic = true;
commentToAdd.Snippet.TopLevelComment.Snippet.TextOriginal = "Test";
commentToAdd.Snippet.VideoId = "kc-LBxBcyG8";
commentToAdd.Snippet.TopLevelComment.Snippet.VideoId = "kc-LBxBcyG8";
CommentThreadsResource.InsertRequest ins = JKYouTube.NewYouTubeService().CommentThreads.Insert(commentToAdd, "snippet");
var insertedComment = ins.Execute();
}
我将其与谷歌浏览器进行比较,并使用相同的属性,浏览器实际上在我的程序失败的地方添加了注释。https://developers.google.com/youtube/v3/docs/commentThreads/insert
一旦到达的第二行代码commentToAdd.Snippet.IsPublic = true;
它只会出错,并继续上面的每一行。
如有任何帮助,我们将不胜感激。
您的问题在于Snippet
是null
。
从您提供的API链接中获取,您需要首先创建一个CommentSnippet
。
在谷歌提供的例子中:
// Insert channel comment by omitting videoId.
// Create a comment snippet with text.
CommentSnippet commentSnippet = new CommentSnippet();
commentSnippet.setTextOriginal(text);
首先,用一些文本创建一个CommentSnippet
,然后我们创建一个顶级注释:
// Create a top-level comment with snippet.
Comment topLevelComment = new Comment();
topLevelComment.setSnippet(commentSnippet);
然后,将您的topLevelComment
添加到CommentThreadSnippet
:
// Create a comment thread snippet with channelId and top-level
// comment.
CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet();
commentThreadSnippet.setChannelId(channelId);
commentThreadSnippet.setTopLevelComment(topLevelComment);
当你终于有了CommentThreadSnippet
时,你可以把它添加到CommentThread
:中
// Create a comment thread with snippet.
CommentThread commentThread = new CommentThread();
commentThread.setSnippet(commentThreadSnippet);
遵循这些步骤不应为您提供NRE
非常感谢您的帮助。设法完成了。
async Task AddVideoCommentAsync(string commentToAdd, string videoID)
{
CommentSnippet commentSnippet = new CommentSnippet();
commentSnippet.TextOriginal = commentToAdd;
Comment topLevelComment = new Comment();
topLevelComment.Snippet = commentSnippet;
CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet();
commentThreadSnippet.VideoId = videoID;
commentThreadSnippet.TopLevelComment = topLevelComment;
CommentThread commentThread = new CommentThread();
commentThread.Snippet = commentThreadSnippet;
var youtubeService = await NewYouTubeService();
CommentThreadsResource.InsertRequest insertComment = youtubeService.CommentThreads.Insert(commentThread, "snippet");
await insertComment.ExecuteAsync();
}