示例#1
0
def default(username, subject, body):
    color.print_color(
        'yellow',
        '-------------------------------\n' + "             DEFAULT\n" +
        "username: "******"\n" + "subject:  " + subject + "\n" +
        "body:     " + body + "\n" + '-------------------------------\n\n')
    logger.log(username + ' submitted an incorrect command')
示例#2
0
def destroy():
    global reddit, connection
    if connection:
        connection.close()
    connection = None
    reddit = None
    color.print_color('red', '----------------- DESTROYED -----------------')
示例#3
0
def feedback(username, user_feedback):
    color.print_color(
        'yellow',
        '-------------------------------\n' + '            FEEDBACK\n' +
        'username: '******'feedback: ' + user_feedback + "\n" +
        '-------------------------------\n\n')
    logger.log(username + ' submitted feedback')
示例#4
0
 def __init__(self, quiet_start=0, quiet_end=0):
     if quiet_end < quiet_start:
         color.print_color('red', 'Invalid Quiet Hours.')
         exit()
     self.quiet_start = quiet_start
     self.quiet_stop = quiet_end
     self.is_quiet = False
示例#5
0
def about_message():
    color.print_color(
        'yellow',
        "================================================================\n" +
        "\t\tGunDealsBot - A Sales Notifier Bot\n" +
        "================================================================\n\n")
    color.print_color(
        'blue', '\n--------------------------------------------------\n' +
        '\t\twww.reddit.com/r/gundeals' + '\n' +
        '--------------------------------------------------\n')
示例#6
0
def match_exception(username, item, message_id, title, permalink, url):
    color.print_color(
        'red',
        "match exception caught\n" + "username:   "******"\n" +
        #"email:   " + email + "\n" +
        #"twitter:   " + twitter + "\n" +
        "message id: " + message_id + "\n" + "item:       " + item + "\n" +
        "title:      " + title + "\n" + "reddit url: " + permalink + "\n" +
        "sale link:  " + url + "\n" + "stacktrace:\n" +
        traceback.format_exc() + "\n\n")
    logger.log('Match exception caught')
示例#7
0
def match(username, email, twitter, item, message_id, title, permalink, url):
    emailmsg = ''
    if email != None:
        emailmsg = ' and email was sent to ' + email
    color.print_color(
        'magenta',
        "-------------------------------\n" + "        SUBMISSION MATCH\n" +
        "username:   "******"\n" + "email:   " + xstr(email) + "\n" +
        "twitter:   " + xstr(twitter) + "\n" + "message id: " + message_id +
        "\n" + "item:       " + item + "\n" + "title:      " + title + "\n" +
        "reddit url: " + permalink + "\n" + "sale link:  " + url + "\n" +
        '-------------------------------\n\n')
    logger.log('Notified ' + username + ' of match for ' + item + emailmsg)
示例#8
0
def send_email(email, username, item, title, permalink, url):
    title = title.decode('UTF-8').encode('ascii', 'replace')
    subject = 'GunDealsBot found a match for ' + item
    sender = accountinfo.gmail_user
    recipient = email
    htmltext = inbox.compose_greeting(username) + \
    "<br><br>We have found a match for your subscription to <b>'" + item + "'</b>! " + \
    "Below you will find the details:" + \
    "<br><br><b>Deal Title: </b>" + title + \
    "<br><b>Links:</b>" + \
    "<br><a href='" + permalink + "'>Reddit Link</a>" +  \
    "<br><a href='" + url + "'>Sale Link</a>" + \
    "<br><br>To unsubscribe from these alerts, message /u/GunDealsBot with the subject '" + \
    item + "' and with the message body 'Unsubscribe'.<br>" + \
    "--GunDealBot<br><br><code><a href='https://github.com/metroshica/reddit-bot-gundeals'>Source Code on Github<a>" + \
    "<br><a href='http://reddit.com/u/metroshica'>/u/metroshica</a>" + \
    "<br><a href='http://reddit.com/r/gundeals'>/r/gundeals</a>"


    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = recipient

    plaintext = "Hi there, this is just placeholder text."

    part1 = MIMEText(plaintext, 'plain')
    part2 = MIMEText(htmltext, 'html')

    msg.attach(part1)
    msg.attach(part2)

    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(accountinfo.gmail_user, accountinfo.gmail_pwd)
        server.sendmail(sender, recipient, msg.as_string())
        server.close()
        color.print_color('cyan', '\n\n' +
                            '----------- EMAIL SENT -----------\n' +
                            'destination: ' + email + '\n' +
                            'subject:     ' + subject + '\n\n') 
    except:
        color.print_color('red', '\n\n' +
                            '----------- EMAIL FAILED -----------\n' +
                            'destination: ' + email + '\n' +
                            'subject:     ' + subject + '\n\n') 
