from datetime import datetime import feedparser import xmpp import tim

 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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()