Better looking tweets
[oweals/karmaworld.git] / karmaworld / apps / notes / tasks.py
1 #!/usr/bin/env python
2 # -*- coding:utf8 -*-
3 # Copyright (C) 2013  FinalsClub Foundation
4
5 from celery import task
6 from karmaworld.apps.notes.models import Note
7 import twitter
8 import logging
9 import gdshortener
10
11 logger = logging.getLogger(__name__)
12
13
14 @task(name="tweet_note")
15 def tweet_note():
16     """Tweet about a new note."""
17
18     try:
19         import karmaworld.secret.twitter as secrets
20     except ImportError:
21         logger.warn("No twitter secrets found, not running tweet_note")
22         return
23
24     api = twitter.Api(consumer_key=secrets.CONSUMER_KEY,
25                       consumer_secret=secrets.CONSUMER_SECRET,
26                       access_token_key=secrets.ACCESS_TOKEN_KEY,
27                       access_token_secret=secrets.ACCESS_TOKEN_SECRET)
28
29     newest_notes = Note.objects.all().order_by('-uploaded_at')[:100]
30     for n in newest_notes:
31         if not n.tweeted:
32             update = tweet_string(n)
33             logger.info("Tweeting: " + update)
34
35             # Mark this tweeted before we actually tweet it
36             # to be extra safe against double tweets
37             n.tweeted = True
38             n.save()
39
40             api.PostUpdate(tweet_string(n))
41
42             break
43
44
45 def tweet_string(note):
46     # This url will use 13 or less characters
47     shortener = gdshortener.ISGDShortener()
48     url = "http://www.karmanotes.org" + \
49         note.get_absolute_url()
50     short_url = shortener.shorten(url)[0]
51
52     # 50 characters
53     short_course = note.course.name[:50]
54
55     # 57 characters
56     short_note = note.name[:57]
57
58     if note.course.school.hashtag:
59         return short_url + " #" + note.course.school.hashtag + " " + \
60         short_course + ": " + \
61         short_note
62     else:
63         return short_url + " " + \
64             short_course + ": " + \
65             short_note