Exemple #1
0
def main():
    """Main Script for posting congratulations."""
    my_diag = classes.Diagnostic(script=str(os.path.basename(__file__)))
    voting_post = get_raw_id()
    my_diag.raw_id = voting_post.id
    my_diag.title = "Contest Congratulations"
    bot_disclaimer_text = functions.bot_disclaimer()
    voting_post.mod.sticky(state=False)

    # # Turn contest mode OFF on the original voting post
    # Need to do this in order to count the votes, otherwise all posts show 1 vote.
    voting_post.mod.contest_mode(state=False)

    # Prepare the loop for parsing contestant maps
    # Prepare the text of the post.
    # Congratulations_text is a boilerplate template for each month's congratulations post.
    # There are a number of variables that need to be changed on this template though.
    # We will do that in the for loop.
    with open('Congratulations_text.txt', 'r') as f:
        congrats_data = str(f.read())

    # Prepare a regex script to find the unique ID on each comment.
    id_regex = re.compile(r'\^\^\^\^\w\w\w\w\w\w')

    # # The Loop
    # Gets top four highest upvoted comments and iterates thru them doing operations each time.
    yyyymm = 0
    for comment in voting_post.comments:
        score = int(comment.score)
        found_id = id_regex.search(comment.body)  # Find those ID's
        if found_id is None:
            continue
        message_id = str(found_id.group()).replace('^^^^', '')

        for obj in cont_db.current_list:
            if message_id == str(obj.raw_id):
                mapcomment = comment.reply("Map by: " + str(obj.author))
                mapcomment.mod.distinguish(how='yes')
                cont_db.add_vote_count_to_submission(raw_id=message_id,
                                                     votecount=score)
                yyyymm = int(obj.cont_date)

    n = 0
    winner, win_map_url = '', ''
    for obj in cont_db.get_sorted_top_of_month(month=yyyymm)[:4]:
        n += 1
        if n == 1:
            winner = obj.author
            win_map_url = obj.url
        congrats_data = congrats_data.replace(str('%' + str(n) + 'PLACEUSER%'),
                                              str(obj.author))
        congrats_data = congrats_data.replace(
            str('%' + str(n) + 'PLACEVOTES%'), str(obj.votes))
        congrats_data = congrats_data.replace(str('%' + str(n) + 'PLACEMAP%'),
                                              str(obj.map_name))
        congrats_data = congrats_data.replace(str('%' + str(n) + 'PLACEURL%'),
                                              str(obj.url))
    # # Post congratulations post to reddit

# Put the contest post URL into the congratulations template.
    congrats_data = congrats_data.replace('%VOTINGPOSTURL%',
                                          voting_post.shortlink)
    congrats_data = congrats_data.replace('%MYUSERID%', functions.my_reddit_ID)
    post_title = (
        'Congratulations to /u/{}: winner of {}\'s Monthly Map Contest!'.
        format(winner, contest_month_pretty))
    congrats_submission = r.subreddit('mapporn').submit(post_title,
                                                        selftext=congrats_data)
    congrats_shortlink = congrats_submission.shortlink
    congrats_submission.mod.distinguish()
    try:
        congrats_submission.mod.approve()
        congrats_submission.mod.sticky()
    except Exception as e:
        functions.send_reddit_message_to_self(
            title='Error encountered',
            message=('Could not sticky this post: {}    \n{}    \n\n'.format(
                congrats_shortlink, str(e))))

    # # Post congratulations post to social media
    # Download the image locally
    winning_image = 'temp.jpg'
    request = requests.get(win_map_url, stream=True)
    if request.status_code == 200:
        with open(winning_image, 'wb') as image:
            for chunk in request:
                image.write(chunk)
        filesize = os.path.getsize('temp.jpg')
        if filesize > 3070000:  # If it's too big social media sites won't like it.
            os.remove(winning_image)
            winning_image = 'misc_images/01.png'  # This is a backup image to post in lieu of the winning map.
    else:
        winning_image = 'misc_images/01.png'

    # Post to social media.
    # Now that we have the image we can run the function to post it to the social media sites
    try:
        generic_post = classes.GenericPost(filename=winning_image,
                                           title=(post_title + ' ' +
                                                  congrats_shortlink))
        social_media_dict = generic_post.post_to_all_social()
        functions.send_reddit_message_to_self(title='The new Congratulations post has just posted.',
                                              message='The congrats post is here:    {}\n    \n{}    \n{}')\
            .format(str(congrats_shortlink), str(voting_post.shortlink), str(social_media_dict['tweet_url']))
    except Exception as e:
        functions.send_reddit_message_to_self(
            title='Could not post to social media',
            message='Could not post announcement to socialmeda:    \n{}    \n\n'
            .format(str(e)))

    # # Send message to winner congratulating them
    congrats_message = (
        '[Congratulations, you won this month\'s Map Contest!](' +
        congrats_shortlink + ')    \n' + bot_disclaimer_text)
    try:
        r.redditor(winner).message('Congratulations', congrats_message)
    except Exception as e:
        functions.send_reddit_message_to_self(
            title='Could not send message to winner',
            message='Error: {}'.format(str(e)))
    log_db.add_row_to_db(diagnostics=my_diag.make_dict(), passfail=1)