示例#9
0
def run_bot():
    global start_time, run
    logger.log('Started gundeals bot')
    output.about_message()
    while True:
        try:
            check_for_commands()
            if run:
                read_inbox()
                crawl_subreddit('gundeals')
                color.print_color('yellow', times.get_time_passed(start_time))
        except KeyboardInterrupt:
            color.print_color('red', 'Interrupted')
            exit()
        except:
            handle_crash(traceback.format_exc())
        sleep(SLEEP_SECONDS)
示例#10
0
def check_for_commands():
    global reddit, run

    unread_messages = []
    try:
        unread_messages = reddit.get_unread(limit=None)
    except:
        output.read_inbox_exception()
        reddit.send_message(accountinfo.developerusername, "Bot Exception - Read Inbox", traceback.format_exc())

    for unread_message in unread_messages:
        username, message_id, subject, body = \
            (str(unread_message.author).lower(),
             unread_message.id,
             inbox.format_subject(unread_message.subject.lower()),
             unread_message.body.lower())

        if username == accountinfo.developerusername:

            if subject == 'kill' or subject == 'stop' or subject == 'pause':
                run = False
                try:
                    unread_message.reply("Standing by for further instructions.")
                    unread_message.mark_as_read()
                    color.print_color('red', '--------- Bot paused by developer ---------')
                except:
                    handle_crash(traceback.format_exc())
            if subject == 'run' or subject == 'start' or subject == 'resume':
                run = True
                try:
                    unread_message.reply("Thanks, I was getting bored!")
                    unread_message.mark_as_read()
                    color.print_color('green', '--------- Bot resumed by developer ---------')
                except:
                    handle_crash(traceback.format_exc())

            if subject == 'test':
                color.print_color('blue', '--------- I am being tested ---------')
                try:
                    if run:
                        unread_message.reply("Bot is active!")
                    else:
                        unread_message.reply("Bot is INACTIVE!")
                    unread_message.mark_as_read()
                except:
                    handle_crash(traceback.format_exc())
示例#11
0
def run_alerts():
    global connection, select_users
    # if selected_users is empty, send to all, otherwise just send to selected_users
    i = 0
    num = 0
    if not select_users:
        needs_alert = connection.cursor().execute(database.GET_USERNAMES_THAT_NEED_ALERT).fetchall()
        num = len(needs_alert)
        for row in needs_alert:
            username = row[database.COL_ALERTS_USERNAME]
            entry = (username, 1)  # 1 == True
            try:
                reddit.send_message(username, subject, compose_alert(username))
                connection.cursor().execute(database.INSERT_ROW_ALERTS, entry)
                connection.commit()
                color.print_color('blue', 'message sent to ' + username)
                i += 1
            except:
                color.print_color('red', "ALERT FAILED: " + username + \
                                  "\n\t \n\t \n" + traceback.format_exc())
                connection.rollback()
                connection.close()
                exit()
            sleep(2)
    else:
        num = len(select_users)
        for username in select_users:
            try:
                reddit.send_message(username, subject, compose_alert(username))
                color.print_color('blue', 'message sent to ' + username)
                i += 1
            except:
                color.print_color('red', "ALERT FAILED: " + username + \
                                  "\n\t \n\t \n" + traceback.format_exc())
            sleep(2)
    print "Sent message to " + str(i) + "/" + str(num) + " users."
