def read_output(fil): global filedir read_out = open(filedir + '/' + fil, 'r') read = read_out.read() if read == '': uselog('runde_texta er tom, wtf?') sys.exit() read_out.close() return read
def create_necessary_file(filename): ''' If a file does not exist, make it ''' if not os.path.exists(filename): uselog('The file {} does not exist. Creating...'.format(filename)) open(filename, 'w').close() try: write_cache('', filename) except(NameError): pass
def post_update(r, tag, new_content, submission=None, comment=None): ''' Updates a submission or a comment between tags with new_content. ''' if submission: temp_item = r.submission(submission) temp_content = temp_item.selftext elif comment: temp_item = r.comment(comment) temp_content = temp_content.body else: uselog('You didn\'t specify neither a submission or a comment.\n' 'Tried to insert this text: \'{}\''.format(new_content)) sys.exit() temp_content_kamper = re.search(r'.*\[\]\(#{tag}\)((.|\n)*)' '\[\]\(\/{tag}\).*'.format(tag=tag), temp_content, flags=re.MULTILINE | re.DOTALL).group(1) if temp_content_kamper == new_content: uselog('No changes discovered. Sleeping.') else: uselog('Discovered new scores, updating...') temp_content = re.sub( r'\[\]\(\#{tag}\)((.|\n)*)\[\]\(\/{tag}\)'.format(tag=tag), '[](#{tag}){new_content}[](/{tag})'.format(new_content=new_content, tag=tag), temp_content, flags=re.MULTILINE | re.DOTALL) temp_item.edit(temp_content) uselog('Updated! Sleeping.')
def post_to_reddit(r, league_name, round_number, post_text, subreddit): ''' Tries to post the 'post_text' to the 'subreddit, but will first check if the post already has been submitted. In any situation, this function will always return the submission object. ''' # Check first if it already has been submitted _already_created = thread_already_created(r, league_name, round_number, subreddit) if _already_created: subm = r.submission(_already_created) uselog('Seems that this already has been posted. ' 'Got submission.id \'{}\''.format(subm.id)) return subm else: uselog('Post doesn\'t exist, posting.') post_title = '{}, {}. runde'.format(league_name, round_number) subm = r.subreddit(subreddit).submit(post_title, selftext=post_text, send_replies=False, resubmit=False) # subm_link = 'http://redd.it/{}'.format(subm.id) return subm
def main(): # Before anything else check the 'postponed_matches.cache' # (generated by the function 'get_raw_round') # - if a match in cache # - check it's date. if within normal range (+/- 2 days), # post it. # - posting has to be done with a slightly different title and text # Get the essentials _get_matches = scraping.get_matches(league) _get_raw_table = scraping.get_raw_table(league) # '_get_raw_round' checks if the next round starts within two days. If not # it stops the script _get_raw_round = scraping.get_raw_round(league, _get_matches['all_matches'], postponed_file) _get_full_round = scraping.get_full_round(_get_raw_table, _get_raw_round['round_matches']) _get_table = scraping.get_table(_get_raw_table, _get_full_round) league_name = _get_matches['league_name'] active_round = _get_raw_round['active_round'] # Make the normal post round_text = posting.make_round_post(league, _get_full_round, _get_table, league_name, active_round) posted_object = posting.post_to_reddit(r, league_name, active_round, round_text, subreddit) # Countdown _round_start_stop = round_start_stop(league, _get_raw_round['round_matches']) _round_start = _round_start_stop['start_seconds'] uselog('Roundstart: {}'.format(_round_start)) # Sove fram til margintid før rundestart. Sov så det gjenstår ca litt over # 1 time før rundestart (1 time tilsvarer 3600 sekunder) # if league: # _round_start -= 3800 # uselog('_round_start: {}'.format(_round_start)) if _round_start > 0: uselog('Sleeping for {} seconds', format(_round_start)) sleep(_round_start) # Lag kamptråder der det blir riktig #posting.post_match_threads(posted_object.id, _get_full_round) # Starter runden uselog('Round started') sleep(2) while calculating.round_start_stop( league, scraping.get_raw_round( league, scraping.get_matches(league)['all_matches'], postponed_file)['round_matches'])['stop_round'] is False: # Updating match info uselog('Checking for new scores...') posting.post_update( r, 'kamper', posting.make_round_post_matches( scraping.get_full_round( _get_raw_table, scraping.get_raw_round( league, scraping.get_matches(league)['all_matches'], postponed_file)['round_matches'])), submission=posted_object.id) # Sleep before starting with new update of round sleep(10)
import ligabot.posting config = ligabot.config.get_config() uselog = ligabot.uselog.uselog scraping = ligabot.scraping posting = ligabot.posting calculating = ligabot.calculating round_start_stop = calculating.round_start_stop subreddit = config['reddit']['subreddit'] # Authenticate to reddit try: uselog('Authenticating to reddit...') r = praw.Reddit(client_id=config['reddit']['client_id'], client_secret=config['reddit']['client_secret'], password=config['reddit']['password'], user_agent=config['reddit']['useragent'], username=config['reddit']['username']) uselog('Authenticating OK.') except Exception as e: uselog('Couldn\'t authenticate to reddit:\n{}'.format(e)) sys.exit() dt = datetime.datetime nowdate = dt.now().strftime('%d.%m.%Y') fulldate = dt.now().strftime('%d.%m.%Y %H.%M.%S') postponed_file = 'postponed_matches.list'
flags=re.MULTILINE | re.DOTALL) write_output(runde_text, filnavn) try: oppdater_runde = str(sys.argv[1]) except IndexError: oppdater_runde = False if oppdater_runde == 'nei': pass else: lag_runde_fil() lag_tabellfil() # Manuell rundeoppdatering uselog('Runden er laget.') while True: # åpne fil og hent info om kamper round_file = bsify_local(read_output('runde.html')) print(round_file) print('Hvilken kamp ønsker du å endre resultatet til? (1-4, alle, ' 'c=start runden, x=avslutt runden)') match_no = input() if match_no == 'c': update_score(no_of_matches=len(round_file.split('\n')), match_no='c') continue elif match_no == 'x': update_score(no_of_matches=len(round_file.split('\n')), match_no='x') continue print('Hva skal settes som nytt resultat?')
def get_raw_round(league, matches, postponed_file): ''' Get this round\'s matches. Returns 'round_matches' and 'active_round' as kwargs. ''' global nowdate, uselog active_round = '' # If the round is starting within the next two days, start scraping for match in matches: _days_to = calculating.days_to(nowdate, match['date']) if _days_to >= 0: if _days_to < 3: active_round = match['round_no'] break else: uselog('The next round doesn\'t start until {} days.'.format( _days_to)) sys.exit() else: uselog('The next round doesn\'t start until {} days.'.format( _days_to)) sys.exit() active_round = '19' round_matches = [] # postponed_matches = [] # temp_postponed_matches = [] last_match_date = '' for match in matches: if match['round_no'] == active_round: match_link = match['status_link'] # Get extra info from match page #match.append(match_info(match_link)['time']) if league is False: ##### print(match) sys.exit() ##### match['match_info_time'] = match['status_text'] else: match['match_info_time'] = match_info(match_link)['time'] match_date = '{} {}.00'.format(match['date'], match['match_info_time']) # # Check if the match is more than 6 days # # away from the last match checked # if last_match_date == '': # last_match_date = match_date # elif calculating.days_to(last_match_date, match_date) >= 6: # # If more than 6 days to match, add to postponed-file # _postponed_matches = read_cache(postponed_file) # _postponed_link = match[1][5] # _postponed_versus = '{} vs {}'.format(match[1][1], match[1][6]) # print('postponing match \'{}\''.format(_postponed_versus)) # if str(match[1]) in _postponed_matches: # continue # else: # _temp_postponed = '{}, '.format(league) # for objects in match: # for item in objects: # _temp_postponed += '{}, '.format(item) # _temp_postponed = re.sub(r', $', r'', _temp_postponed, # flags=re.MULTILINE | re.DOTALL) # else: # last_match_date = match_date round_matches.append(match) return {'round_matches': round_matches, 'active_round': active_round}