Skip to content

Instantly share code, notes, and snippets.

@johannesmols
Created February 16, 2017 11:46
Show Gist options
  • Save johannesmols/086dbe380a522712861af06526218259 to your computer and use it in GitHub Desktop.
Save johannesmols/086dbe380a522712861af06526218259 to your computer and use it in GitHub Desktop.
import pafy #Docs: http://pythonhosted.org/pafy/
import praw
import urllib.parse
import credentials
import time
#Read and Write Files Doc: https://www.tutorialspoint.com/python3/python_files_io.htm
def load_cache_on_startup(): #loads cached comments on startup in the list
try:
file = open('cache.txt', "r") #r = read only
cached_comments = file.read()
id_list = cached_comments.split(',')
return id_list
except Exception as e:
print('Error loading cache on startup')
words_to_match = ['youtube.com/watch?v=', 'youtu.be/'] #search criteria for youtube links
blacklist = ['pathofexile', 'watchpeopledie', 'todayilearned', 'gamedeals', 'the_donald', 'translater']
cache = load_cache_on_startup()
def main():
check_inbox_for_delete_requests()
reply_to_comments()
reply_to_submissions()
def reply_to_comments():
reddit = praw.Reddit(user_agent=credentials.user_agent, client_id=credentials.client_id, client_secret=credentials.client_secret,
username=credentials.username, password=credentials.password)
subreddit = reddit.subreddit('BotTestingRange')
comments = subreddit.comments(limit=100)
for comment in comments:
comment_text = comment.body
isMatch = any(string in comment_text for string in words_to_match) #finds out if a comment has a youtube link in it
if comment.id not in cache and isMatch and comment.subreddit.display_name.lower() not in blacklist:
#Get the whole video url
try:
url = get_youtube_url(str(comment.body))
output = construct_table(url) #construct the comment in reddit formatting for tables
my_comment = comment.reply(output)
add_delete_link(my_comment)
print("Reply successfull")
cache.append(comment.id)
with open('cache.txt', 'a') as out: #a = appending modus
out.write(comment.id + ',') #append comment id to cache
update_cache()
except Exception as e:
print('Error in the reply process')
continue
elif comment.id in cache:
print("Comment ID already in cache")
print('Done with 100 comments, wait until restart')
def reply_to_submissions():
reddit = praw.Reddit(user_agent=credentials.user_agent, client_id=credentials.client_id, client_secret=credentials.client_secret,
username=credentials.username, password=credentials.password)
subreddit = reddit.subreddit('BotTestingRange')
submissions = subreddit.new(limit=50)
for submission in submissions:
submission_url = submission.url
isMatch = any(string in submission_url for string in words_to_match) #finds out if link is a youtube link
if submission.id not in cache and isMatch and submission.subreddit.display_name.lower() not in blacklist:
try:
url = get_youtube_url(submission_url)
output = construct_table(submission_url) #construct the comment in reddit formatting for tables
my_comment = submission.reply(output)
add_delete_link(my_comment)
print("Comment successfull")
cache.append(submission.id)
with open('cache.txt', 'a') as out: #a = appending modus
out.write(submission.id + ',') #append comment id to cache
update_cache()
except Exception as e:
print('Error in the comment process')
continue
elif submission.id in cache:
print("Submission ID already in cache")
continue
print('Done with 50 submissions, wait until restart')
def update_cache():
file = open('cache.txt', "r") #r = read only
cached_comments = file.read()
cache = cached_comments.split(',') #split by , and put in the list
def get_youtube_url(comment_text):
url = str(comment_text).split("/") #split into it's parts
stepone = str(url[2]) + "/" + str(url[3]) #left part cutted
steptwo = str(stepone).split("&ab_channel=") #split right part
return steptwo[0]
def sanitize_data_input(input):
output = ""
for i in input:
if i.isalnum() == True or i == " ":
output += i
else:
output += " "
return output
def construct_table(url):
video = pafy.new(url)
metadata = {'title':str(video.title), 'author':str(video.author), 'viewcount':str(video.viewcount), 'duration':str(video.duration),
'likes':str(video.likes), 'dislikes':str(video.dislikes), 'rating':str(video.rating), 'date':str(video.published),
'description':str(video.description), 'category':str(video.category), 'keywords':str(video.keywords), 'thumbnail':str(video.thumb), 'id':str(video.videoid)}
metadata['title'] = sanitize_data_input(metadata['title'])
metadata['author'] = sanitize_data_input(metadata['author'])
metadata['keywords'] = sanitize_data_input(metadata['keywords'])
#Rick Roll Preserving Measure
if metadata['id'] == 'DLzxrzFCyOs':
print('PRESERVE THE RICK ROLLING')
return
output = ( "Hello! It looks like you posted a YouTube video. I am here to provide you with unnecessary meta information about the video. Enjoy!\n\n" +
"|Category|Information|\n" + ":--|:--\n" + "Title" + "|" + metadata['title'] + "\n" +
"Author" + "|" + metadata['author'] + "\n" +
"Views" + "|" + str(format(int(metadata['viewcount']), ',d')) + "\n" + #format to have commas for every thousand
"Duration" + "|" + metadata['duration'] + "\n" +
#"Likes" + "|" + metadata['likes'] + "\n" + #doesn't show up
#"Dislikes" + "|" + metadata['dislikes'] + "\n" + #doesn't show up
"Rating" + "|" + metadata['rating'] + "\n" + #cut decimals
"Upload Date" + "|" + metadata['date'] + "\n" + #format into a better readable format
#"Description" + "|" + metadata['description'] + "\n" + #way tooo long sometimes
"Category" + "|" + metadata['category'] + "\n" +
"Keywords" + "|" + metadata['keywords'] + "\n" + #remove brackets and '
"Thumbnail" + "|" + "[Thumbnail](" + metadata['thumbnail'] + ")" + "\n" +
"Video ID" + "|" + metadata['id'] + "\n" +
"If you are unhappy with my services or found a bug, please [write a message](https://www.reddit.com/message/compose?to=maggiforever) to my creator"
)
return output
def add_delete_link(my_comment):
message_template = 'https://www.reddit.com/message/compose/?to=SlightlyAnnoyingBot&subject=deletion&message={fullname}'
delete_link = message_template.format(fullname=my_comment.fullname)
footer_template = "\n\nTo delete this comment, click [here]({url})"
footer = footer_template.format(url=delete_link)
print(footer)
my_comment.edit(my_comment.body + footer)
def check_inbox_for_delete_requests():
reddit = praw.Reddit(user_agent=credentials.user_agent, client_id=credentials.client_id, client_secret=credentials.client_secret,
username=credentials.username, password=credentials.password)
unread = reddit.inbox.unread(limit=50)
for message in unread:
if message.subject == 'deletion': #if the guy who sent the request is the author of the parent comment of my comment
print("Comment to delete: " + message.body)
comment = reddit.comment(message.body) #get comment with id
comment.delete() #doesn't delete itself!!!!!!!! why??????????????????
message.mark_read()
print('Deleted a comment by request (' + message.body + ')')
#run the program
while True:
try:
main()
time.sleep(20)
except Exception as e:
print(e.message)
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment