def updateExpired(self): try: self.logInfo("Checking for expirations") query = "SELECT id, bearer, issuer, type FROM tracker_notes WHERE expiry < now() AND status = 0" for note in self.getRows(query): self.logInfo('Note %s expired' % note[0]) self.updateNote(note[0], 'status', 2) # promise if note[3] == 0: code = 2 # offer elif note[3] == 4: code = 8 # need elif note[3] == 5: code = 9 # request elif note[3] == 10: code = 12 # Create event E = Event(note[0], 0, code, datetime.now(), note[2], note[1]) E.save() except Exception, e: raise Exception("Cleaning database failed: %s" % e)
def parsePayment(self,tweet): try: self.logInfo("Parsing tweet %s [payment]" % tweet['tweet_id']) # Strip out user accout h = re.search('(.*)(@%s)(.*)'% (ISSUER_ACCOUNT), tweet['content'], re.IGNORECASE) if h: statement = h.group(1) + h.group(3) else: raise Exception("Issuer not found") r = re.search('@(\w+)(.*)', statement) if r: recipient = r.group(1) else: raise Exception("Recipient not found") # Check not to self if recipient == tweet['author']: raise Exception("Issuer and recipient are the same") tags = tweet['tags'] #TODO Check if the number of tejas payed match the tejas issued for tag in tags: query = "SELECT e.* \ FROM tracker_events e, tracker_tweets t \ WHERE (t.tag_1 = %(tag)d OR t.tag_2 = %(tag)d OR t.tag_3=%(tag)d ) \ AND t.tweet_id = e.tweet_id \ AND to_user='******' and from_user = '******'" % {'tag':tag,'recipient':recipient,'author':tweet['author']} for recipient_event in self.getRows(query): note = self.getNote(recipient_event[2]) if tweet['author'].lower() != note['issuer']: raise Exception("Close attempt by non-issuer") if note['status'] != 10 and note['status']!=4: raise Exception("Note already closed") if tweet['url'] is None or tweet['url']=='': self.updateNote(note['id'], 'status', 4) code = 4 #payment with error it is marked as offer else: self.updateNote(note['id'], 'status', 3) code = 3 #payment correct it is a transfer # Create event E = Event(note['id'], tweet['tweet_id'], code, tweet['created'], tweet['author'], recipient) E.save() # Log event self.logInfo("[X] '%s' closed note %s" % (tweet['author'], note['id'])) self.setParsed(tweet['tweet_id']) except Exception, e: self.logWarning("Processing payment %s failed: %s" % (tweet['tweet_id'], e)) self.setParsed(tweet['tweet_id'], '-')
def get_message(): data = request.get_json() print(json.dumps(data)) if "standby" in data["entry"][0]: Event( data["entry"][0]["standby"][0]["sender"]["id"], datetime.now(), "get_message", "INI", datetime.now(), "New Message from {}".format( data["entry"][0]["standby"][0]["sender"]["id"])) return "OK", 200 event = Event( data["entry"][0]["messaging"][0]["sender"]["id"], datetime.now(), "get_message", "INI", datetime.now(), "New Message from {}".format( data["entry"][0]["messaging"][0]["sender"]["id"])) # event.update("OK ", datetime.now(), json.dumps(data)) entry = Entry(**data["entry"][0]) message = Messaging(**entry.messaging[0]) if "message" in entry.messaging[0]: process_message(message, event) event.update("OK ", datetime.now(), "Receive OK!") return "OK", 200 if "postback" in entry.messaging[0]: process_postback(message, event) event.update("OK ", datetime.now(), "Receive OK!") return "OK", 200 event.update("OK ", datetime.now(), "Receive OK!") return "OK", 200
def parseRedemption(self, tweet): try: self.logInfo("Parsing tweet %s [redemption]" % tweet['tweet_id']) from_user = tweet['author'] # If tweet has no reply to id if tweet['reply_to_id'] is None: raise Exception("Tweet is not a reply") # If tweet has a reply_to_id, parse as redemption else: original_id = self.findOriginal(tweet['reply_to_id'], tweet['tweet_id']) note = self.getNote(original_id) to_user = note['issuer'] # Check original exists if note is False: raise Exception("Original note not found") # Check tweet author is current bearer if note['bearer'] != from_user: raise Exception("User is not the current note bearer") # Check note is open (i.e. not expired or redeemed) if note['status'] != 0: if note['status'] == 1: raise Exception("Note has already been redeemed") if note['status'] == 2: raise Exception("Note has expired") message = note['promise'] # Process redemption self.updateNote(note['id'], 'status', 1) E = Event(note['id'], tweet['tweet_id'], 1, tweet['created'], from_user, to_user) E.save() # Log redemption self.logInfo('[T] @%s redeemed %s from @%s' % (to_user, message, from_user)) # Tweet event self.sendTweet('@%s thanked @%s for %s http://www.punkmoney.org/note/%s' % (from_user, to_user, note['promise'], note['id'])) self.setParsed(tweet['tweet_id']) except Exception, e: self.logWarning("Processing redemption %s failed: %s" % (tweet['tweet_id'], e)) self.setParsed(tweet['tweet_id'], '-')
def createRequest(self, tweet): try: query = "SELECT id FROM tracker_notes WHERE id = '%s'" % tweet['tweet_id'] if self.getSingleValue(query) is None: query = "INSERT INTO tracker_notes(id, issuer, bearer, promise, created, expiry, status, transferable, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)" params = (tweet['tweet_id'], tweet['author'].lower(), tweet['recipient'].lower(), tweet['message'], tweet['created'], tweet['expiry'], 0, 0, 10) self.queryDB(query, params) # Create an event E = Event(tweet['tweet_id'],10,10,tweet['created'], tweet['author'], tweet['recipient']) E.save() else: self.logWarning('Note %s already exists' % tweet['tweet_id']) return False except Exception, e: raise Exception("Creating thanks note from tweet %s failed: %s" % (tweet['tweet_id'], e))
def parseClose(self, tweet): try: # Check if this is a close instruction c = re.match('(.*)(close)(.*)', tweet['content']) # check tweet has a reply_to_id if c: if tweet.get('reply_to_id', False) is not False: original_id = self.findOriginal(tweet['reply_to_id'], tweet['tweet_id']) note = self.getNote(original_id) if tweet['author'].lower() != note['issuer']: raise Exception("Close attempt by non-issuer") if note['status'] != 0: raise Exception("Note already closed") self.updateNote(note['id'], 'status', 1) if note['type'] == 4: code = 6 elif note['type'] == 5: code = 7 elif note['type'] == 10: code = 11 # Create event E = Event(note['id'], tweet['tweet_id'], code, tweet['created'], tweet['author'], '') E.save() # Log event self.logInfo("[X] '%s' closed note %s" % (tweet['author'], note['id'])) self.setParsed(tweet['tweet_id']) elif tweet.get('reply_to_id', False) is False: self.setParsed(tweet['tweet_id'], '-') raise Exception("Close failed: original not found") except Exception, e: self.logWarning("Processing %s failed: %s" % (tweet['tweet_id'], e)) self.setParsed(tweet['tweet_id'], '-')
def verify(): event = Event(None, datetime.now(), "verify", "INI", datetime.now(), "New Verification") if request.args.get("hub.mode") == "subscribe" and request.args.get( "hub.challenge"): event.update("PRO", datetime.now(), "hub.challenge") if not request.args.get( "hub.verify_token") == os.environ["VERIFY_TOKEN"]: event.update("ERR", datetime.now(), "Verification token mismatch") return "Verification token mismatch", 403 event.update("OK ", datetime.now(), "Verification OK") return request.args["hub.challenge"], 200 return "Hello world", 200
def createRequest(self, tweet): try: query = "SELECT id FROM tracker_notes WHERE id = '%s'" % tweet[ 'tweet_id'] if self.getSingleValue(query) is None: query = "INSERT INTO tracker_notes(id, issuer, bearer, promise, created, expiry, status, transferable, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)" params = (tweet['tweet_id'], tweet['author'].lower(), tweet['recipient'].lower(), tweet['message'], tweet['created'], tweet['expiry'], 0, 0, 10) self.queryDB(query, params) # Create an event E = Event(tweet['tweet_id'], 10, 10, tweet['created'], tweet['author'], tweet['recipient']) E.save() else: self.logWarning('Note %s already exists' % tweet['tweet_id']) return False except Exception, e: raise Exception("Creating thanks note from tweet %s failed: %s" % (tweet['tweet_id'], e))
def _load_event(self, elem): logging.getLogger().debug('----- event from current view: <%s>' % (elem.attrib['intent'])) if (elem.attrib.has_key('module') and elem.attrib.has_key('function')): if (elem.attrib.has_key('action-id')): return Event(elem.attrib['control-id'], elem.attrib['intent'], elem.attrib['action-id'], elem.attrib['module'], elem.attrib['function']) else: return Event(elem.attrib['control-id'], elem.attrib['intent'], None, elem.attrib['module'], elem.attrib['function']) elif (elem.attrib.has_key('action-id')): return Event(elem.attrib['control-id'], elem.attrib['intent'], elem.attrib['action-id']) else: # This case should never happen logging.getLogger().error( 'Loading failed: An event should have at least action-id or module function defined. Exiting now...' ) raise Exception('Loading failed', 'event is not having minimum required fields')
def parsePromise(self, tweet): try: # Tweet flag default true tweet_errors = True # Strip out hashtag h = re.search('(.*)(%s|%s)(.*)' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if h: statement = h.group(1) + h.group(3) else: raise Exception("Hashtag not found") # Get recipient r = re.search('(.*)@(\w+)(.*)', statement) if r: tweet['recipient'] = r.group(2) statement = r.group(1).strip() + r.group(3) self.saveUser(tweet['recipient'], intro=True) else: # (Don't tweet this as an error) tweet_errors = False; raise Exception("Recipient not found") # Check not to self if tweet['recipient'] == tweet['author']: raise Exception("Issuer and recipient are the same") # Check Transferability (optional) t = re.match('(.*)( NT )(.*)', statement, re.IGNORECASE) if t: tweet['transferable'] = False statement = t.group(1) + t.group(3) else: tweet['transferable'] = True # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.match('(.*) Expires in (\d+) (\w+)(.*)', statement, re.IGNORECASE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) statement = e.group(1) + e.group(4) else: tweet['expiry'] = None # Get condition c = re.match('(.*)( if )(.*)', statement, re.IGNORECASE) if c: tweet['condition'] = c.group(3) else: tweet['condition'] = None # Get promise p = re.match('(.*)(promise)(.*)', statement, re.IGNORECASE) if p: if p.group(1).strip().lower() == 'i': promise = p.group(3) else: promise = p.group(1).strip() + p.group(3) else: raise Exception("Promise not found") # Clean up promise ''' Remove trailing white space, full stop and word 'you' (if found) ''' promise = promise.strip() while promise[-1] == '.': promise = promise[:-1] if promise[0:4] == 'you ': promise = promise[4:] tweet['promise'] = promise # Processing promise self.setParsed(tweet['tweet_id']) self.createNote(tweet) E = Event(tweet['tweet_id'], tweet['tweet_id'], 0, tweet['created'], tweet['author'], tweet['recipient']) E.save() self.sendTweet('@%s promised @%s %s http://www.punkmoney.org/note/%s' % (tweet['author'], tweet['recipient'], promise, tweet['tweet_id'])) self.logInfo('[P] @%s promised @%s %s.' % (tweet['author'], tweet['recipient'], tweet['tweet_id'])) except Exception, e: self.logWarning("Processing promise %s failed: %s" % (tweet['tweet_id'], e)) if tweet_errors is not False: self.sendTweet('@%s Sorry, your promise [%s] didn\'t parse. Try again: http://www.punkmoney.org/print/' % (tweet['author'], tweet['tweet_id'])) self.setParsed(tweet['tweet_id'], '-')
while promise[-1] == '.': promise = promise[:-1] if promise[0:4] == 'you ': promise = promise[4:] tweet['promise'] = promise except Exception, e: raise Exception # Processing promise try: self.setParsed(tweet['tweet_id']) self.createNote(tweet) E = Event(tweet['tweet_id'], tweet['tweet_id'], 0, tweet['created'], tweet['author'], tweet['recipient']) E.save() self.sendTweet( '@%s promised @%s %s http://www.punkmoney.org/note/%s' % (tweet['author'], tweet['recipient'], tweet['promise'], tweet['tweet_id'])) self.logInfo( '[P] @%s promised @%s %s.' % (tweet['author'], tweet['recipient'], tweet['tweet_id'])) except Exception, e: self.logWarning("Processing promise %s failed: %s" % (tweet['tweet_id'], e)) if tweet_errors is not False: self.sendTweet( '@%s Sorry, your promise [%s] didn\'t parse. Try again: http://www.punkmoney.org/print/'
def parseNeed(self, tweet): try: # Strip out hashtag h = re.search('(.*)(%s|%s)(.*)' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if h: statement = h.group(1) + h.group(3) else: raise Exception("Hashtag not found") # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.search('(.*) Expires in (\d+) (\w+)(.*)', statement, re.IGNORECASE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) statement = e.group(1) + e.group(4) else: tweet['expiry'] = None # Get thing offered/needed p = re.match('(.*)(need[s]?)(.*)', statement, re.IGNORECASE) if p: if p.group(1).strip().lower() == 'i': item = p.group(3) else: item = p.group(1).strip() + p.group(3) else: raise Exception("Item not found") # Get condition c = re.match('(.*)( if )(.*)', item, re.IGNORECASE) if c: tweet['condition'] = c.group(3) else: tweet['condition'] = None # Clean up promise ''' Remove trailing white space, full stop and word 'you' (if found) ''' item = item.strip() while item[-1] == '.': item = item[:-1] tweet['item'] = item self.createOffer(5, tweet) # Create event E = Event(tweet['tweet_id'], '0', 5, tweet['created'], tweet['author'], '') E.save() # Log event self.logInfo('[N] @%s needs %s.' % (tweet['author'], tweet['tweet_id'])) # Tweet self.sendTweet('[N] @%s needs %s http://www.punkmoney.org/note/%s' % (tweet['author'], item, tweet['tweet_id'])) self.setParsed(tweet['tweet_id']) except Exception, e: self.logWarning("Processing %s failed: %s" % (tweet['tweet_id'], e)) self.sendTweet('@%s Sorry, your need [%s] didn\'t parse. Try again: http://www.punkmoney.org/print/' % (tweet['author'], tweet['tweet_id'])) self.setParsed(tweet['tweet_id'], '-')
def parseThanks(self, tweet): try: self.logInfo("Parsing tweet %s [thanks]" % tweet['tweet_id']) from_user = tweet['author'] # If tweet has no reply to id if tweet['reply_to_id'] is None: h = re.search('(.*)(%s|%s)(.*)' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if h: tweet['message'] = h.group(1) + h.group(3).strip() self.createThanks(tweet) tweet['message'] = 'for ' + tweet['message'] self.saveUser(tweet['recipient'], intro=True) # Log thanks message = '[Thanks] @%s thanked @%s %s' % (tweet['author'], tweet['recipient'], tweet['message']) self.logInfo(message) self.sendTweet('@%s thanked @%s %s http://www.punkmoney.org/note/%s' % (tweet['author'], tweet['recipient'], tweet['message'], tweet['tweet_id'])) self.setParsed(tweet['tweet_id']) # If tweet has a reply_to_id, parse as redemption else: original_id = self.findOriginal(tweet['reply_to_id'], tweet['tweet_id']) note = self.getNote(original_id) to_user = note['issuer'] # Check original exists if note is False: raise Exception("Original note not found") # Check tweet author is current bearer if note['bearer'] != from_user: raise Exception("User is not the current note bearer") # Check note is open (i.e. not expired or redeemed) if note['status'] != 0: if note['status'] == 1: raise Exception("Note has already been redeemed") if note['status'] == 2: raise Exception("Note has expired") message = note['promise'] # Process thanks self.updateNote(note['id'], 'status', 1) E = Event(note['id'], tweet['tweet_id'], 1, tweet['created'], from_user, to_user) E.save() # Log thanks self.logInfo('[T] @%s thanked @%s for %s' % (to_user, from_user, message)) # Tweet event self.sendTweet('@%s thanked @%s for %s http://www.punkmoney.org/note/%s' % (from_user, to_user, note['promise'], note['id'])) self.setParsed(tweet['tweet_id']) except Exception, e: self.logWarning("Processing thanks %s failed: %s" % (tweet['tweet_id'], e)) self.setParsed(tweet['tweet_id'], '-')
def parseTransfer(self, tweet): try: self.logInfo("Parsing tweet %s [transfer]" % tweet['tweet_id']) # Get issuer and recipient from_user = tweet['author'] to_user = tweet['to_user'] # Create user self.saveUser(to_user) # If issuer and recipient are the same, skip if from_user == to_user: raise Exception("Issuer and recipient are the same") # Find original tweet this is a reply to original_id = self.findOriginal(tweet['reply_to_id'], tweet['tweet_id']) # Check note exists if original_id is None: raise Exception("Original note could not be found") # Get original note note = self.getNote(original_id) # Check transferer is current bearer if from_user != note['bearer']: raise Exception("User %s is not the current note bearer" % from_user) # Check note is open (i.e. not expired or redeemed) if note['status'] != 0: if note['status'] == 1: raise Exception("Note has already been redeemed") if note['status'] == 2: raise Exception("Note has expired") # Check note is transferable if note['transferable'] != 1: raise Exception("Note is non-transferable") # Check recipient is trusted [Disabled] ''' if self.checkTrusted(note['issuer'], to_user) is False: raise Exception("Transferee not trusted by issuer") ''' self.saveUser(to_user, intro=True) # Process transfer self.setParsed(tweet['tweet_id']) self.updateNote(note['id'], 'bearer', to_user) # Create event E = Event(note['id'], tweet['tweet_id'], 3, tweet['created'], from_user, to_user) E.save() # Log transfer self.logInfo('[Tr] @%s transferred %s to @%s' % (tweet['author'], note['id'], to_user)) self.setParsed(tweet['tweet_id']) except Exception, e: self.setParsed(tweet['tweet_id'], '-') self.logWarning("Processing transfer %s failed: %s" % (tweet['tweet_id'], e))
def parsePromise(self, tweet): # If this promise is a reply with no content, create promise from note it is a reply to r = re.match('@(\w+) promise %s|%s' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if r and tweet.get('reply_to_id', None) is not None: note = self.getNote(tweet['reply_to_id']) tweet['recipient'] = note['issuer'] if note['type'] == 10: if note['bearer'].strip() != tweet['author'].strip(): raise Exception('Promise issued by non-bearer') else: tweet['issuer'] = tweet['author'] else: tweet['issuer'] = tweet['author'] # Check Transferability (optional) t = re.match('(.*)( NT )(.*)', tweet['content'], re.IGNORECASE) if t: tweet['transferable'] = False else: tweet['transferable'] = True tweet['promise'] = note['promise'] # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.match('(.*) Expires in (\d+) (\w+)(.*)', tweet['content'], re.IGNORECASE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) else: tweet['expiry'] = None tweet_errors = False tweet['condition'] = None # Close request if note['type'] == 10: self.updateNote(note['id'], 'status', 1) E = Event(note['id'], tweet['tweet_id'], 11, tweet['created'], tweet['author'], tweet['recipient']) E.save() # If this is an original promise... else: try: # Tweet flag default true tweet_errors = True # Strip out hashtag h = re.search('(.*)(%s|%s)(.*)' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if h: statement = h.group(1) + h.group(3) else: raise Exception("Hashtag not found") # Get recipient r = re.search('(.*)@(\w+)(.*)', statement) if r: tweet['recipient'] = r.group(2) statement = r.group(1).strip() + r.group(3) self.saveUser(tweet['recipient'], intro=True) else: # (Don't tweet this as an error) tweet_errors = False; raise Exception("Recipient not found") # Check not to self if tweet['recipient'] == tweet['author']: raise Exception("Issuer and recipient are the same") # Check Transferability (optional) t = re.match('(.*)( NT )(.*)', statement, re.IGNORECASE) if t: tweet['transferable'] = False statement = t.group(1) + t.group(3) else: tweet['transferable'] = True # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.match('(.*) Expires in (\d+) (\w+)(.*)', statement, re.IGNORECASE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) statement = e.group(1) + e.group(4) else: tweet['expiry'] = None # Get condition c = re.match('(.*)( if )(.*)', statement, re.IGNORECASE) if c: tweet['condition'] = c.group(3) else: tweet['condition'] = None # Get promise p = re.match('(.*)(promise)(.*)', statement, re.IGNORECASE) if p: if p.group(1).strip().lower() == 'i': promise = p.group(3) else: promise = p.group(1).strip() + p.group(3) else: raise Exception("Promise not found") # Clean up promise ''' Remove trailing white space, full stop and word 'you' (if found) ''' promise = promise.strip() while promise[-1] == '.': promise = promise[:-1] if promise[0:4] == 'you ': promise = promise[4:] tweet['promise'] = promise except Exception, e: raise Exception
while promise[-1] == '.': promise = promise[:-1] if promise[0:4] == 'you ': promise = promise[4:] tweet['promise'] = promise except Exception, e: raise Exception # Processing promise try: self.setParsed(tweet['tweet_id']) self.createNote(tweet) E = Event(tweet['tweet_id'], tweet['tweet_id'], 0, tweet['created'], tweet['author'], tweet['recipient']) E.save() self.sendTweet('@%s promised @%s %s http://www.punkmoney.org/note/%s' % (tweet['author'], tweet['recipient'], tweet['promise'], tweet['tweet_id'])) self.logInfo('[P] @%s promised @%s %s.' % (tweet['author'], tweet['recipient'], tweet['tweet_id'])) except Exception, e: self.logWarning("Processing promise %s failed: %s" % (tweet['tweet_id'], e)) if tweet_errors is not False: self.sendTweet('@%s Sorry, your promise [%s] didn\'t parse. Try again: http://www.punkmoney.org/print/' % (tweet['author'], tweet['tweet_id'])) self.setParsed(tweet['tweet_id'], '-') # parseTransfer # parse and save a transfer def parseTransfer(self, tweet): try:
def parsePromise(self, tweet): # If this promise is a reply with no content, create promise from note it is a reply to r = re.match('@(\w+) promise %s|%s' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if r and tweet.get('reply_to_id', None) is not None: note = self.getNote(tweet['reply_to_id']) tweet['recipient'] = note['issuer'] if note['type'] == 10: if note['bearer'].strip() != tweet['author'].strip(): raise Exception('Promise issued by non-bearer') else: tweet['issuer'] = tweet['author'] else: tweet['issuer'] = tweet['author'] # Check Transferability (optional) t = re.match('(.*)( NT )(.*)', tweet['content'], re.IGNORECASE) if t: tweet['transferable'] = False else: tweet['transferable'] = True tweet['promise'] = note['promise'] # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.match('(.*) Expires in (\d+) (\w+)(.*)', tweet['content'], re.IGNORECASE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) else: tweet['expiry'] = None tweet_errors = False tweet['condition'] = None # Close request if note['type'] == 10: self.updateNote(note['id'], 'status', 1) E = Event(note['id'], tweet['tweet_id'], 11, tweet['created'], tweet['author'], tweet['recipient']) E.save() # If this is an original promise... else: try: # Tweet flag default true tweet_errors = True # Strip out hashtag h = re.search('(.*)(%s|%s)(.*)' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if h: statement = h.group(1) + h.group(3) else: raise Exception("Hashtag not found") # Get recipient r = re.search('(.*)@(\w+)(.*)', statement) if r: tweet['recipient'] = r.group(2) statement = r.group(1).strip() + r.group(3) self.saveUser(tweet['recipient'], intro=True) else: # (Don't tweet this as an error) tweet_errors = False raise Exception("Recipient not found") # Check not to self if tweet['recipient'] == tweet['author']: raise Exception("Issuer and recipient are the same") # Check Transferability (optional) t = re.match('(.*)( NT )(.*)', statement, re.IGNORECASE) if t: tweet['transferable'] = False statement = t.group(1) + t.group(3) else: tweet['transferable'] = True # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.match('(.*) Expires in (\d+) (\w+)(.*)', statement, re.IGNORECASE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) statement = e.group(1) + e.group(4) else: tweet['expiry'] = None # Get condition c = re.match('(.*)( if )(.*)', statement, re.IGNORECASE) if c: tweet['condition'] = c.group(3) else: tweet['condition'] = None # Get promise p = re.match('(.*)(promise)(.*)', statement, re.IGNORECASE) if p: if p.group(1).strip().lower() == 'i': promise = p.group(3) else: promise = p.group(1).strip() + p.group(3) else: raise Exception("Promise not found") # Clean up promise ''' Remove trailing white space, full stop and word 'you' (if found) ''' promise = promise.strip() while promise[-1] == '.': promise = promise[:-1] if promise[0:4] == 'you ': promise = promise[4:] tweet['promise'] = promise except Exception, e: raise Exception
def parsePromise(self, tweet): expressions = self.types_map['promise'] for expression in expressions: try: # Tweet flag default true tweet_errors = True # Strip out user accout h = re.search('(.*)(@%s)(.*)'% (ISSUER_ACCOUNT), tweet['content'], re.IGNORECASE) if h: statement = h.group(1) + h.group(3) else: raise Exception("Issuer not found") tweet['transferable'] = False # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.match('(.*) Expira en (\d+) (\w+)(.*)', statement, re.IGNORECASE|re.UNICODE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) statement = e.group(1) + e.group(4) else: tweet['expiry'] = None # Get condition c = re.match('(.*)( if )(.*)', statement, re.IGNORECASE) if c: tweet['condition'] = c.group(3) else: tweet['condition'] = None # Get promise p = re.match('(.*)(%s)(.*)con(.*)' % expression, statement, re.IGNORECASE) if p: print p.groups() if p.group(1).strip().lower() == 'i': promise = p.group(3) else: promise = p.group(1).strip() + p.group(3) else: continue # Get bearer r = re.search('@(\w+)(.*)', promise) if r: tweet['recipient'] = tweet['author'] #The recipient for the debt is the author of the tweet tweet['author'] = r.group(1) promise = r.group(2).strip() self.saveUser(tweet['author'], intro=True) else: # (Don't tweet this as an error) tweet_errors = False; raise Exception("Recipient not found") # Check not to self if tweet['recipient'] == tweet['author']: raise Exception("Issuer and recipient are the same") # Clean up promise ''' Remove trailing white space, full stop and word 'you' (if found) ''' promise = promise.strip() while promise[-1] == '.': promise = promise[:-1] if promise[0:4] == 'you ': promise = promise[4:] tweet['promise'] = promise except Exception, e: raise e if promise: # Processing promise try: self.setParsed(tweet['tweet_id']) self.createNote(tweet) self.sendWelcome(tweet['author'], tweet['recipient'],tweet['tweet_id']) E = Event(tweet['tweet_id'], tweet['tweet_id'], 10, tweet['created'], tweet['author'], tweet['recipient']) E.save() self.sendTweet('@%s %s @%s %s http://www.punkmoney.org/note/%s' % (expression ,tweet['author'], tweet['recipient'], tweet['promise'], tweet['tweet_id'])) self.logInfo('[P] @%s %s @%s %s.' % (expression, tweet['author'], tweet['recipient'], tweet['tweet_id'])) break except Exception, e: self.logWarning("Processing promise %s failed: %s" % (tweet['tweet_id'], e)) if tweet_errors is not False: self.sendTweet('@%s Sorry, your promise [%s] didn\'t parse. Try again: http://www.punkmoney.org/print/' % (tweet['author'], tweet['tweet_id'])) self.setParsed(tweet['tweet_id'], '-')
def parseThanks(self, tweet): try: self.logInfo("Parsing tweet %s [thanks]" % tweet['tweet_id']) from_user = tweet['author'] # If tweet has no reply to id if tweet['reply_to_id'] is None: h = re.search('(.*)(%s|%s)(.*)' % (HASHTAG, ALT_HASHTAG), tweet['message'], re.IGNORECASE) if h: tweet['message'] = h.group(1) + h.group(3).strip() self.createThanks(tweet) tweet['message'] = 'for ' + tweet['message'] self.saveUser(tweet['recipient'], intro=True) # Log thanks message = '[Thanks] @%s thanked @%s %s' % ( tweet['author'], tweet['recipient'], tweet['message']) self.logInfo(message) self.sendTweet( '@%s thanked @%s %s http://www.punkmoney.org/note/%s' % (tweet['author'], tweet['recipient'], tweet['message'], tweet['tweet_id'])) self.setParsed(tweet['tweet_id']) # If tweet has a reply_to_id, parse as redemption else: original_id = self.findOriginal(tweet['reply_to_id'], tweet['tweet_id']) note = self.getNote(original_id) to_user = note['issuer'] # Check original exists if note is False: raise Exception("Original note not found") # Check tweet author is current bearer if note['bearer'] != from_user: raise Exception("User is not the current note bearer") # Check note is open (i.e. not expired or redeemed) if note['status'] != 0: if note['status'] == 1: raise Exception("Note has already been redeemed") if note['status'] == 2: raise Exception("Note has expired") message = note['promise'] # Process thanks self.updateNote(note['id'], 'status', 1) E = Event(note['id'], tweet['tweet_id'], 1, tweet['created'], from_user, to_user) E.save() # Log thanks self.logInfo('[T] @%s thanked @%s for %s' % (to_user, from_user, message)) # Tweet event self.sendTweet( '@%s thanked @%s for %s http://www.punkmoney.org/note/%s' % (from_user, to_user, note['promise'], note['id'])) self.setParsed(tweet['tweet_id']) except Exception, e: self.logWarning("Processing thanks %s failed: %s" % (tweet['tweet_id'], e)) self.setParsed(tweet['tweet_id'], '-')
def parseNeed(self, tweet): try: # Strip out hashtag h = re.search('(.*)(%s|%s)(.*)' % (HASHTAG, ALT_HASHTAG), tweet['content'], re.IGNORECASE) if h: statement = h.group(1) + h.group(3) else: raise Exception("Hashtag not found") # Check expiry (optional) ''' 'Expires in' syntax ''' e = re.search('(.*) Expires in (\d+) (\w+)(.*)', statement, re.IGNORECASE) if e: num = e.group(2) unit = e.group(3) tweet['expiry'] = self.getExpiry(tweet['created'], num, unit) statement = e.group(1) + e.group(4) else: tweet['expiry'] = None # Get thing offered/needed p = re.match('(.*)(need[s]?)(.*)', statement, re.IGNORECASE) if p: if p.group(1).strip().lower() == 'i': item = p.group(3) else: item = p.group(1).strip() + p.group(3) else: raise Exception("Item not found") # Get condition c = re.match('(.*)( if )(.*)', item, re.IGNORECASE) if c: tweet['condition'] = c.group(3) else: tweet['condition'] = None # Clean up promise ''' Remove trailing white space, full stop and word 'you' (if found) ''' item = item.strip() while item[-1] == '.': item = item[:-1] tweet['item'] = item self.createOffer(5, tweet) # Create event E = Event(tweet['tweet_id'], '0', 5, tweet['created'], tweet['author'], '') E.save() # Log event self.logInfo('[N] @%s needs %s.' % (tweet['author'], tweet['tweet_id'])) # Tweet self.sendTweet( '[N] @%s needs %s http://www.punkmoney.org/note/%s' % (tweet['author'], item, tweet['tweet_id'])) self.setParsed(tweet['tweet_id']) except Exception, e: self.logWarning("Processing %s failed: %s" % (tweet['tweet_id'], e)) self.sendTweet( '@%s Sorry, your need [%s] didn\'t parse. Try again: http://www.punkmoney.org/print/' % (tweet['author'], tweet['tweet_id'])) self.setParsed(tweet['tweet_id'], '-')