Exemple #2
0
"""

import classes
import csv
import functions
import os
import praw
import requests
import time
from WhereWorld import get_image_name

r = praw.Reddit('bot1')
my_reddit_id = 'Petrarch1603'
script = str(os.path.basename(__file__))
disclaimer = functions.bot_disclaimer()
MessageReply = 'Your map has been received.   ' + '\n' + 'Look for the voting post for the contest soon.    ' + '\n' + \
               '        ' + '\n' + disclaimer


class WhereWorldRow:
    """
    Self-running class to parse Where World Messages.
    * Downloads the image locally
    * Adds row to CSV with url, and answer
    * Send Message to bot, subject: 'WW' with two lines:
    *                                                      url
    *                                                      answer_text
    """
    def __init__(self, msg_obj, csv_path='data/locations.csv'):
        self.csv_path = csv_path
Exemple #3
0
"""Script for creating a voting post for a new /r/MapPorn Map Contest"""

from datetime import datetime, timedelta
import classes
import functions
import praw

r = praw.Reddit('bot1')
cont_db = classes.ContestDB()
numbersubmitted = cont_db.live_count
botDisclaimerText = functions.bot_disclaimer()


def prepare_voting_text():
    """Prepares the Voting Post Self Text with information populated.

    :return: Voting Post text with information filled out.
    :rtype: str

    """

    with open('VotingText.txt', 'r') as my_file:
        my_voting_text = my_file.read()
    lastmonthfile = open('data/lastmonth.txt', 'r')
    last_month_url = (lastmonthfile.read())
    next_week = datetime.now() + timedelta(days=5)  # Need at least 5 days to vote.
    next_sunday = functions.next_weekday(next_week, 6)
    pretty_next_sunday = next_sunday.strftime('%A %B %d, %Y')
    my_voting_text = my_voting_text.replace('%NUMBERSUBMITTED%', str(numbersubmitted))
    my_voting_text = my_voting_text.replace('%ENDDATE%', str(pretty_next_sunday))
    my_voting_text = my_voting_text.replace('%MYREDDITID%', functions.my_reddit_ID)
import os
import praw
import csv
from functions import my_reddit_ID, bot_disclaimer
import datetime


# Print time and date for verification
print(datetime.datetime.now())

r = praw.Reddit('bot1')
disclaimer = bot_disclaimer()
MessageReply = 'Your map has been received.   ' + '\n' + 'Look for the voting post for the contest soon.    ' + '\n' + \
               '        ' + '\n' + disclaimer
                # To Do: add contest date to the MessageReply, that way users know when the contest is.

for message in r.inbox.unread():
    if message.subject == "Map Contest Submission":
        print(message.subject)
        submission = message.body
        submission = os.linesep.join([s for s in submission.splitlines() if s])  # removes extraneous line breaks
        submission = submission.splitlines()  # Turn submission into a list
        submission = [w.replace('Link: ', '') for w in submission] # Replace the text 'Link: ' with blankspace. I'd like to do a regex process to fix this sometime, but can't figure it out.
        submission.append(message.author)  # Add author value
        submission.append(message)  # Add unique value for the message. This is important for indexing later on.
        # Now make that list a row a CSV
        with open('submissions.csv', 'a') as submitFile:
            reader = csv.reader(submitFile)
            wr = csv.writer(submitFile)
            wr.writerow(submission)
            message.reply(MessageReply)
        social_media_post = classes.GenericPost(filename=image_file_name, title=post_message_with_url)
        socialmediadict = social_media_post.post_to_all_social()
        functions.send_reddit_message_to_self('New Voting Post Posted',
                                              'A new votingpost.py has been run. Check the post to make'
                                              ' sure the bot did it right.   \nHere\'s the link to the '
                                              'post: ' + shortlink + '   \nHere\'s the social media '
                                              'links:    \n' + str(socialmediadict['tweet_url']))
        return str(socialmediadict['tweet_url'])
    except Exception as eee:
        error_message += "Could not post results to social media.   \n{}    \n\n".format(str(eee))
    if error_message != '':
        functions.send_reddit_message_to_self(title="error", message=error_message)


if __name__ == "__main__":
    bot_disclaimer_text = functions.bot_disclaimer()
    contest_year = (datetime.now() - timedelta(days=10)).year
    cont_db = classes.ContestDB()
    finalists_list = cont_db.get_top_posts_of_year()

    # Verify that all the finalist maps have valid URLs:
    for obj in finalists_list:
        if urllib.request.urlopen(obj.url).getcode() != 200:
            finalists_list.remove(obj)

    post_message = 'Vote Now for the best map of ' + str(contest_year) + '!'
    r = praw.Reddit('bot1')
    shortlink = main()
    print(shortlink)

    # Create Grid Collage