usr bin python sucked from http twistedmatrix com pipermail twisted-py

  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
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
#!/usr/bin/python
# sucked from:
# * http://twistedmatrix.com/pipermail/twisted-python/2004-May/007903.html
# * http://redfoot.net/hypercode/modules/xmpp/client
# Twisted Imports
from twisted.words.protocols.jabber import client, jid
from twisted.words.xish import domish
from twisted.internet import reactor
# System Imports
#import sys
name = None
server = None
resource = None
password = None
me = None
thexmlstream = None
tryandregister = 1
def initOnline(xmlstream):
global factory
print 'Initializing...'
xmlstream.addObserver('/message', gotMessage)
xmlstream.addObserver('/presence', gotPresence)
xmlstream.addObserver('/*', gotSomething)
def authd(xmlstream):
global thexmlstream
thexmlstream = xmlstream
print "we've authd!"
print repr(xmlstream)
#need to send presence so clients know we're
#actually online
presence = domish.Element(('jabber:client', 'presence'))
presence.addElement('status').addContent('Online')
xmlstream.send(presence)
initOnline(xmlstream)
def send(author, to, msg):
global thexmlstream
message = domish.Element(('jabber:client','message'))
message["to"] = jid.JID(to).full()
message["from"] = jid.JID(author).full()
message["type"] = "chat"
message.addElement("body", "jabber:client", msg)
thexmlstream.send(message)
def gotMessage(el):
global me
#print 'Got message: %s' % str(el.attributes)
from_id = el["from"]
body = "empty"
for e in el.elements():
if e.name == "body":
body = unicode(e.__str__())
break
body = body.split(" ")
body.reverse()
body = " ".join(body)
send(me, from_id, body)
def gotSomething(el):
print 'Got something: %s -> %s' % (el.name, str(el.attributes))
def gotPresence(el):
global thexmlstream
friendJid = el["from"]
if "type" in str(el.attributes):
presence = el.attributes["type"]
if presence == "subscribe":
thexmlstream.send(domish.Element(('jabber:client', 'presence'), attribs={'from': me, 'to': el["from"], 'type': 'subscribed'}))
print presence
def authfailedEvent(xmlstream):
global reactor
print 'Auth failed!'
reactor.stop()
if __name__ == '__main__':
USER_HANDLE = 'robco@jabber.ru'
PASSWORD = 'djbntkmgthdsqbot'
me = USER_HANDLE + "/bot"
myJid = jid.JID(me)
server = 'jabber.ru'
factory = client.basicClientFactory(myJid, PASSWORD)
# Register authentication callbacks
factory.addBootstrap('//event/stream/authd', authd)
# Go!
reactor.connectTCP(server, 5222, factory)
reactor.run()