My Site
Categories
Posting articles to Twitter via Django

I noticed that every time Clint Savage makes a blog update, he posts the URL to Twitter twice (yeah, that's you herlo :P). The URLs for each Twitter post are different, so I figured it must be some sort of automated Wordpress script with a bug in it.

So, I decided to write something to do the same for my own blog. Clint's passes the URL through tinyurl to get an address that's not too long for Twitter, but in my blog's case, http://vimtips.org/article_id works just fine.

Here's the code I used to do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from vimtips import settings

try:
    import twitter
except ImportError:
    twitter = None

def twitter_post(article_id, title):
    """
        Posts an article update to twitter
    """
    
    if not twitter or not hasattr(settings, 'TWITTER_USER') or \
        not hasattr(settings, 'TWITTER_PASS'):
        return

    try:
        api = twitter.Api(settings.TWITTER_USER, settings.TWITTER_PASS)
        api.PostUpdate(
            "Blog Update: %s (http://vimtips.org/ class="si">%d)" % (title, article_id)
        )
    except Exception, e:
        if settings.DEBUG:
            raise(e)

class Article(models.Model):
    """
        The model representing each news article on the blog
    """
    
    # ... model fields here ...

    def save(self, *args):
        """
            Saves the article.  If this is a new article, it also posts to
            twitter
        """
        post = not self.id

        models.Model.save(self, *args)

        if post:
            twitter_post(self.id, self.title)

This requires that you install the python-twitter module from http://code.google.com/p/python-twitter/.

Filed under: Programming, Python, Django
Comments:

No comments have been added yet

Add a comment:
captcha

Optional, for comment reply notifications
 
Note: If you enter your email address, you will be subscribed to this article and will recieve comment updates via email. This is the only thing your address will be used for. A link will be provided at the end of each email that will allow you to unsubscribe should you need to, or you can go to http://synicworld.com//unsubscribe to unsubscribe from any/all updates.