Commits

Gregory Petukhov committed 609f8cf

initial commit

  • Participants

Comments (0)

Files changed (2)

+^settings\.py$
+\.swp$
+\.pyc$
+^gids\.txt$
+from datetime import datetime
+import feedparser
+import xmpp
+import time
+import logging
+
+import settings
+
+def fetch_feed():
+    """
+    Fetch and parse feed from habrahabr.ru. Return parsed publications.
+    """
+
+    feed = feedparser.parse('http://habrahabr.ru/rss/e7d875f8829bc7f3aac7125b1281ad2b/')
+    entries = feed.entries
+    for entry in entries:
+        entry['date'] = datetime(*entry['updated_parsed'][:-2])
+    return entries
+
+
+def main():
+    entries = fetch_feed()
+    new_items = []
+
+    try:
+        gids = [x.strip() for x in file('gids.txt')]
+    except IOError:
+        gids = []
+
+    for entry in entries:
+        if not entry['id'] in gids:
+            new_items.append(entry)
+            gids.append(entry['id'])
+
+    if new_items:
+        logging.debug('Found %d new publications' % (len(new_items)))
+        file('gids.txt', 'w').write('\n'.join(gids))
+        send_message(new_items)
+
+    logging.debug('Done')
+
+
+def send_message(items):
+    """
+    Compose and send message to XMPP conference.
+    """
+
+    client = setup_xmpp_client()
+    client.send(xmpp.Presence(to='%s/%s' % (settings.NOTIFY_ROOM, settings.XMPP_NICK)))
+
+    step = 3
+    for start in xrange(0, len(items), step):
+        message = []
+        for item in items[start:start + step]:
+            message.append(u'%s (%s)' % (item['title'], item['link']))
+        message = '\n'.join(message)
+        client.send(xmpp.Message(to=settings.NOTIFY_ROOM, typ='groupchat', body=message))
+        time.sleep(settings.MESSAGE_DELAY)
+
+
+def setup_xmpp_client():
+    """
+    Connect to xmpp server and authenticate.
+    """
+
+    jid = xmpp.protocol.JID(settings.XMPP_USER)
+    client = xmpp.Client(jid.getDomain(), debug=[])
+    if client.connect():
+        if client.auth(jid.getNode(), settings.XMPP_PASSWORD):
+            return client
+        else:
+            raise Exception('Could not authorize.')
+    else:
+        raise Exception('Could not connect.')
+
+
+if __name__ == "__main__":
+    logging.basicConfig(level=logging.DEBUG)
+    main()