def updateSidebar(fixturesData, r, subredditName): newTable = MakeRedditTable(fixturesData, r, subredditName) EndOfTableMarker = "[More International Fixtures](http://www.espncricinfo.com/ci/content/match/fixtures/index.html?days=30)." #Signature to look for that marks the end of table BeginningOfTableMarker = "**Upcoming International Fixtures:**" #Signature to look for that marks beginning of table try: settings = r.get_settings(subredditName) description_html = settings['description'] html_parser = HTMLParser.HTMLParser() description = html_parser.unescape(description_html) if ((description.find(BeginningOfTableMarker) == -1) or (description.find(EndOfTableMarker) == -1)): sendEmail( "We've got a problem", "Couldn't update sidebar, couldn't find either BeginningOfTableMarker or EndOfTableMarker. Trying again in 60 seconds..." ) return descriptionBegin = description.find(BeginningOfTableMarker) descriptionEnd = description.find(EndOfTableMarker) + len( EndOfTableMarker) description = description[:descriptionBegin] + newTable + description[ descriptionEnd:] settings = r.get_subreddit(subredditName).update_settings( description=description) except: sendEmail("We've got a problem", "Couldn't update sidebar, trying again in 60 seconds...")
def updateLineupPerThread(r,matchThreadLink): updatedThreads=[] text_file = open("updatedThreads.txt") for line in text_file: # if line!="": updatedThreads.append(line.strip().lower()) text_file.close() if updatedThreads.count(matchThreadLink)<1: updatedThreads.append(matchThreadLink) text_file=open('updatedThreads.txt', 'w') for line in updatedThreads: if line!="": print>>text_file, line text_file.close() submission = r.get_submission(matchThreadLink) selfText = submission.selftext teamOneName,teamOnePlayers=extractTeamInfo(selfText,1) teamTwoName,teamTwoPlayers=extractTeamInfo(selfText,2) threadTitle=submission.title.lower() if 'test' in threadTitle: format='tests' elif 'odi' in threadTitle: format='odi' elif 't20i' in threadTitle: format='t20i' else: return False,"Couldn't figure out the format." teamOneName=teamOneName.replace(" squad","") teamTwoName=teamTwoName.replace(" squad","") teamOneTable=teamOneName+"|M|R|HS|Avg|100|Wkt|BBI|Bowl Av.|5|Ct|St|"+"(v. )"+teamTwoName+"|M|R|HS|Avg|100|Wkt|BBI|Bowl Av.|5|Ct|St|\n" teamOneTable=teamOneTable+"|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|\n" teamTwoTable=teamTwoName+"|M|R|HS|Avg|100|Wkt|BBI|Bowl Av.|5|Ct|St|"+"(v. )"+teamOneName+"|M|R|HS|Avg|100|Wkt|BBI|Bowl Av.|5|Ct|St|\n" teamTwoTable=teamTwoTable+"|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|:-|\n" try: for player in teamOnePlayers: teamOneTable=teamOneTable+returnStatsPerPlayer(player,teamTwoName.lower(),format)+"\n" time.sleep(2) for player in teamTwoPlayers: teamTwoTable=teamTwoTable+returnStatsPerPlayer(player,teamOneName.lower(),format)+"\n" time.sleep(2) except: sendEmail("Couldn't update match thread with lineup","Link to thread: "+str(submission.url)) return False,"Something went wrong while updating thread. Try doing it manually." lineSplit=selfText.split("***") teamInfo=lineSplit[2] teamOneTable="\n\n"+teamOneTable+"\n" teamTwoTable="\n\n"+teamTwoTable+"\n" selfText=selfText.replace(selfText.split("***")[2],teamOneTable) selfText=selfText.replace(selfText.split("***")[3],teamTwoTable) html_parser = HTMLParser.HTMLParser() selfText = html_parser.unescape(selfText) submission.edit(selfText) return True,"Worked"
def updateLiveScores(r): ArrayOfCurrentlyRunningFixtures = getArrayOfCurrentlyRunningFixtures() if not ArrayOfCurrentlyRunningFixtures: return for runningFixture in ArrayOfCurrentlyRunningFixtures: matchThreadLink = runningFixture[0] liveThreadLink = runningFixture[1] try: matchScoreUpdater(r,liveThreadLink,matchThreadLink) except: sendEmail("Couldn't update live score","Quitting this loop, will try again next loop.") return
def updateLiveScores(r): ArrayOfCurrentlyRunningFixtures = getArrayOfCurrentlyRunningFixtures() if not ArrayOfCurrentlyRunningFixtures: return for runningFixture in ArrayOfCurrentlyRunningFixtures: matchThreadLink = runningFixture[0] liveThreadLink = runningFixture[1] try: matchScoreUpdater(r, liveThreadLink, matchThreadLink) except: sendEmail("Couldn't update live score", "Quitting this loop, will try again next loop.") return
def createMatchThreadWrapper(r,threadTitle,liveThreadURL,source,subreddit): #RealLink,matchInfo = getMatchInfoWrapper(liveThreadURL) #if not RealLink: # return [False,matchInfo] # At this point, we have a cricinfo live thread link #if not threadTitle: # threadTitle = matchInfo['title'] #If it's a test playing nation, tell them that the thread will be created automatically. #if ( source!='rCricketBot' and (WeCareAbout(matchInfo['teamInfo']['team1name']) or WeCareAbout(matchInfo['teamInfo']['team2name']))): # return [False,"Match thread creation request denied. \n\nAt least one of the teams has test status. A match thread will be created automatically approximately one hour before the game. If a thread hasn't been created please message /u/rreyv"] #If it's not a test playing nation, see if a thread already exists [alreadyExists, replyLink]=HasThreadBeenCreated(liveThreadURL) if alreadyExists: return [False,"Match thread has been created already for this match less than 12 hours ago. Here's the [link.]("+replyLink+")"] #At this line, the request to create the thread is either automated, or it's a match containing shitty teams threadText = "###" + threadTitle + "\n\n" threadText = threadText + "[Link to Cricinfo Live Commentary](" + liveThreadURL + ")" + " | Sort this thread by new posts | Reddit-Stream link for this thread" + "\n\n" + "***" + "\n\n" threadText = threadText + "***\n" #threadText = threadText + getMainThreadInformation(matchInfo) # other match related information #threadText = threadText + "\n\n" + "*Series links:* " + \ # "\n\n" + matchInfo['otherInfo'] + "\n\n" + "***" +"\n\n" threadText = threadText + getGeneralRedditStuff(source) html_parser = HTMLParser.HTMLParser() threadText = html_parser.unescape(threadText) try: submission = r.submit(subreddit, threadTitle, text=threadText) except: return [False, "Submission failed for some unknown reason. Maybe reddit was down? Please try again and if it fails, message /u/rreyv with the live thread link that you submitted."] #Update the SQL table with submission information InsertMatchThreadInfoIntoSQL(threadTitle,liveThreadURL,source,str(submission.url)) #By this line, the thread has been created TryLoop=None while not TryLoop: try: TryLoop=EditSubmission(r,submission) except: time.sleep(30) #By this line, the submission has been edited and we can tell the requestor about it. sendEmail("Started match thread","Created a new match thread "+str(submission.url)) return [True,"Match thread successfully created. [Here's the link](" + str(submission.url) +")."]
def createMatchThreadWrapper(r,threadTitle,liveThreadURL,source,subreddit): RealLink,matchInfo = getMatchInfoWrapper(liveThreadURL) if not RealLink: return [False,matchInfo] # At this point, we have a cricinfo live thread link if not threadTitle: threadTitle = matchInfo['title'] #If it's a test playing nation, tell them that the thread will be created automatically. if ( source!='rCricketBot' and (WeCareAbout(matchInfo['teamInfo']['team1name']) or WeCareAbout(matchInfo['teamInfo']['team2name']))): return [False,"Match thread creation request denied. \n\nAt least one of the teams has test status. A match thread will be created automatically approximately one hour before the game. If a thread hasn't been created please message /u/rreyv"] #If it's not a test playing nation, see if a thread already exists [alreadyExists, replyLink]=HasThreadBeenCreated(liveThreadURL) if alreadyExists: return [False,"Match thread has been created already for this match less than 12 hours ago. Here's the [link.]("+replyLink+")"] #At this line, the request to create the thread is either automated, or it's a match containing shitty teams threadText = "###" + threadTitle + "\n\n" threadText = threadText + "[Link to Cricinfo Live Commentary](" + liveThreadURL + ")" + " | Sort this thread by new posts | Reddit-Stream link for this thread" + "\n\n" + "***" + "\n\n" threadText = threadText + "***\n" #threadText = threadText + getMainThreadInformation(matchInfo) # other match related information #threadText = threadText + "\n\n" + "*Series links:* " + \ # "\n\n" + matchInfo['otherInfo'] + "\n\n" + "***" +"\n\n" threadText = threadText + getGeneralRedditStuff(source) html_parser = HTMLParser.HTMLParser() threadText = html_parser.unescape(threadText) try: submission = r.submit(subreddit, threadTitle, text=threadText) except: return [False, "Submission failed for some unknown reason. Maybe reddit was down? Please try again and if it fails, message /u/rreyv with the live thread link that you submitted."] #Update the SQL table with submission information InsertMatchThreadInfoIntoSQL(threadTitle,liveThreadURL,source,str(submission.url)) #By this line, the thread has been created TryLoop=None while not TryLoop: try: TryLoop=EditSubmission(r,submission) except: time.sleep(30) #By this line, the submission has been edited and we can tell the requestor about it. sendEmail("Started match thread","Created a new match thread "+str(submission.url)) return [True,"Match thread successfully created. [Here's the link](" + str(submission.url) +")."]
def OrangeRed(r): Moderators = [ 'rreyv', 'neoronin', 'brownboy13', 'rahulthewall', 'poop_monster', 'Envia', 'parlor_tricks', 'kabuliwallah', 'sunnydelish' ] subreddit = "india" already_done = [] try: for message in r.get_unread(limit=None): msgSubject = str(message.subject) msgAuthor = str(message.author) message.mark_as_read() if ((message.was_comment == False) and (message.id not in already_done)): if msgSubject.lower() == "add users": if msgAuthor in Moderators: replyText = AddUser(r, message) else: replyText = "Only moderators can use this command." elif msgSubject.lower() == "remove users": if msgAuthor in Moderators: replyText = RemoveUser(r, message) else: replyText = "Only moderators can use this command." elif msgSubject.lower() == "list users": if msgAuthor in Moderators: replyText = ListUsers(r) else: replyText = "Only moderators can use this command." elif msgSubject.lower().startswith("[mega thread]"): if msgAuthor in Moderators: replyText = CreateThread(r, message, subreddit) elif ((msgSubject.find('reddit.com') != -1) or (msgSubject.find('redd.it') != -1)): replyText = UpdateThread(r, message) else: replyText = "I don't know what you're trying to say." message.reply(replyText) already_done.append(message.id) except: sendEmail("Couldn't read inbox", "Couldn't read inbox")
def OrangeRed(r): Moderators=['rreyv','neoronin','brownboy13','rahulthewall','poop_monster','Envia','parlor_tricks','kabuliwallah','sunnydelish'] subreddit="india" already_done=[] try: for message in r.get_unread(limit=None): msgSubject=str(message.subject) msgAuthor=str(message.author) message.mark_as_read() if ((message.was_comment==False) and (message.id not in already_done)): if msgSubject.lower()=="add users": if msgAuthor in Moderators: replyText=AddUser(r,message) else: replyText="Only moderators can use this command." elif msgSubject.lower()=="remove users": if msgAuthor in Moderators: replyText=RemoveUser(r,message) else: replyText="Only moderators can use this command." elif msgSubject.lower()=="list users": if msgAuthor in Moderators: replyText=ListUsers(r) else: replyText="Only moderators can use this command." elif msgSubject.lower().startswith("[mega thread]"): if msgAuthor in Moderators: replyText=CreateThread(r,message,subreddit) elif ((msgSubject.find('reddit.com')!=-1) or (msgSubject.find('redd.it')!=-1)): replyText=UpdateThread(r,message) else: replyText="I don't know what you're trying to say." message.reply(replyText) already_done.append(message.id) except: sendEmail("Couldn't read inbox","Couldn't read inbox")
if __name__ == "__main__": # One time setup r = praw.Reddit( "/r/cricket sidebar updating and match thread creating bot by /u/rreyv. This does match updates every minute. Version 2.0" ) # reddit stuff subredditName = "cricket" r.login() # sign in! MTB = praw.Reddit( "MegaThreadBot by /u/rreyv. Checkout https://bitbucket.org/rreyv/megathreadbot for details. Currently only live on /r/india. Version 1.0" ) MTB.login() fixturesData = {} fixturesData = getFixturesDictionary(5) sendEmail("Bot has begun", "Yep it has") # SQL table init i = 0 # one time setup ends while True: # things that happen every four hours while True: # things that happen every 50 seconds updateLiveScores(r) # updateLineups(r) updateSidebar(fixturesData, r, subredditName) readInbox(r, subredditName) OrangeRed(MTB) time.sleep(50) i += 1 if i % 240 == 0:
from inboxHandler import readInbox from liveScoreHandler import updateLiveScores from lineupHandler import updateLineups from OrangeRed import OrangeRed if __name__=="__main__": #One time setup r = praw.Reddit('/r/cricket sidebar updating and match thread creating bot by /u/rreyv. This does match updates every minute. Version 2.0') #reddit stuff subredditName='cricket' r.login() #sign in! MTB = praw.Reddit('MegaThreadBot by /u/rreyv. Checkout https://bitbucket.org/rreyv/megathreadbot for details. Currently only live on /r/india. Version 1.0') MTB.login() fixturesData={} fixturesData=getFixturesDictionary(5) sendEmail("Bot has begun","Yep it has") # SQL table init i=0 #one time setup ends while True: #things that happen every four hours while True: #things that happen every 50 seconds updateLiveScores(r) #updateLineups(r) updateSidebar(fixturesData,r,subredditName) readInbox(r,subredditName) OrangeRed(MTB) time.sleep(50) i+=1; if i%240==0: