Skip to content

Commit 1753c2d

Browse files
"Added sample: python/comment_handling.py"
1 parent d4805cf commit 1753c2d

1 file changed

Lines changed: 192 additions & 0 deletions

File tree

python/comment_handling.py

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
#!/usr/bin/python
2+
3+
# Usage example:
4+
# python comments.py --videoid='<video_id>' --text='<text>'
5+
6+
import httplib2
7+
import os
8+
import sys
9+
10+
from apiclient.discovery import build_from_document
11+
from apiclient.errors import HttpError
12+
from oauth2client.client import flow_from_clientsecrets
13+
from oauth2client.file import Storage
14+
from oauth2client.tools import argparser, run_flow
15+
16+
17+
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
18+
19+
# the OAuth 2.0 information for this application, including its client_id and
20+
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
21+
# the {{ Google Cloud Console }} at
22+
# {{ https://cloud.google.com/console }}.
23+
# Please ensure that you have enabled the YouTube Data API for your project.
24+
# For more information about using OAuth2 to access the YouTube Data API, see:
25+
# https://developers.google.com/youtube/v3/guides/authentication
26+
# For more information about the client_secrets.json file format, see:
27+
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
28+
CLIENT_SECRETS_FILE = "client_secrets.json"
29+
30+
# This OAuth 2.0 access scope allows for full read/write access to the
31+
# authenticated user's account and requires requests to use an SSL connection.
32+
YOUTUBE_READ_WRITE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
33+
YOUTUBE_API_SERVICE_NAME = "youtube"
34+
YOUTUBE_API_VERSION = "v3"
35+
36+
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
37+
# missing.
38+
MISSING_CLIENT_SECRETS_MESSAGE = """
39+
WARNING: Please configure OAuth 2.0
40+
41+
To make this sample run you will need to populate the client_secrets.json file
42+
found at:
43+
%s
44+
with information from the APIs Console
45+
https://developers.google.com/console
46+
47+
For more information about the client_secrets.json file format, please visit:
48+
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
49+
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
50+
CLIENT_SECRETS_FILE))
51+
52+
# Authorize the request and store authorization credentials.
53+
def get_authenticated_service(args):
54+
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SSL_SCOPE,
55+
message=MISSING_CLIENT_SECRETS_MESSAGE)
56+
57+
storage = Storage("%s-oauth2.json" % sys.argv[0])
58+
credentials = storage.get()
59+
60+
if credentials is None or credentials.invalid:
61+
credentials = run_flow(flow, storage, args)
62+
63+
# Trusted testers can download this discovery document from the developers page
64+
# and it should be in the same directory with the code.
65+
with open("youtube-v3-discoverydocument.json", "r") as f:
66+
doc = f.read()
67+
return build_from_document(doc, http=credentials.authorize(httplib2.Http()))
68+
69+
70+
# Call the API's commentThreads.list method to list the existing comment threads.
71+
def get_comment_threads(youtube, video_id):
72+
results = youtube.commentThreads().list(
73+
part="snippet",
74+
videoId=video_id,
75+
textFormat="plainText"
76+
).execute()
77+
78+
for item in results["items"]:
79+
comment = item["snippet"]["topLevelComment"]
80+
author = comment["snippet"]["authorDisplayName"]
81+
text = comment["snippet"]["textDisplay"]
82+
print "Comment by %s: %s" % (author, text)
83+
84+
return results["items"]
85+
86+
87+
# Call the API's comments.list method to list the existing comment replies.
88+
def get_comments(youtube, parent_id):
89+
results = youtube.comments().list(
90+
part="snippet",
91+
parentId=parent_id,
92+
textFormat="plainText"
93+
).execute()
94+
95+
for item in results["items"]:
96+
author = item["snippet"]["authorDisplayName"]
97+
text = item["snippet"]["textDisplay"]
98+
print "Comment by %s: %s" % (author, text)
99+
100+
return results["items"]
101+
102+
103+
# Call the API's comments.insert method to reply to a comment.
104+
# (If the intention is to create a new to-level comment, commentThreads.insert
105+
# method should be used instead.)
106+
def insert_comment(youtube, parent_id, text):
107+
insert_result = youtube.comments().insert(
108+
part="snippet",
109+
body=dict(
110+
snippet=dict(
111+
parentId=parent_id,
112+
textOriginal=text
113+
)
114+
)
115+
).execute()
116+
117+
author = insert_result["snippet"]["authorDisplayName"]
118+
text = insert_result["snippet"]["textDisplay"]
119+
print "Replied to a comment for %s: %s" % (author, text)
120+
121+
122+
# Call the API's comments.update method to update an existing comment.
123+
def update_comment(youtube, comment):
124+
comment["snippet"]["textOriginal"] = 'updated'
125+
update_result = youtube.comments().update(
126+
part="snippet",
127+
body=comment
128+
).execute()
129+
130+
author = update_result["snippet"]["authorDisplayName"]
131+
text = update_result["snippet"]["textDisplay"]
132+
print "Updated comment for %s: %s" % (author, text)
133+
134+
135+
# Call the API's comments.setModerationStatus method to set moderation status of an
136+
# existing comment.
137+
def set_moderation_status(youtube, comment):
138+
youtube.comments().setModerationStatus(
139+
id=comment["id"],
140+
moderationStatus="published"
141+
).execute()
142+
143+
print "%s moderated succesfully" % (comment["id"])
144+
145+
146+
# Call the API's comments.markAsSpam method to mark an existing comment as spam.
147+
def mark_as_spam(youtube, comment):
148+
youtube.comments().markAsSpam(
149+
id=comment["id"]
150+
).execute()
151+
152+
print "%s marked as spam succesfully" % (comment["id"])
153+
154+
155+
# Call the API's comments.delete method to delete an existing comment.
156+
def delete_comment(youtube, comment):
157+
youtube.comments().delete(
158+
id=comment["id"]
159+
).execute()
160+
161+
print "%s deleted succesfully" % (comment["id"])
162+
163+
164+
if __name__ == "__main__":
165+
# The "videoid" option specifies the YouTube video ID that uniquely
166+
# identifies the video for which the comment will be inserted.
167+
argparser.add_argument("--videoid",
168+
help="Required; ID for video for which the comment will be inserted.")
169+
# The "text" option specifies the text that will be used as comment.
170+
argparser.add_argument("--text", help="Required; text that will be used as comment.")
171+
args = argparser.parse_args()
172+
173+
if not args.videoid:
174+
exit("Please specify videoid using the --videoid= parameter.")
175+
if not args.text:
176+
exit("Please specify text using the --text= parameter.")
177+
178+
youtube = get_authenticated_service(args)
179+
# All the available methods are used in sequence just for the sake of an example.
180+
try:
181+
video_comment_threads = get_comment_threads(youtube, args.videoid)
182+
parent_id = video_comment_threads[0]["id"]
183+
insert_comment(youtube, parent_id, args.text)
184+
video_comments = get_comments(youtube, parent_id)
185+
update_comment(youtube, video_comments[0])
186+
set_moderation_status(youtube, video_comments[0])
187+
mark_as_spam(youtube, video_comments[0])
188+
delete_comment(youtube, video_comments[0])
189+
except HttpError, e:
190+
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
191+
else:
192+
print "Inserted, listed, updated, moderated, marked and deleted comments."

0 commit comments

Comments
 (0)