Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import praw
- import config
- import time
- import os
- import unicodedata
- keyword = '!respect'
- subreddit_list = ['whowouldwin', 'respectthread_bot']
- posts_list = []
- def bot_login():
- print('Logging in...')
- r = praw.Reddit(username = config.username,
- password = config.password,
- client_id = config.client_id,
- client_secret = config.client_secret,
- user_agent = 'respectthread responder v0.1')
- print('Logged in')
- with open("saved_posts.txt", "a") as f:
- f.write('\n')
- return r
- class LineResults:
- def __init__(self, linelist, searchResults):
- self.linelist = linelist
- self.searchResults = searchResults
- def run_bot(r):
- for sub in subreddit_list:
- # loop through every comment on a certain subreddit. Limits to 30 comments.
- quantity = 20
- print('Obtaining ' + str(quantity) + ' comments from r/' + sub + '...')
- for comment in r.subreddit(sub).comments(limit=quantity):
- resultList = []
- replyTo = False
- if comment.author != r.user.me() and comment not in posts_list and keyword in comment.body.lower():
- bodylist = comment.body.split('\n')
- for line in bodylist:
- linelist = line.split()
- if len(linelist) >= 2 and len(line) < 150 and 'https://www.reddit.com/r/respectthreads' not in line and 'https://redd.it' not in line:
- if summoning_conditional(linelist):
- searchResults = generate_search_results(linelist)
- resultList.append(LineResults(linelist, searchResults))
- replyTo = True
- if replyTo:
- generate_reply(comment, resultList)
- sleep_time = 20
- print('Sleeping for ' + str(sleep_time) + ' seconds...')
- time.sleep(sleep_time)
- def summoning_conditional(line_list):
- if line_list[0] == '-' or line_list[0] == '*' or line_list[0] == '+':
- line_list.pop(0)
- if line_list[0].lower() == keyword:
- line_list.pop(0)
- if line_list[0].lower() == 'threads':
- return False
- elif line_list[0].lower() == 'thread':
- line_list.pop(0)
- if line_list[0].lower() == 'for':
- line_list.pop(0)
- return True
- return False
- def generate_search_results(linelist):
- query = ''
- for string in linelist:
- query += string + ' '
- # Remove extra space at end of string
- query = query[:-1]
- search_results = r.subreddit('respectthreads').search(query, sort='relevance', syntax='lucene', time_filter='all')
- filteredResults = []
- # Separate between bracketed and unbracketed user text, and remove accents.
- bracketedQuery = strip_accents(substring_in_brackets(query))
- unbracketedQuery = strip_accents(substring_out_brackets(query))
- # If the user specified the version or verse in brackets
- if len(bracketedQuery) > 0:
- for post in search_results:
- # Separate between bracketed and unbracketed title text, and remove accents.
- bracketedTitle = strip_accents(substring_in_brackets(post.title))
- unbracketedTitle = strip_accents(substring_out_brackets(post.title))
- # Check for matches between user text and post title.
- if unbracketedQuery in unbracketedTitle and bracketedQuery in bracketedTitle:
- filteredResults.append(post)
- # Else if the user only specified the name
- else:
- for post in search_results:
- unbracketedTitle = strip_accents(substring_out_brackets(post.title))
- if unbracketedQuery in unbracketedTitle:
- filteredResults.append(post)
- # In case the user specifies the character name in brackets and no matches are found.
- if len(filteredResults) <= 0:
- # Have to redo the search results.
- search_results = r.subreddit('respectthreads').search(query, sort='relevance', syntax='lucene', time_filter='all')
- for post in search_results:
- # Separate between bracketed and unbracketed title text, and remove accents.
- bracketedTitle = strip_accents(substring_in_brackets(post.title))
- unbracketedTitle = strip_accents(substring_out_brackets(post.title))
- # Swap queries.
- if unbracketedQuery in bracketedTitle and bracketedQuery in unbracketedTitle:
- filteredResults.append(post)
- return filteredResults
- def substring_in_brackets(query):
- A = list(query)
- inBrackets = False
- c = 0
- while c < len(A):
- if not inBrackets:
- if A[c] == '(' or A[c] == '[':
- inBrackets = True
- del A[c]
- else:
- if A[c] == ')' or A[c] == ']':
- inBrackets = False
- del A[c]
- else:
- c += 1
- return ''.join(A).lower()
- def substring_out_brackets(query):
- A = list(query)
- inBrackets = False
- c = 0
- while c < len(A):
- if not inBrackets:
- if A[c] == '(' or A[c] == '[':
- inBrackets = True
- else:
- c += 1
- else:
- if A[c] == ')' or A[c] == ']':
- inBrackets = False
- del A[c]
- return ''.join(A).lower()
- def strip_accents(text):
- try:
- text = unicode(text, 'utf-8')
- except NameError: # unicode is a default on python 3
- #print("NameError")
- pass
- text = unicodedata.normalize('NFD', text).encode('ascii', 'ignore').decode("utf-8")
- return str(text).replace("-", " ").strip() # Remove dashes
- def generate_reply(comment, result_list):
- reply_text = ''
- max_reply_length = 8000
- too_long = False
- for result in result_list:
- query = ' '.join(result.linelist)
- if result.searchResults:
- reply_text += 'Here\'s what I found on r/respectthreads for *' + query + '*:\n\n'
- for searchResult in result.searchResults:
- reply_text += '- [' + searchResult.title + '](' + searchResult.shortlink + ')' + '\n\n'
- if len(reply_text) > max_reply_length:
- too_long = True
- break
- else:
- reply_text += 'Sorry, I couldn\'t find anything on r/respectthreads for *' + query + '*\n\n'
- reply_text += 'If you\'re having issues finding a RT, please see the [user instructions](https://redd.it/bd2iv9).' + '\n'
- reply_text += 'If the RT you\'re looking for does not exist, you can [request it](https://redd.it/b5hr1x) or [make it yourself](https://www.reddit.com/r/respectthreads/wiki/introduction_guide).' + '\n\n'
- if len(reply_text) > max_reply_length:
- too_long = True
- break
- reply_text += '***\n\n'
- if too_long:
- reply_text += 'Some results may be cut off as this reply has gotten too long.' + '\n\n'
- reply_text += '***\n\n'
- break
- reply_text += '^(I am a bot) ^| '
- reply_text += '[^(About)](https://redd.it/bd2mld) ^| '
- reply_text += '[^(How to use)](https://redd.it/cljh3v) ^| '
- reply_text += '[^(How to run)](https://redd.it/be38fh) ^| '
- reply_text += '[^(Code)](https://pastebin.com/gaU5qTmD)'
- comment.reply(reply_text)
- print(reply_text)
- with open("saved_posts.txt", "a") as f:
- f.write(comment.id + '\n')
- posts_list.append(comment.id)
- result_list = []
- def get_saved_posts():
- # Make sure the file exists.
- if not os.path.isfile("saved_posts.txt"):
- posts_list = []
- else:
- # "r" is to read from saved_posts.txt as the variable f
- with open("saved_posts.txt", "r") as f:
- posts_list = f.read()
- posts_list = posts_list.split("\n")
- return posts_list
- posts_list = get_saved_posts()
- r = bot_login()
- while True:
- run_bot(r)
Add Comment
Please, Sign In to add comment