示例#12
0
def unsubscribe_exception(username, item):
    color.print_color(
        'red', 'unsubscribe exception caught\n' + "username:   "******"\n" + "item:       " + item + "\n" + "stacktrace: " + "\n" +
        traceback.format_exc() + "\n\n")
    logger.log('Unsubscribe exception caught')
示例#13
0
def read_inbox():
    global connection, reddit
    i = 0

    unread_messages = []
    try:
        unread_messages = reddit.get_unread(limit=None)
    except:
        output.read_inbox_exception()
        reddit.send_message(accountinfo.developerusername, "Bot Exception - Read Inbox", traceback.format_exc())

    for unread_message in unread_messages:
        i += 1
        username, message_id, subject, body = \
            (str(unread_message.author).lower(),
             unread_message.id,
             inbox.format_subject(unread_message.subject.lower()),
             unread_message.body.lower())

        if username == 'reddit':
            try:
                reddit.send_message(accountinfo.developerusername, "FORWARD: " + subject, body)
                unread_message.mark_as_read()
            except:
                handle_crash(traceback.format_exc())

        elif ('unsubscribe' in body and 'all' in body) \
                or ('unsubscribe' in subject and 'all' in subject):
            try:
                cursor = connection.cursor()
                cursor.execute(database.REMOVE_ALL_SUBSCRIPTIONS_BY_USERNAME, (username,))
                cursor.execute(database.REMOVE_ALL_MATCHES_BY_USERNAME, (username,))
                unread_message.reply(inbox.compose_unsubscribe_all_message(username))
                unread_message.mark_as_read()
                connection.commit()
                output.unsubscribe_all(username)
            except:
                connection.rollback()
                output.unsubscribe_all_exception(username)
                reddit.send_message(accountinfo.developerusername, "Bot Exception - Unsubscribe All", traceback.format_exc())

        elif body == 'unsubscribe' and subject.replace(' ', '') != '':
            try:
                cursor = connection.cursor()
                cursor.execute(database.REMOVE_ROW_SUBSCRIPTIONS, (username, subject))
                cursor.execute(database.REMOVE_MATCHES_BY_USERNAME_AND_SUBJECT, (username, subject))
                unread_message.reply(inbox.compose_unsubscribe_message(username, subject))
                unread_message.mark_as_read()
                connection.commit()
                output.unsubscribe(username, subject)
            except:
                connection.rollback()
                output.unsubscribe_exception(username, subject)
                reddit.send_message(accountinfo.developerusername, "Bot Exception - Unsubscribe", traceback.format_exc())

        # Item must be 1+ non-space characters.
        elif 'subscribe' in body and len(inbox.format_subject(subject).replace(' ', '')) > 0:
            email = None
            twitter = None
            if 'email:' in body or 'e-mail:' in body:
                try:
                    email = body.split('mail:')[1].replace('\n',' ').strip().split()[0]
                except:
                    pass
            if 'twitter:' in body:
                twitter = body.split('twitter:')[1].replace('\n',' ').strip().split()[0]
            subscription = (username, message_id, subject, email, twitter, times.get_current_timestamp())
            try:
                cursor = connection.cursor()
                try:
                    cursor.execute(database.INSERT_ROW_SUBMISSIONS, subscription)
                    unread_message.reply(inbox.compose_subscribe_message(username, subject))
                except:
                    pass
                unread_message.mark_as_read()
                connection.commit()
                output.subscribe(username, subject)
            except:
                connection.rollback()
                output.subscribe_exception(username, subject)
                reddit.send_message(accountinfo.developerusername, "Bot Exception - Subscribe", traceback.format_exc())

        elif subject == 'information' or subject == 'help':
            try:
                cursor = connection.cursor()
                cursor.execute(database.GET_SUBSCRIPTIONS_BY_USERNAME, (username,))
                unread_message.reply(inbox.compose_information_message(username, cursor.fetchall()))
                unread_message.mark_as_read()
                output.information(username)
            except:
                output.information_exception(username)
                reddit.send_message(accountinfo.developerusername, "Bot Exception - Information", traceback.format_exc())

        elif subject == 'feedback':
            try:
                reddit.send_message(accountinfo.developerusername, "Feedback for sales__bot",
                                    inbox.compose_feedback_forward(username, body))
                unread_message.reply(inbox.compose_feedback_message(username))
                unread_message.mark_as_read()
                output.feedback(username, body)
            except:
                output.feedback_exception(username, body)
                reddit.send_message(accountinfo.developerusername, "Bot Exception - Feedback", traceback.format_exc())
        else:
            try:
                unread_message.reply(inbox.compose_default_message(username, subject, body))
                unread_message.mark_as_read()
                output.default(username, subject, body)
            except:
                output.default_exception(username, subject, body)
                reddit.send_message(accountinfo.developerusername, "Bot Exception - Default", traceback.format_exc())
        sleep(2)
    color.print_color('cyan', str(i) + ' UNREAD MESSAGES')
