import datetime

import sqlalchemy

from okcupyd.db import mailbox, model, txn
import time


class MessageHandler(object):

    def __init__(self, user, *handlers):
        self.user = user
        self.handlers = handlers

    def handle_messages(self, sleep_time=30, sync_until=None):
        while True:
            _, new_messages = mailbox.Sync(self.user).inbox()
            with txn() as session:
                for message in new_messages:
                    session.add(message)
                for handler in self.handlers:
                    handler(self.user, new_messages)
            time.sleep(sleep_time)


def do_it():
    def handle(user, messages):
        if len(messages) == 0:
            return
        messages = messages[::-1]
        new_wall = u'\n'.join(
            u'<a href="http://www.okcupid.com/profile/{0}">{0}</a>: {1}\n'.format(
                message.sender.handle, message.text
            )
            for message in messages
            if message.sender.handle != 'pumpkinmania8'
        ) + user.profile.essays.my_life
        user.profile.essays.my_life = new_wall.replace('\n\n', '\n')

    import okcupyd
    MessageHandler(okcupyd.User.from_credentials('pumpkinmania8', 'thisisforokc'),
                   handle).handle_messages()

@@ -366,133 +366,8 @@
 x()%0A
-            with txn() as session:%0A                for message in new_messages:%0A                    session.add(message)%0A    
     
@@ -404,20 +404,16 @@
 ndlers:%0A
-    
         
@@ -494,25 +494,8 @@
 )%0A%0A%0A
-def do_it():%0A    
 def 
@@ -522,20 +522,16 @@
 s):%0A    
-  
-  
 if len(m
@@ -545,20 +545,16 @@
 ) == 0:%0A
-    
         
@@ -560,20 +560,16 @@
  return%0A
-    
     mess
@@ -594,20 +594,16 @@
 -1%5D%0A    
-  
-  
 new_wall
@@ -617,20 +617,16 @@
 '.join(%0A
-    
         
@@ -708,20 +708,16 @@
         
- 
-   
 message.
@@ -744,20 +744,16 @@
 ge.text%0A
-    
         
@@ -758,28 +758,24 @@
   )%0A        
-    
 for message 
@@ -794,20 +794,16 @@
         
-  
-  
 if messa
@@ -846,48 +846,29 @@
     
-    ) + user.profile.essays.my_life%0A    
+)%0A    print new_wall%0A
     
@@ -929,16 +929,204 @@
  '%5Cn')%0A%0A
+def reset(user, ignore):%0A    with txn() as session:%0A        messages = model.Message.query_no_txn(session)%0A        handle(user, sorted(messages, key=lambda m: m.created_at))%0A%0Adef do_it():%0A
     impo
@@ -1238,22 +1238,21 @@
         
-handle
+reset
 ).handle
@@ -1261,10 +1261,23 @@
 essages(
+sleep_time=30
 )%0A

Fix stuff.