Advertising
- Gnip-Twitter
- Sunday, October 26th, 2008 at 9:42:53pm UTC
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- # Gnip-Twitter - An XMPP bot for Gnip Twitter stream
- # Author: [email protected]
- # Requires Python xmpppy library (apt:python-xmpp)
- # Usage :
- #
- # 1. Get a Gnip account @ http://www.gnipcentral.com/ ;
- # 2. Create a new Twitter filter @ https://s.gnipcentral.com/publishers/twitter/filters/new ;
- # 3. And add your JID and a comma-separated list of users (in the "Actor" form) ;
- # 4. Make the bot subscribe to xmpp:[email protected] ;
- # 5. Launch the bot.
- from sys import exit
- from xmpp import JID, Client, Iq, Presence, NS_VERSION, NS_VCARD
- from StringIO import StringIO
- from xml.dom.minidom import parse, parseString
- from urllib import urlencode
- from urllib2 import Request, urlopen
- from base64 import encode, decode
- from hashlib import sha1
- from gzip import GzipFile
- Jid = ''
- Password = ''
- Resource = 'twitter'
- 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'}
- NS_VCARD_UPDATE = 'vcard-temp:x:update'
- NS_NICK = 'http://jabber.org/protocol/nick'
- def hash_img(img):
- return sha1(img).hexdigest()
- def get_img(data):
- try:
- icon_url = data.getElementsByTagName('icon')[0].firstChild.data
- req = Request(icon_url.replace('_normal','_bigger'))
- response = urlopen(req)
- img = response.read()
- return {'base64_img': img.encode('base64'),
- 'content-type': response.info()['Content-Type'],
- 'hash': hash_img(img)}
- except:
- return TWITTER_IMG
- def send_vcard(conn, base64_img, mime_type, nick):
- iq_vcard = Iq(typ='set')
- vcard = iq_vcard.addChild(name='vCard', namespace=NS_VCARD)
- vcard.addChild(name='NICKNAME', payload=[nick])
- photo = vcard.addChild(name='PHOTO')
- photo.setTagData(tag='TYPE', val=mime_type)
- photo.setTagData(tag='BINVAL', val=base64_img)
- conn.send(iq_vcard)
- def send_presence(conn, status, hash1, nick):
- presence = Presence(status = status, show = 'xa', priority = '-1')
- presence.setTag(name='x',namespace=NS_VCARD_UPDATE).setTag(name='photo',namespace=NS_VCARD_UPDATE).setData(hash1)
- presence.setTag(name='nick',namespace=NS_NICK).setData(nick)
- conn.send(presence)
- def version_handler(conn, iq):
- reply = iq.buildReply('result')
- q = reply.getTag('query')
- q.addChild(name='name', payload=['Jabber-Gnip'])
- q.addChild(name='version', payload=['1.0'])
- conn.send(reply)
- def presenceCB(conn,msg):
- prs_type=msg.getType()
- who=msg.getFrom()
- if prs_type == "subscribe":
- conn.send(xmpp.Presence(to=who, typ = 'subscribed'))
- conn.send(xmpp.Presence(to=who, typ = 'subscribe'))
- def messageCB(conn,msg):
- jid = msg.getFrom()
- body = msg.getBody()
- return str_to_xml(conn, body)
- def str_to_xml(conn, data):
- data_xml = parseString(data.encode("utf-8"))
- activity = data_xml.getElementsByTagName('activity')[0]
- body = data_xml.getElementsByTagName('body')[0]
- if data_xml.getElementsByTagName('activities')[0].attributes["publisher"].value == 'twitter':
- try:
- raw = data_xml.getElementsByTagName('raw')[0].firstChild.data
- return twitter_data(conn, activity, body, raw)
- except:
- pass
- def twitter_data(conn, activity, body, raw):
- author = activity.attributes["actor"].value
- date = activity.attributes["at"].value
- title = body.firstChild.data
- title.encode("utf-8")
- source = activity.attributes['source'].value
- status = '_' + author + '@twitter/' + source + '_ - ' + date + '\n' + title
- data = b64decode(raw)
- data = unzip(data)
- xml=parseString(data)
- img = get_img(xml)
- nick = author + '@twitter/' + source
- send_vcard(conn, img['base64_img'], img['content-type'], nick)
- send_presence(conn, status, img['hash'], nick)
- def StepOn(conn):
- try:
- conn.Process(1)
- except KeyboardInterrupt:
- return 0
- return 1
- def GoOn(conn):
- while StepOn(conn):
- pass
- def b64decode(data):
- return data.decode('base64')
- def unzip(data):
- compressedstream = StringIO(data)
- return GzipFile(fileobj=compressedstream).read()
- def main():
- jid=JID(Jid)
- cl = Client(jid.getDomain(), debug=[])
- if cl.connect() == "":
- #print "not connected"
- sys.exit(0)
- if cl.auth(jid.getNode(),Password, Resource) == None:
- #print "authentication failed"
- sys.exit(0)
- #cl.RegisterHandler('presence', presenceCB)
- cl.RegisterHandler('message', messageCB)
- cl.RegisterHandler('iq', version_handler, typ='get', ns=NS_VERSION)
- cl.sendInitPresence()
- cl.send(Presence(show='xa', priority=-1))
- GoOn(cl)
- main()
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.
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.