Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"xubuntu"]
OSSTRING = fillout(OSSTRING)
# BOT LOGIN
print(SUBREDDIT, "bot\n")
r = Reddit(client_id=getpass("ID: "),
client_secret=getpass("Secret: "),
user_agent=USERAGENT,
username=USERNAME,
password=getpass("Password: "))
try:
print("{} running on r/{}".format(r.user.me(), SUBREDDIT))
except (exceptions.OAuthException, exceptions.ResponseException):
print("Login error! Please try again.")
exit(1)
# DEFINING FUNCTIONS
def slay(post, response):
print("\tReplying to OP")
res = post.reply(response)
res.mod.distinguish(sticky=True)
if not TRUSTME:
print("\tReporting to mods")
post.report("Reason in comments")
post.mod.remove(spam=False)
print("\tPost removed")
sleep(5)
def _request_token(self, **data):
url = (
self._authenticator._requestor.reddit_url + const.ACCESS_TOKEN_PATH
)
pre_request_time = time.time()
response = self._authenticator._post(url, **data)
payload = response.json()
if "error" in payload: # Why are these OKAY responses?
raise OAuthException(
response, payload["error"], payload.get("error_description")
)
self._expiration_timestamp = (
pre_request_time - 10 + payload["expires_in"]
)
self.access_token = payload["access_token"]
if "refresh_token" in payload:
self.refresh_token = payload["refresh_token"]
self.scopes = set(payload["scope"].split(" "))
self.r = praw.Reddit(
user_agent = self.config['bot']['useragent'][self.useragent],
refresh_token = self.refresh_token,
**self.config['account']['oauth']
)
else:
self.r = praw.Reddit(
user_agent = self.config['bot']['useragent'][self.useragent],
**self.config['account']['oauth']
)
rt = self.authorize_oauth()
if rt:
rtfile = open('refresh_token','w')
rtfile.write(rt)
else:
raise prawcore.exceptions.OAuthException("Couldn't fetch refresh token!")
def _connect(self):
try:
self._r = praw.Reddit(self._user, check_for_updates=False, user_agent="python:shreddit:v6.0.4")
self._logger.info("Logged in as {user}.".format(user=self._r.user.me()))
except ResponseException:
raise ShredditError("Bad OAuth credentials")
except OAuthException:
raise ShredditError("Bad username or password")
duration = time.time() - start
totaltime += duration
numsamples += 1
if(numchecked % update_period == 0):
bot.log("\rChecked %d comments...",(numchecked),stderr=True,newline=False)
if(numsamples >= maxsamples):
bot.log("Average processing time of last %d comments: %.2f ms",(numsamples, totaltime/numsamples*1000))
numsamples = 0
totaltime = 0
sys.stdout.flush()
# Maybe if we get to the end, we need to get more?
bot.refresh_comments()
except prawcore.exceptions.OAuthException:
bot.refresh_oauth()
except KeyboardInterrupt:
bot.log("Shutting down after scanning %d comments...",(numchecked))
bot.save_seen()
sys.exit("Keyboard interrupt, shutting down...")
except Exception, e:
bot.log(u"Error!")
print traceback.format_exc()
def get_reddit_object(token):
try:
reddit = praw.Reddit(user_agent='reddit_utils web app by Roman Kuleshov',
client_id=token['client_id'],
client_secret=token['client_secret'],
username=token['username'],
password=token['password'])
reddit.user.me()
return {'status': 'success', 'data': reddit}
except OAuthException as err:
return {'status': 'error', 'data': 'Error: Unable to get API access, please make sure API credentials are correct and try again (check the username and password first)'}
except ResponseException as err:
return {'status': 'error', 'data': 'Error: ResponseException: ' + str(err)}
except Exception as err:
return {'status': 'error', 'data': 'Unexpected Error: ' + str(err)}
def test_reddit_connection(reddit):
"""
This function just tests connection to reddit
Many things can happen:
- Wrong credentials
- Absolutly garbage credentials
- No internet
This function helps us to quickly check if we are online
Return true on success and false on failure
"""
try:
reddit.user.me()
except prawcore.exceptions.OAuthException as e_creds:
traceback.print_exc()
logging.error(e_creds)
logging.critical("Invalid login credentials. Check your .env!")
logging.critical("Fatal error. Cannot continue or fix the problem. Bailing out...")
return False
except prawcore.exceptions.ResponseException as http_error:
traceback.print_exc()
logging.error(http_error)
logging.critical("Received 401 HTTP response. Try checking your .env!")
logging.critical("Fatal error. Cannot continue or fix the problem. Bailing out...")
return False
return True
try:
await self._start_listener()
except RequestException:
# probably a connexion loss, try again
time.sleep(self._SLEEPING_TIME_BEFORE_RECONNECT_ATTEMPT_SEC)
except InvalidToken as e:
# expired, try again
self.logger.exception(e, True, f"Error when receiving Reddit feed: '{e}'")
self.logger.info(f"Try to continue after {self._SLEEPING_TIME_BEFORE_RECONNECT_ATTEMPT_SEC} seconds.")
time.sleep(self._SLEEPING_TIME_BEFORE_RECONNECT_ATTEMPT_SEC)
except ServerError as e:
# server error, try again
self.logger.exception(e, True, "Error when receiving Reddit feed: '{e}'")
self.logger.info(f"Try to continue after {self._SLEEPING_TIME_BEFORE_RECONNECT_ATTEMPT_SEC} seconds.")
time.sleep(self._SLEEPING_TIME_BEFORE_RECONNECT_ATTEMPT_SEC)
except OAuthException as e:
self.logger.exception(e, True, f"Error when receiving Reddit feed: '{e}' this may mean that reddit "
f"login info in config.json are wrong")
self.keep_running = False
except ResponseException as e:
message_complement = "this may mean that reddit login info in config.json are invalid." \
if not self.credentials_ok else \
f"Try to continue after {self._SLEEPING_TIME_BEFORE_RECONNECT_ATTEMPT_SEC} seconds."
self.logger.exception(e, True,
f"Error when receiving Reddit feed: '{e}' this may mean {message_complement}")
if not self.credentials_ok:
self.connect_attempts += 1
else:
self.connect_attempts += 0.1
time.sleep(self._SLEEPING_TIME_BEFORE_RECONNECT_ATTEMPT_SEC)
except Exception as e:
self.logger.error(f"Error when receiving Reddit feed: '{e}'")