Part of Slepp's ProjectsPastebinTURLImagebinFilebin
Feedback -- English French German Japanese
Create Upload Newest Tools Donate

Advertising

Gnip-Twitter
Sunday, October 26th, 2008 at 9:42:53pm UTC 

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # Gnip-Twitter - An XMPP bot for Gnip Twitter stream
  5.  
  6. # Author: [email protected]
  7.  
  8. # Requires Python xmpppy library (apt:python-xmpp)
  9.  
  10. # Usage :
  11. #
  12. # 1. Get a Gnip account @ http://www.gnipcentral.com/ ;
  13. # 2. Create a new Twitter filter @ https://s.gnipcentral.com/publishers/twitter/filters/new ;
  14. # 3. And add your JID and a comma-separated list of users (in the "Actor" form) ;
  15. # 4. Make the bot subscribe to xmpp:[email protected] ;
  16. # 5. Launch the bot.
  17.  
  18. from sys import exit
  19. from xmpp import JID, Client, Iq, Presence, NS_VERSION, NS_VCARD
  20. from StringIO import StringIO
  21. from xml.dom.minidom import parse, parseString
  22. from urllib import urlencode
  23. from urllib2 import Request, urlopen
  24. from base64 import encode, decode
  25. from hashlib import sha1
  26. from gzip import GzipFile
  27.  
  28. Jid = ''
  29. Password = ''
  30. Resource = 'twitter'
  31.  
  32. TWITTER_IMG = {'hash': 'ab0733c8d6a8adc0f26f64794e21d096b393b8b8', 'content-type': 'image/png', 'base64_img': 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAb5JREFU\nOI2Nk71OVUEUhb81c849J0BEDTGoWKCND0BhfBjfQBsTC1/AF7D3fSzsFDoKCwNBIPhD7mVmL4tz\nLlyuRt3JdDNrr2/t2bJtgBLBrAaWSJgk0eXMv6oBMFBs9kMcF7OaxeMWwoPQ3yoBYHMW8HFaOKmV\nvWnhqA6u/ssBwMzmazUNMAUqIAfT4uGCQRI5iZzS7wIB/AjTCorh06xylBMxIgIIc6+BTQdtTlcC\nkgjD9zCthDDvzwtXALqUaYDnt3puLzuowJlhghkHMzyRkA0YSRzW4DB8XcA2xXASQb/Q0KPtOUKx\neThJbLdLGQiomNMIeomf1by42bPTNUztS4CK2ciZdmG0zRxxZjgMsyb4FmYliVWZG02GESmAvPQv\n0oAALXAQ5nOY/TB7F0EjcMRwwYaIBaClEB+0YiKxWw2CVyfnHNWOrZwoY/cGeNo3bE+uvrjmu0BU\n3pzOeH38E8YZE4vdDBZ3s/iwtc7mGORlnKHEy/WOZ2sdlBhSS1o4CbL4UoLdi3o9A4AkkQXv7qzw\ndmOVR43obDqbfjyEedI37HR/Qpg7sanlgnMyB2FiHPMIwf0sJoLJuOq/APFk5YSrRsZcAAAAAElF\nTkSuQmCC\n'}
  33.  
  34. NS_VCARD_UPDATE = 'vcard-temp:x:update'
  35. NS_NICK = 'http://jabber.org/protocol/nick'
  36.  
  37. def hash_img(img):
  38.     return sha1(img).hexdigest()
  39.  
  40. def get_img(data):
  41.     try:
  42.         icon_url = data.getElementsByTagName('icon')[0].firstChild.data
  43.         req = Request(icon_url.replace('_normal','_bigger'))
  44.         response = urlopen(req)
  45.         img = response.read()
  46.         return {'base64_img': img.encode('base64'),
  47.                 'content-type': response.info()['Content-Type'],
  48.                 'hash': hash_img(img)}
  49.     except:
  50.         return TWITTER_IMG
  51.  
  52. def send_vcard(conn, base64_img, mime_type, nick):
  53.     iq_vcard = Iq(typ='set')
  54.     vcard = iq_vcard.addChild(name='vCard', namespace=NS_VCARD)
  55.     vcard.addChild(name='NICKNAME', payload=[nick])
  56.     photo = vcard.addChild(name='PHOTO')
  57.     photo.setTagData(tag='TYPE', val=mime_type)
  58.     photo.setTagData(tag='BINVAL', val=base64_img)
  59.     conn.send(iq_vcard)
  60.  
  61. def send_presence(conn, status, hash1, nick):
  62.     presence = Presence(status = status, show = 'xa', priority = '-1')
  63.     presence.setTag(name='x',namespace=NS_VCARD_UPDATE).setTag(name='photo',namespace=NS_VCARD_UPDATE).setData(hash1)
  64.     presence.setTag(name='nick',namespace=NS_NICK).setData(nick)
  65.     conn.send(presence)
  66.  
  67.  
  68. def version_handler(conn, iq):
  69.     reply = iq.buildReply('result')
  70.     q = reply.getTag('query')
  71.     q.addChild(name='name', payload=['Jabber-Gnip'])
  72.     q.addChild(name='version', payload=['1.0'])
  73.     conn.send(reply)
  74.  
  75. def presenceCB(conn,msg):
  76.     prs_type=msg.getType()
  77.     who=msg.getFrom()
  78.     if prs_type == "subscribe":
  79.         conn.send(xmpp.Presence(to=who, typ = 'subscribed'))
  80.         conn.send(xmpp.Presence(to=who, typ = 'subscribe'))
  81.  
  82. def messageCB(conn,msg):
  83.     jid = msg.getFrom()
  84.     if str(jid).startswith([email protected]'):
  85.         body = msg.getBody()
  86.         return str_to_xml(conn, body)
  87.  
  88. def str_to_xml(conn, data):
  89.     data_xml = parseString(data.encode("utf-8"))
  90.     activity = data_xml.getElementsByTagName('activity')[0]
  91.     body = data_xml.getElementsByTagName('body')[0]
  92.     if data_xml.getElementsByTagName('activities')[0].attributes["publisher"].value == 'twitter':
  93.         try:
  94.             raw = data_xml.getElementsByTagName('raw')[0].firstChild.data
  95.             return twitter_data(conn, activity, body, raw)
  96.         except:
  97.             pass
  98.  
  99. def twitter_data(conn, activity, body, raw):
  100.     author = activity.attributes["actor"].value
  101.     date = activity.attributes["at"].value
  102.     title = body.firstChild.data
  103.     title.encode("utf-8")
  104.     source = activity.attributes['source'].value
  105.     status = '_' + author + [email protected]/' + source + '_ - ' + date + '\n' + title
  106.     data = b64decode(raw)
  107.     data = unzip(data)
  108.     xml=parseString(data)
  109.     img = get_img(xml)
  110.     nick = author + [email protected]/' + source
  111.     send_vcard(conn, img['base64_img'], img['content-type'], nick) 
  112.     send_presence(conn, status, img['hash'], nick)
  113.  
  114. def StepOn(conn):
  115.     try:
  116.        conn.Process(1)
  117.     except KeyboardInterrupt:
  118.             return 0
  119.     return 1
  120.  
  121. def GoOn(conn):
  122.     while StepOn(conn):
  123.             pass
  124.  
  125. def b64decode(data):
  126.     return data.decode('base64')
  127.  
  128. def unzip(data):
  129.     compressedstream = StringIO(data)
  130.     return GzipFile(fileobj=compressedstream).read()
  131.  
  132. def main():
  133.     jid=JID(Jid)
  134.     cl = Client(jid.getDomain(), debug=[])
  135.     if cl.connect() == "":
  136.         #print "not connected"
  137.         sys.exit(0)
  138.        
  139.     if cl.auth(jid.getNode(),Password, Resource) == None:
  140.         #print "authentication failed"
  141.         sys.exit(0)
  142.  
  143.     #cl.RegisterHandler('presence', presenceCB)
  144.     cl.RegisterHandler('message', messageCB)
  145.     cl.RegisterHandler('iq', version_handler, typ='get', ns=NS_VERSION)
  146.     cl.sendInitPresence()
  147.     cl.send(Presence(show='xa', priority=-1))
  148.     GoOn(cl)
  149.  
  150. main()

Paste Details

advertising

Update the Post

Either update this post and resubmit it with changes, or make a new post.

You may also comment on this post.

update paste below
details of the post (optional)

Note: Only the paste content is required, though the following information can be useful to others.

Save name / title?

(space separated, optional)



Please note that information posted here will not expire by default. If you do not want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords. All illegal activities will be reported and any information will be handed over to the authorities, so be good.

comments powered by Disqus
worth-right