Skip to content

Instantly share code, notes, and snippets.

@rhcarvalho
Created March 12, 2012 00:44
Show Gist options
  • Select an option

  • Save rhcarvalho/2018916 to your computer and use it in GitHub Desktop.

Select an option

Save rhcarvalho/2018916 to your computer and use it in GitHub Desktop.
XMPP Bots with xmpppy
# 2012/03/11 Rodolfo Carvalho
# Small demo showing how two bots connected with the same JID
# (and different resources) can communicate using xmpppy
import xmpp
import random
from getpass import getpass
from time import sleep
from threading import Thread, Event
# generate different resource names every time the script is run
_salt = random.randint(1000, 9999)
# flag to tell all threads to stop
_stop = Event()
def get_bot_online(jid, passwd, resource):
bot = xmpp.Client(jid.getDomain(), debug=[])
resource = '%s-%d' % (resource, _salt)
# It seems that we need to help xmpppy in case we're on Gtalk...
if jid.getDomain() == 'gmail.com':
server = ('talk.google.com', 5222)
else:
server = None
print 'Bot:', resource
print ' connected using:', bot.connect(server)
print ' authenticated using:', bot.auth(jid.getNode(), passwd, resource)
bot.sendInitPresence(0)
return bot
def make_echo(reply):
def echo(dispatcher, message):
print '[%s] %s' % (dispatcher._owner.Resource, message)
# send reply after some time
sleep(random.uniform(1, 5))
dispatcher.send(xmpp.protocol.Message(message.getFrom(), reply))
return echo
def process_until_disconnect(bot):
ret = -1
while ret != 0 and not _stop.is_set():
ret = bot.Process()
def run_inter_bot_communication(jid, passwd):
"""Connect two bots to the network and start a ping-pong communication."""
_stop.clear()
try:
jid = xmpp.protocol.JID(jid)
print ' Connecting to XMPP network '.center(78, '=')
bot1 = get_bot_online(jid, passwd, 'bot1')
bot2 = get_bot_online(jid, passwd, 'bot2')
bot1.RegisterHandler('message', make_echo('pong'))
bot2.RegisterHandler('message', make_echo('ping'))
print ' Processing XMPP events '.center(78, '=')
print 'Ctrl-C to stop and exit'
print
Thread(target=process_until_disconnect, args=(bot1,)).start()
Thread(target=process_until_disconnect, args=(bot2,)).start()
# Initial message to bot1
bot2.send(xmpp.protocol.Message('%s@%s/%s' % (jid.getNode(),
jid.getDomain(),
bot1.Resource),
'ping'))
# Block main thread waiting for KeyboardInterrupt
while True:
pass
except KeyboardInterrupt:
_stop.set()
print
print "Bye!"
if __name__ == '__main__':
import sys
argv = sys.argv
try:
jid = argv[1:] and argv[1] or raw_input('JID: ')
passwd = argv[2:] and argv[2] or getpass()
except KeyboardInterrupt:
pass
else:
run_inter_bot_communication(jid, passwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment