import twitter
import re
import os

TWITTER_PERMALINK_RE = re.compile("https?://(?:www.)?twitter.com/(\w+)/status/(\w+)")

_api = None
def get_api():
    if not get_api.cached: 
        CONSUMER_KEY = "Cm9wmVhNTgES6xm2mUwRtg"
        CONSUMER_SECRET = "CvtRQR9LzP2QF0JhNGmb9ZHKi6PwQrf2uz7ghbplCFo"
        MY_TWITTER_CREDS = os.path.expanduser('~/.groomsman/twitter_credentials')
        if not os.path.exists(MY_TWITTER_CREDS):
            twitter.oauth_dance("groomsman-kylewm.com", CONSUMER_KEY, CONSUMER_SECRET,
                                MY_TWITTER_CREDS)
        oauth_token, oauth_secret = twitter.read_token_file(MY_TWITTER_CREDS)
        get_api.cached = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret,
                                                  CONSUMER_KEY, CONSUMER_SECRET))
    return get_api.cached

get_api.cached = None

def handle_new_or_edit(post):
    api = get_api()
    args = {
        'status' : create_status(post),
        'trim_user' : True
    }
    
    match = TWITTER_PERMALINK_RE.match(post.in_reply_to)
    if match:
        args['in_reply_to_status_id'] = match.group(2)

    result = api.statuses.update(**args)
    if result:
        status_id = result.get('id_str')
        post.twitter_status_id = status_id
        
def create_status(post):
    permalink = post.permalink_short_url

    if post.title:
        text = post.title
    else:
        text = post.content

    allowed_chars = 140 - 1 - len(permalink)
    text = text[:allowed_chars] + " " + permalink
    return text

@@ -120,20 +120,8 @@
 %22)%0A%0A
-_api = None%0A
 def 
@@ -902,66 +902,146 @@
     
-args = %7B%0A        'status' : create_status(post),%0A        '
+# check for RT's%0A    match = TWITTER_PERMALINK_RE.match(post.repost_source)%0A    if match:%0A        api.statuses.retweet(id=match.group(2), 
 trim
@@ -1049,28 +1049,29 @@
 user
-' : 
+=
 True
+)
 %0A    
-%7D
+else:
 %0A    
-%0A
     
@@ -1131,171 +1131,273 @@
     
-if match:%0A        args%5B'in_reply_to_status_id'%5D = match.group(2)%0A%0A    result = api.statuses.update(**args)%0A    if result:%0A        status_id = result.get('id_str')%0A
+    in_reply_to = match.group(2) if match else None%0A        result = api.statuses.update(status=create_status(post),%0A                                     in_reply_to_status_id=in_reply_to,%0A                                     trim_user=True)%0A        if result:%0A    
     
@@ -1425,25 +1425,36 @@
 us_id = 
-status_id
+result.get('id_str')
 %0A       

Perform "native" retweets when repost source is a twitter URL