def sendDelayDefensiveNumberMessage(game): recpt = game['waitingOn'] messageToSend = "{}\n\nReply with a number between **1** and **{}**, inclusive".format(getCurrentPlayString(game), globals.maxRange) reddit.sendMessage(game[recpt]['coaches'],"{} vs {}".format(game['away']['name'], game['home']['name']),embedTableInMessage(messageToSend, {'action': 'play'})) messageResult = reddit.getRecentSentMessage() game['waitingId'] = messageResult.fullname log.debug('Just sent the defensive message to {} after their delay of game'.format(game[recpt]['coaches']))
def sendDefensiveNumberMessage(game, mess=None, recpt=None): defenseHomeAway = reverseHomeAway(game['status']['possession']) log.debug("Sending get defense number message to {}".format( getCoachString(game, defenseHomeAway))) if mess is not None: reddit.sendMessage(game[game['waitingOn']]['coaches'][0], 'Tip result', embedTableInMessage(mess, {'action': 'play'})) else: if not game['status']['free']: messageToSend = "{}\n\nReply with a number between **1** and **{}**, inclusive \ or you can send foul for an intentional foul. There is currently {} \ left in the {} half".format(getCurrentPlayString(game), globals.maxRange, renderTime(game['status']['clock']), getNthWord(game['status']['half'])) else: messageToSend = "{}\n\nReply with a number between **1** and **{}**, inclusive".format( getCurrentPlayString(game), globals.maxRange) reddit.sendMessage( game[defenseHomeAway]['coaches'], "{} vs {}".format(game['away']['name'], game['home']['name']), embedTableInMessage(messageToSend, {'action': 'play'})) messageResult = reddit.getRecentSentMessage() log.debug('messageResult is {}'.format(messageResult)) game['waitingId'] = messageResult.fullname log.debug("Defensive number sent, now waiting on: {}".format( game['waitingId']))
def sendTipNumberMessages(game, coaches): reddit.sendMessage(coaches, 'Tip Number', embedTableInMessage("\n\nReply with a number between \ **1** and **{0}**, inclusive.".format(globals.maxRange) , {'action': 'tip'})) messageResult = reddit.getRecentSentMessage() game['waitingId'] = messageResult.fullname log.debug("Tip number sent, now waiting on: {}".format(game['waitingId']))
def processMessageRejectGame(dataTable, author): log.debug("Processing reject game message") if 'opponent' not in dataTable: log.warning("Couldn't find opponent in datatable") return False, "I couldn't figure out which opponent you were rejecting. This shouldn't happen, please let /u/Watchful1 know" log.debug( "Sending message to /u/{} that {} rejected their challenge".format( dataTable['opponent'], author)) reddit.sendMessage(dataTable['opponent'], "Challenge rejected", "/u/{} has rejected your game challenge".format(author)) return True, "Challenge successfully rejected"
def sendDefensiveNumberMessage(game): defenseHomeAway = reverseHomeAway(game['status']['possession']) log.debug("Sending get defence number to {}".format( getCoachString(game, defenseHomeAway))) reddit.sendMessage( game[defenseHomeAway]['coaches'], "{} vs {}".format(game['away']['name'], game['home']['name']), embedTableInMessage( "{}\n\nReply with a number between **1** and **1500**, inclusive.". format(getCurrentPlayString(game)), {'action': 'play'})) messageResult = reddit.getRecentSentMessage() game['waitingId'] = messageResult.fullname log.debug("Defensive number sent, now waiting on: {}".format( game['waitingId']))
def MessageLineAddSubreddit(line): results = defaultdict(list) if line.startswith("addsubreddit"): subs = re.findall('(?:/?r/)(\w*)', line) filters = re.findall('(?:filter=)(\S*)', line) if len(filters): filter = filters[0] log.debug("Found filter in addsubreddit: "+filter) else: filter = None for sub in subs: log.info("Whitelisting subreddit /r/"+sub) deniedRequests = database.getDeniedSubscriptions(sub.lower()) for user in deniedRequests: log.info("Messaging /u/%s that their subscriptions in /r/%s have been activated", user, sub) strList = strings.activatingSubredditMessage(sub.lower(), deniedRequests[user]) strList.append("\n\n*****\n\n") strList.append(strings.footer) if not reddit.sendMessage(user, strings.messageSubject(user), ''.join(strList)): log.warning("Could not send message to /u/%s when activating subreddit", user) results['subredditsAdded'].append({'subreddit': sub, 'subscribers': len(deniedRequests)}) database.activateSubreddit(sub, line.startswith("addsubredditsub"), filter) return results
def checkDeniedRequests(subreddit): count = database.getDeniedRequestsCount(subreddit) if database.checkUpdateDeniedRequestsNotice(subreddit, count): log.info("Messaging owner that that requests for /r/%s have hit %d", subreddit, count) noticeStrList = strings.subredditNoticeThresholdMessage(subreddit, count) noticeStrList.append("\n\n*****\n\n") noticeStrList.append(strings.footer) if not reddit.sendMessage(globals.OWNER_NAME, "Subreddit Threshold", ''.join(noticeStrList)): log.warning("Could not send message to owner when notifying on subreddit threshold")
def sendDefensiveNumberMessage(game): defenseHomeAway = game.status.possession.negate() log.debug("Sending get defence number to {}".format( getCoachString(game, defenseHomeAway))) results = reddit.sendMessage( recipients=game.team(defenseHomeAway).coaches, subject="{} vs {}".format(game.away.name, game.home.name), message=embedTableInMessage( "{}\n\nReply with a number between **1** and **1500**, inclusive.\n\nYou have until {}." .format(getCurrentPlayString(game), renderDatetime(game.playclock)), getActionTable(game, game.status.waitingAction))) resetWaitingId(game) for message in results: addWaitingId(game, message.fullname) log.debug("Defensive number sent, now waiting on: {}".format( game.status.waitingId))
def processMessageNewGame(body, author): log.debug("Processing new game message") users = re.findall('(?: /u/)([\w-]*)', body) if len(users) == 0: log.debug("Could not find an opponent in create game message") return "Please resend the message and specify an opponent" opponent = users[0] log.debug("Found opponent in message /u/{}".format(opponent)) i, result = utils.verifyCoaches([author, opponent]) if i == 0 and result == 'team': log.debug("Author does not have a team") return "It looks like you don't have a team, please contact the /r/FakeCollegeFootball moderators" if i == 0 and result == 'game': log.debug("Author already has a game") return "You're already playing a game, you can't challenge anyone else until that game finishes" if result == 'duplicate': log.debug("{} challenged themselves to a game".format(author)) return "You can't challenge yourself to a game" if i == 1 and result == 'team': log.debug("Opponent does not have a team") return "It looks like your opponent doesn't have a team, please contact the /r/FakeCollegeFootball moderators" if i == 1 and result == 'game': log.debug("Opponent already has a game") return "/u/{} is already playing a game".format(opponent) authorTeam = wiki.getTeamByCoach(author) message = "/u/{}'s {} has challenged you to a game! Reply **accept** or **reject**.".format( author, authorTeam['name']) data = {'action': 'newgame', 'opponent': author} embeddedMessage = utils.embedTableInMessage(message, data) log.debug( "Sending message to /u/{} that /u/{} has challenged them to a game". format(opponent, author)) if reddit.sendMessage(opponent, "Game challenge", embeddedMessage): return "I've let /u/{} know that you have challenged them to a game. I'll message you again when they accept".format( opponent) else: return "Something went wrong, I couldn't find that user"
def MessageLineAddSubreddit(line): results = defaultdict(list) if line.startswith("addsubreddit"): subs = re.findall('(?:/?r/)(\w*)', line) filters = re.findall('(?:filter=)(\S*)', line) if len(filters): filter = filters[0] log.debug("Found filter in addsubreddit: " + filter) else: filter = None for sub in subs: log.info("Whitelisting subreddit /r/" + sub) deniedRequests = database.getDeniedSubscriptions(sub.lower()) for user in deniedRequests: log.info( "Messaging /u/%s that their subscriptions in /r/%s have been activated", user, sub) strList = strings.activatingSubredditMessage( sub.lower(), deniedRequests[user]) strList.append("\n\n*****\n\n") strList.append(strings.footer) if not reddit.sendMessage(user, strings.messageSubject(user), ''.join(strList)): log.warning( "Could not send message to /u/%s when activating subreddit", user) results['subredditsAdded'].append({ 'subreddit': sub, 'subscribers': len(deniedRequests) }) database.activateSubreddit(sub, line.startswith("addsubredditsub"), filter) return results
def sendGameMessage(isHome, game, message, dataTable): reddit.sendMessage( game.team(isHome).coaches, "{} vs {}".format(game.home.name, game.away.name), embedTableInMessage(message, dataTable)) return reddit.getRecentSentMessage().id
seconds = 150 recovered = False for num in range(1, 4): time.sleep(seconds) if reddit.checkConnection(): recovered = True break seconds = seconds * 2 problemStrList = [] if recovered: log.warning("Messaging owner that that we recovered from a problem") problemStrList.append("Recovered from an exception after " + str(seconds) + " seconds.") problemStrList.append("\n\n*****\n\n") problemStrList.append(strings.footer) if not reddit.sendMessage(globals.OWNER_NAME, "Recovered", ''.join(problemStrList)): log.warning("Could not send message to owner when notifying recovery") else: log.warning("Messaging owner that that we failed to recover from a problem") problemStrList.append("Failed to recovered from an exception after " + str(seconds) + " seconds.") problemStrList.append("\n\n*****\n\n") problemStrList.append(strings.footer) if not reddit.sendMessage(globals.OWNER_NAME, "Failed recovery", ''.join(problemStrList)): log.warning("Could not send message to owner when notifying failed recovery") break markTime('end', startTime) try: logStrList = strings.longRunLog(timings, counts, foundPosts) log.debug(''.join(logStrList)) except Exception as err:
def searchComments(searchTerm, startTime): errors = [] if searchTerm == globals.UPDATE_NAME: subscriptionType = True elif searchTerm == globals.SUBSCRIPTION_NAME: subscriptionType = False url = "https://api.pushshift.io/reddit/comment/search?q=" + searchTerm + "&limit=200&sort=desc" try: requestTime = time.perf_counter() json = requests.get(url, headers={'User-Agent': globals.USER_AGENT}) requestSeconds = int(time.perf_counter() - requestTime) if json.status_code != 200: log.warning("Could not parse data for search term: " + searchTerm + " status: " + str(json.status_code)) errors.append("Could not parse data for search term: " + str(json.status_code) + " : " + url) return 0, 0, 0, errors comments = json.json()['data'] except Exception as err: log.warning("Could not parse data for search term: " + searchTerm) log.warning(traceback.format_exc()) errors.append("Could not parse data for search term: " + url) return 0, 0, 0, errors if len(comments) == 0: log.warning("Could not parse data for search term, no results: " + searchTerm + " status: " + str(json.status_code)) errors.append("Could not parse data for search term, no results: " + str(json.status_code) + " : " + url) return 0, 0, 0, errors elif requestSeconds > 80 and len(comments) > 0: log.warning("Long request, but returned successfully: " + str(requestSeconds)) timestamp = database.getCommentSearchTime(searchTerm) if timestamp is None: timestamp = startTime database.updateCommentSearchSeconds(searchTerm, timestamp) # we want to start at the oldest. Since we update the current timestamp at each item, # if we crash, we don't want to lose anything oldestIndex = len(comments) - 1 for i, comment in enumerate(comments): if datetime.utcfromtimestamp(comment['created_utc']) < timestamp: oldestIndex = i - 1 break if i == 99: log.info( "Messaging owner that that we might have missed a comment") strList = strings.possibleMissedCommentMessage( datetime.utcfromtimestamp(comment['created_utc']), timestamp) strList.append("\n\n*****\n\n") strList.append(strings.footer) if not reddit.sendMessage(globals.OWNER_NAME, "Missed Comment", ''.join(strList)): log.warning( "Could not send message to owner that we might have missed a comment" ) if oldestIndex == -1: return 0, 0, requestSeconds, errors commentsAdded = 0 commentsSearched = 0 for comment in comments[oldestIndex::-1]: if comment['author'].lower() != globals.ACCOUNT_NAME.lower(): commentsSearched += 1 if database.isBlacklisted(comment['author'].lower(), comment['subreddit'].lower()): continue log.info("Found public comment by /u/" + comment['author']) comment['link_author'] = str( reddit.getSubmission(comment['link_id'][3:]).author) result, data = utility.addUpdateSubscription( comment['author'], comment['link_author'], comment['subreddit'], datetime.utcfromtimestamp(comment['created_utc']), subscriptionType, None) posted = False if result != 'couldnotadd' and not database.alwaysPMForSubreddit(comment['subreddit'].lower()) \ and not database.isThreadReplied(comment['link_id'][3:]): strList = [] existingSubscribers = database.getAuthorSubscribersCount( comment['subreddit'].lower(), comment['link_author'].lower()) strList.extend( strings.confirmationComment(subscriptionType, comment['link_author'], comment['subreddit'], comment['link_id'][3:], existingSubscribers)) strList.append("\n\n*****\n\n") strList.append(strings.footer) log.info("Publicly replying to /u/%s for /u/%s in /r/%s:", comment['author'], comment['link_author'], comment['subreddit']) resultCommentID = reddit.replyComment(comment['id'], ''.join(strList)) if resultCommentID is not None: database.addThread(comment['link_id'][3:], resultCommentID, comment['link_author'].lower(), comment['subreddit'].lower(), comment['author'].lower(), datetime.utcnow(), existingSubscribers, subscriptionType, False) posted = True else: log.warning("Could not publicly reply to /u/%s", comment['author']) if not posted: strList = [] if result == 'couldnotadd': utility.checkDeniedRequests(data['subreddit']) strList.extend(strings.couldNotSubscribeSection([data])) else: if result == 'added': commentsAdded += 1 strList.extend(strings.confirmationSection([data])) elif result == 'updated': commentsAdded += 1 strList.extend( strings.updatedSubscriptionSection([data])) elif result == 'exist': strList.extend(strings.alreadySubscribedSection([data ])) strList.append("\n\n*****\n\n") strList.append(strings.footer) log.info( "Messaging confirmation for public comment to /u/%s for /u/%s in /r/%s:", comment['author'], comment['link_author'], comment['subreddit']) if not reddit.sendMessage( comment['author'], strings.messageSubject(comment['author']), ''.join(strList)): log.warning( "Could not send message to /u/%s when sending confirmation for public comment", comment['author']) database.updateCommentSearchSeconds( searchTerm, datetime.utcfromtimestamp(comment['created_utc']) + timedelta(0, 1)) return commentsSearched, commentsAdded, requestSeconds, errors
messages.processMessage(message) except Exception as err: log.warning("Error in main loop") log.warning(traceback.format_exc()) if globals.game is not None: log.debug("Setting game {} as errored".format(globals.game.thread)) index.setGameErrored(globals.game) file_utils.saveGameObject(globals.game) ownerMessage = string_utils.renderGameStatusMessage(globals.game) message.reply("This game has errored. Please wait for the bot owner to help.") else: ownerMessage = "Unable to process message from /u/{}, skipping".format(str(message.author)) try: reddit.sendMessage(globals.OWNER, "NCFAA game errored", ownerMessage) message.mark_read() except Exception as err2: log.warning("Error sending error message") log.warning(traceback.format_exc()) log.debug("Message processed after: %d", int(time.perf_counter() - startTime)) utils.clearLogGameID() for game in index.getGamesPastPlayclock(): log.debug("Game past playclock: {}".format(game.thread)) utils.cycleStatus(game, None) game.status.state(game.status.waitingOn).playclockPenalties += 1 penaltyMessage = "{} has not sent their number in over 24 hours, playclock penalty. This is their {} penalty.".format( string_utils.getCoachString(game, game.status.waitingOn), string_utils.getNthWord(game.status.state(game.status.waitingOn).playclockPenalties)) if game.status.state(game.status.waitingOn).playclockPenalties >= 3:
def processSubreddits(): subredditsCount = 0 groupsCount = 0 postsCount = 0 messagesSent = 0 foundPosts = [] for subreddits in database.getSubscribedSubreddits(): groupsCount += 1 subPostsCount = 0 startTimestamp = datetime.utcnow() earliestDatetime = datetime.utcnow() subredditsStrings = [] for subreddit in subreddits: subredditsStrings.append(subreddit['subreddit']) subredditDatetime = datetime.strptime(subreddit['lastChecked'], "%Y-%m-%d %H:%M:%S") if earliestDatetime - subredditDatetime > timedelta(seconds=0): earliestDatetime = subredditDatetime subredditsCount += 1 subredditString = '+'.join(subredditsStrings) #log.debug("Searching subreddit group: "+subredditString) submissions = [] hitEnd = True try: for submission in reddit.getSubredditSubmissions(subredditString): submissionCreated = datetime.utcfromtimestamp( submission.created_utc) if submissionCreated < earliestDatetime: hitEnd = False break if submissionCreated > startTimestamp: log.debug( "Found newer timestamp than start: {} : {}".format( submissionCreated, startTimestamp)) # startTimestamp = submissionCreated if submission.id in submissionIds: log.debug( "Found duplicate submission: {} : {} : {}".format( submission.id, submissionCreated, earliestDatetime)) else: submissionIds.add(submission.id) if len(submissionIds) > 5000: log.debug("Purging submissionIds") submissionIds.clear() submissions.append({ 'id': submission.id, 'dateCreated': submissionCreated, 'author': str(submission.author).lower(), 'link': "https://www.reddit.com" + submission.permalink, 'submission': submission, 'subreddit': str(submission.subreddit).lower() }) if len(submissions) % 50 == 0: log.info("Posts searched in " + str(submission.subreddit) + ": " + str(len(submissions))) except Exception as err: log.debug("Could not fetch subreddits: " + subredditString) log.warning(traceback.format_exc()) continue if hitEnd and len(submissions): log.info( "Messaging owner that that we might have missed a post in /r/" + subredditString) strList = strings.possibleMissedPostMessage( submissions[len(submissions) - 1]['dateCreated'], earliestDatetime, subredditString) strList.append("\n\n*****\n\n") strList.append(strings.footer) if not reddit.sendMessage(globals.OWNER_NAME, "Missed Post", ''.join(strList)): log.warning( "Could not send message to owner that we might have missed a post" ) if len(submissions): for submission in submissions: postsCount += 1 subPostsCount += 1 foundPosts.append(submission['id']) passesSubFilter = utility.passesFilter( submission['submission'], database.getFilter(submission['subreddit'])) if database.isPrompt(submission['author'], submission['subreddit']) and passesSubFilter and \ not database.isThreadReplied(submission['id']): log.info("Posting a prompt for /u/" + submission['author'] + " in /r/" + submission['subreddit']) subredditDefaultSubscribe = database.subredditDefaultSubscribe( submission['subreddit']) promptStrList = strings.promptPublicComment( submission['author'], submission['subreddit']) promptStrList.append("\n\n*****\n\n") promptStrList.append(strings.footer) resultCommentID = reddit.replySubmission( submission['id'], ''.join(promptStrList)) if resultCommentID is not None: database.addThread(submission['id'], resultCommentID, submission['author'], submission['subreddit'], "", datetime.utcnow(), 0, subredditDefaultSubscribe, True) for subscriber in database.getSubredditAuthorSubscriptions( submission['subreddit'], submission['author']): if submission['dateCreated'] > datetime.strptime( subscriber['lastChecked'], "%Y-%m-%d %H:%M:%S"): if (subscriber['filter'] != "none" and utility.passesFilter(submission, subscriber['filter'])) or \ (subscriber['filter'] == "none" and passesSubFilter): messagesSent += 1 log.info( "Messaging /u/%s that /u/%s has posted a new thread in /r/%s: %s", subscriber['subscriber'], submission['author'], submission['subreddit'], submission['id']) strList = strings.alertMessage( submission['author'], submission['subreddit'], submission['link'], subscriber['single']) strList.append("\n\n*****\n\n") strList.append(strings.footer) if reddit.sendMessage( subscriber['subscriber'], strings.messageSubject( subscriber['subscriber']), ''.join(strList)): database.checkRemoveSubscription( subscriber['ID'], subscriber['single'], submission['dateCreated'] + timedelta(0, 1)) else: log.warning( "Could not send message to /u/%s when sending update", subscriber['subscriber']) for subreddit in subreddits: database.checkSubreddit(subreddit['subreddit'], startTimestamp) #log.debug(str(subPostsCount)+" posts searched in: "+str(round(time.perf_counter() - subStartTime, 3))) return subredditsCount, groupsCount, postsCount, messagesSent, foundPosts
def sendPlayResultMessage(isHome, game, message): reddit.sendMessage( game[('home' if isHome == 'home' else 'away')]['coaches'], 'Result of Play', message) return reddit.getRecentSentMessage().id
def sendGameMessage(isHome, game, message, dataTable): reddit.sendMessage( game[('home' if isHome else 'away')]['coaches'], "{} vs {}".format(game['home']['name'], game['away']['name']), embedTableInMessage(message, dataTable)) return reddit.getRecentSentMessage().id
def processSubreddits(): subredditsCount = 0 groupsCount = 0 postsCount = 0 messagesSent = 0 foundPosts = [] for subreddits in database.getSubscribedSubreddits(): groupsCount += 1 subPostsCount = 0 startTimestamp = datetime.utcnow() earliestDatetime = datetime.utcnow() subredditsStrings = [] for subreddit in subreddits: subredditsStrings.append(subreddit['subreddit']) subredditDatetime = datetime.strptime(subreddit['lastChecked'], "%Y-%m-%d %H:%M:%S") if earliestDatetime - subredditDatetime > timedelta(seconds=0): earliestDatetime = subredditDatetime subredditsCount += 1 subredditString = '+'.join(subredditsStrings) #log.debug("Searching subreddit group: "+subredditString) submissions = [] hitEnd = True try: for submission in reddit.getSubredditSubmissions(subredditString): submissionCreated = datetime.utcfromtimestamp(submission.created_utc) if submissionCreated < earliestDatetime: hitEnd = False break if submissionCreated > startTimestamp: log.debug("Found newer timestamp than start: {} : {}".format(submissionCreated, startTimestamp)) # startTimestamp = submissionCreated if submission.id in submissionIds: log.debug("Found duplicate submission: {} : {} : {}".format(submission.id, submissionCreated, earliestDatetime)) else: submissionIds.add(submission.id) if len(submissionIds) > 5000: log.debug("Purging submissionIds") submissionIds.clear() submissions.append({'id': submission.id, 'dateCreated': submissionCreated, 'author': str(submission.author).lower(), 'link': "https://www.reddit.com"+submission.permalink, 'submission': submission, 'subreddit': str(submission.subreddit).lower()}) if len(submissions) % 50 == 0: log.info("Posts searched in "+str(submission.subreddit)+": "+str(len(submissions))) except Exception as err: log.debug("Could not fetch subreddits: "+subredditString) log.warning(traceback.format_exc()) continue if hitEnd and len(submissions): log.info("Messaging owner that that we might have missed a post in /r/"+subredditString) strList = strings.possibleMissedPostMessage(submissions[len(submissions) - 1]['dateCreated'], earliestDatetime, subredditString) strList.append("\n\n*****\n\n") strList.append(strings.footer) if not reddit.sendMessage(globals.OWNER_NAME, "Missed Post", ''.join(strList)): log.warning("Could not send message to owner that we might have missed a post") if len(submissions): for submission in submissions: postsCount += 1 subPostsCount += 1 foundPosts.append(submission['id']) passesSubFilter = utility.passesFilter(submission['submission'], database.getFilter(submission['subreddit'])) if database.isPrompt(submission['author'], submission['subreddit']) and passesSubFilter and \ not database.isThreadReplied(submission['id']): log.info("Posting a prompt for /u/"+submission['author']+" in /r/"+submission['subreddit']) subredditDefaultSubscribe = database.subredditDefaultSubscribe(submission['subreddit']) promptStrList = strings.promptPublicComment(submission['author'], submission['subreddit']) promptStrList.append("\n\n*****\n\n") promptStrList.append(strings.footer) resultCommentID = reddit.replySubmission(submission['id'], ''.join(promptStrList)) if resultCommentID is not None: database.addThread(submission['id'], resultCommentID, submission['author'], submission['subreddit'], "", datetime.utcnow(), 0, subredditDefaultSubscribe, True) for subscriber in database.getSubredditAuthorSubscriptions(submission['subreddit'], submission['author']): if submission['dateCreated'] > datetime.strptime(subscriber['lastChecked'], "%Y-%m-%d %H:%M:%S"): if (subscriber['filter'] != "none" and utility.passesFilter(submission, subscriber['filter'])) or \ (subscriber['filter'] == "none" and passesSubFilter): messagesSent += 1 log.info("Messaging /u/%s that /u/%s has posted a new thread in /r/%s: %s", subscriber['subscriber'], submission['author'], submission['subreddit'], submission['id']) strList = strings.alertMessage(submission['author'], submission['subreddit'], submission['link'], subscriber['single']) strList.append("\n\n*****\n\n") strList.append(strings.footer) if reddit.sendMessage(subscriber['subscriber'], strings.messageSubject(subscriber['subscriber']), ''.join(strList)): database.checkRemoveSubscription(subscriber['ID'], subscriber['single'], submission['dateCreated'] + timedelta(0,1)) else: log.warning("Could not send message to /u/%s when sending update", subscriber['subscriber']) for subreddit in subreddits: database.checkSubreddit(subreddit['subreddit'], startTimestamp) #log.debug(str(subPostsCount)+" posts searched in: "+str(round(time.perf_counter() - subStartTime, 3))) return subredditsCount, groupsCount, postsCount, messagesSent, foundPosts
log.warning(traceback.format_exc()) if globals.gameId is not None: log.debug("Setting game {} as errored".format(globals.gameId)) database.setGameErrored(globals.gameId) ownerMessage = "[Game]({}) errored. Click [here]({}) to clear."\ .format("{}{}".format(globals.SUBREDDIT_LINK, globals.logGameId[1:-1]), utils.buildMessageLink( globals.ACCOUNT_NAME, "Kick game", "kick {}".format(globals.gameId) )) else: ownerMessage = "Unable to process message from /u/{}, skipping".format(str(message.author)) try: reddit.sendMessage(globals.OWNER, "NCFAA game errored", ownerMessage) message.mark_read() except Exception as err2: log.warning("Error sending error message") log.warning(traceback.format_exc()) for threadId in database.getGamesPastPlayclock(): techFoul = True log.debug("Game past playclock: {}".format(threadId)) game = utils.getGameByThread(threadId) if not game['tip']['homeTip'] and not game['tip']['awayTip'] and game['waitingAction'] == 'tip': game['away']['playclockPenalties'] += 1 game['home']['playclockPenalties'] += 1 techFoul = False penaltyMessage = "You two souls both got a DOG at the same time. Please send your tip message." elif not game['tip']['homeTip'] and game['tip']['awayTip'] and game['waitingAction'] == 'tip':
def searchComments(searchTerm, startTime): errors = [] if searchTerm == globals.UPDATE_NAME: subscriptionType = True elif searchTerm == globals.SUBSCRIPTION_NAME: subscriptionType = False url = "https://api.pushshift.io/reddit/comment/search?q="+searchTerm+"&limit=100&sort=desc" try: requestTime = time.perf_counter() json = requests.get(url, headers={'User-Agent': globals.USER_AGENT}) requestSeconds = int(time.perf_counter() - requestTime) if json.status_code != 200: log.warning("Could not parse data for search term: "+searchTerm + " status: " + str(json.status_code)) errors.append("Could not parse data for search term: "+str(json.status_code) + " : " + url) return 0, 0, 0, errors comments = json.json()['data'] except Exception as err: log.warning("Could not parse data for search term: "+searchTerm) log.warning(traceback.format_exc()) errors.append("Could not parse data for search term: "+url) return 0, 0, 0, errors if len(comments) == 0: log.warning("Could not parse data for search term, no results: "+searchTerm + " status: "+str(json.status_code)) errors.append("Could not parse data for search term, no results: "+str(json.status_code) + " : " +url) return 0, 0, 0, errors elif requestSeconds > 80 and len(comments) > 0: log.warning("Long request, but returned successfully: "+str(requestSeconds)) timestamp = database.getCommentSearchTime(searchTerm) if timestamp is None: timestamp = startTime database.updateCommentSearchSeconds(searchTerm, timestamp) # we want to start at the oldest. Since we update the current timestamp at each item, # if we crash, we don't want to lose anything oldestIndex = len(comments) - 1 for i, comment in enumerate(comments): if datetime.utcfromtimestamp(comment['created_utc']) < timestamp: oldestIndex = i - 1 break if i == 99: log.info("Messaging owner that that we might have missed a comment") strList = strings.possibleMissedCommentMessage(datetime.utcfromtimestamp(comment['created_utc']), timestamp) strList.append("\n\n*****\n\n") strList.append(strings.footer) if not reddit.sendMessage(globals.OWNER_NAME, "Missed Comment", ''.join(strList)): log.warning("Could not send message to owner that we might have missed a comment") if oldestIndex == -1: return 0, 0, requestSeconds, errors commentsAdded = 0 commentsSearched = 0 for comment in comments[oldestIndex::-1]: if comment['author'].lower() != globals.ACCOUNT_NAME.lower(): commentsSearched += 1 if database.isBlacklisted(comment['author'].lower(), comment['subreddit'].lower()): continue log.info("Found public comment by /u/"+comment['author']) comment['link_author'] = str(reddit.getSubmission(comment['link_id'][3:]).author) result, data = utility.addUpdateSubscription(comment['author'], comment['link_author'], comment['subreddit'], datetime.utcfromtimestamp(comment['created_utc']), subscriptionType, None) posted = False if result != 'couldnotadd' and not database.alwaysPMForSubreddit(comment['subreddit'].lower()) \ and not database.isThreadReplied(comment['link_id'][3:]): strList = [] existingSubscribers = database.getAuthorSubscribersCount(comment['subreddit'].lower(), comment['link_author'].lower()) strList.extend( strings.confirmationComment(subscriptionType, comment['link_author'], comment['subreddit'], comment['link_id'][3:], existingSubscribers)) strList.append("\n\n*****\n\n") strList.append(strings.footer) log.info("Publicly replying to /u/%s for /u/%s in /r/%s:", comment['author'], comment['link_author'], comment['subreddit']) resultCommentID = reddit.replyComment(comment['id'], ''.join(strList)) if resultCommentID is not None: database.addThread(comment['link_id'][3:], resultCommentID, comment['link_author'].lower(), comment['subreddit'].lower(), comment['author'].lower(), datetime.utcnow(), existingSubscribers, subscriptionType, False) posted = True else: log.warning("Could not publicly reply to /u/%s", comment['author']) if not posted: strList = [] if result == 'couldnotadd': utility.checkDeniedRequests(data['subreddit']) strList.extend(strings.couldNotSubscribeSection([data])) else: if result == 'added': commentsAdded += 1 strList.extend(strings.confirmationSection([data])) elif result == 'updated': commentsAdded += 1 strList.extend(strings.updatedSubscriptionSection([data])) elif result == 'exist': strList.extend(strings.alreadySubscribedSection([data])) strList.append("\n\n*****\n\n") strList.append(strings.footer) log.info("Messaging confirmation for public comment to /u/%s for /u/%s in /r/%s:", comment['author'], comment['link_author'], comment['subreddit']) if not reddit.sendMessage(comment['author'], strings.messageSubject(comment['author']), ''.join(strList)): log.warning("Could not send message to /u/%s when sending confirmation for public comment", comment['author']) database.updateCommentSearchSeconds(searchTerm, datetime.utcfromtimestamp(comment['created_utc']) + timedelta(0, 1)) return commentsSearched, commentsAdded, requestSeconds, errors