示例#14
0
    color.print_color('red', '----------------- DESTROYED -----------------')


def handle_crash(stacktrace):
    global connection, reddit
    destroy()
    reset = False
    while not reset:
        try:
            initialize()
            reddit.send_message(accountinfo.developerusername, "Exception Handled", stacktrace)
            reset = True
        except:
            sleep(15)


__author__ = 'Metroshica'
if __name__ == "__main__":
    try:
        global start_time
        start_time = times.get_current_timestamp()
        initialize()
        run_bot()
    except KeyboardInterrupt:
        color.print_color('red', 'Interrupted')
        exit()
    except:
        color.print_color('red', traceback.format_exc())
        exit()
 
示例#15
0
def unsubscribe_all(username):
    color.print_color(
        'red',
        '-------------------------------\n' + '         UNSUBSCRIBE ALL\n' +
        'username: '******'-------------------------------\n\n')
    logger.log(username + ' unsubscribed from all notifications')
示例#16
0
def subscribe(username, item):
    color.print_color(
        'green', '-------------------------------\n' +
        '           SUBSCRIBE\n' + 'username: '******'item:     ' + item + "\n" + '-------------------------------\n\n')
    logger.log(username + ' subscribed to ' + item)
示例#17
0
def information(username):
    color.print_color(
        'green',
        '-------------------------------\n' + '         INFORMATION\n' +
        'username: '******'-------------------------------\n\n')
    logger.log(username + ' asked for information')
示例#18
0
def default_exception(username, subject, body):
    color.print_color(
        'red', 'unsubscribe exception caught\n' + "username:   "******"\n" + "subject:    " + subject + "\n" + "body:       " + body + "\n" +
        "stacktrace: " + "\n" + traceback.format_exc() + "\n\n")
    logger.log('Unsubscribe exception caught')
示例#19
0
def feedback_exception(username, user_feedback):
    color.print_color(
        'red', 'feedback exception caught\n' + "username:   "******"\n" + "feedback:   " + "\n" + user_feedback + "\n" + "stacktrace: " +
        "\n" + traceback.format_exc() + "\n\n")
    logger.log('Feedback exception caught')
示例#20
0
def information_exception(username):
    color.print_color(
        'red', 'information exception caught\n' + "username:   "******"\n" + "stacktrace: " + "\n" + traceback.format_exc() + "\n\n")
    logger.log('Information exception caught')
示例#21
0
def handle_crash(stacktrace):
    global connection, reddit
    color.print_color('red', stacktrace)
    reddit.send_message(accountinfo.developerusername, "Bot Alerts Crashed", stacktrace)
    connection.close()
    exit()
示例#22
0
def get_submissions_exception():
    color.print_color(
        'red', "get submissions exception caught\n" + "stacktrace:\n" +
        traceback.format_exc() + "\n\n")
    logger.log('Get submissions exception caught')
示例#23
0
def read_inbox_exception():
    color.print_color(
        'red', "read inbox exception caught\n" + "stacktrace:\n" +
        traceback.format_exc() + "\n\n")
    logger.log('Read inbox exception caught')
示例#24
0
def unsubscribe(username, item):
    color.print_color(
        'red', '-------------------------------\n' +
        '           UNSUBSCRIBE\n' + 'username: '******'item:     ' + item + '\n' + '-------------------------------\n\n')
    logger.log(username + ' unsubscribed from ' + item)