/usr/share/doc/python-xmpp/examples/commandsbot.py is in python-xmpp 0.4.1-cvs20080505.4.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | #!/usr/bin/python
""" The example of using xmpppy's Ad-Hoc Commands (JEP-0050) implementation.
"""
import xmpp
from xmpp.protocol import *
options = {
'JID': 'circles@example.com',
'Password': '********',
}
class TestCommand(xmpp.commands.Command_Handler_Prototype):
""" Example class. You should read source if you wish to understate how it works. This one
actually does some calculations."""
name = 'testcommand'
description = 'Circle calculations'
def __init__(self, jid=''):
""" Initialize some internals. Set the first request handler to self.calcTypeForm.
"""
xmpp.commands.Command_Handler_Prototype.__init__(self,jid)
self.initial = {
'execute': self.initialForm
}
def initialForm(self, conn, request):
""" Assign a session id and send the first form. """
sessionid = self.getSessionID()
self.sessions[sessionid] = {
'jid':request.getFrom(),
'data':{'type':None}
}
# simulate that the client sent sessionid, so calcTypeForm will be able
# to continue
request.getTag(name="command").setAttr('sessionid', sessionid)
return self.calcTypeForm(conn, request)
def calcTypeForm(self, conn, request):
""" Send first form to the requesting user. """
# get the session data
sessionid = request.getTagAttr('command','sessionid')
session = self.sessions[sessionid]
# What to do when a user sends us a response? Note, that we should always
# include 'execute', as it is a default action when requester does not send
# exact action to do (should be set to the same as 'next' or 'complete' fields)
session['actions'] = {
'cancel': self.cancel,
'next': self.calcTypeFormAccept,
'execute': self.calcTypeFormAccept,
}
# The form to send
calctypefield = xmpp.DataField(
name='calctype',
desc='Calculation Type',
value=session['data']['type'],
options=[
['Calculate the diameter of a circle','circlediameter'],
['Calculate the area of a circle','circlearea']
],
typ='list-single',
required=1)
# We set label attribute... seems that the xmpppy.DataField cannot do that
calctypefield.setAttr('label', 'Calculation Type')
form = xmpp.DataForm(
title='Select type of operation',
data=[
'Use the combobox to select the type of calculation you would like'\
'to do, then click Next.',
calctypefield])
# Build a reply with the form
reply = request.buildReply('result')
replypayload = [
xmpp.Node('actions',
attrs={'execute':'next'},
payload=[xmpp.Node('next')]),
form]
reply.addChild(
name='command',
namespace=NS_COMMANDS,
attrs={
'node':request.getTagAttr('command','node'),
'sessionid':sessionid,
'status':'executing'},
payload=replypayload)
self._owner.send(reply) # Question: self._owner or conn?
raise xmpp.NodeProcessed
def calcTypeFormAccept(self, conn, request):
""" Load the calcType form filled in by requester, then reply with
the second form. """
# get the session data
sessionid = request.getTagAttr('command','sessionid')
session = self.sessions[sessionid]
# load the form
node = request.getTag(name='command').getTag(name='x',namespace=NS_DATA)
form = xmpp.DataForm(node=node)
# retrieve the data
session['data']['type'] = form.getField('calctype').getValue()
# send second form
return self.calcDataForm(conn, request)
def calcDataForm(self, conn, request, notavalue=None):
""" Send a form asking for diameter. """
# get the session data
sessionid = request.getTagAttr('command','sessionid')
session = self.sessions[sessionid]
# set the actions taken on requester's response
session['actions'] = {
'cancel': self.cancel,
'prev': self.calcTypeForm,
'next': self.calcDataFormAccept,
'execute': self.calcDataFormAccept
}
# create a form
radiusfield = xmpp.DataField(desc='Radius',name='radius',typ='text-single')
radiusfield.setAttr('label', 'Radius')
form = xmpp.DataForm(
title = 'Enter the radius',
data=[
'Enter the radius of the circle (numbers only)',
radiusfield])
# build a reply stanza
reply = request.buildReply('result')
replypayload = [
xmpp.Node('actions',
attrs={'execute':'complete'},
payload=[xmpp.Node('complete'),xmpp.Node('prev')]),
form]
if notavalue:
replypayload.append(xmpp.Node('note',
attrs={'type': 'warn'},
payload=['You have to enter valid number.']))
reply.addChild(
name='command',
namespace=NS_COMMANDS,
attrs={
'node':request.getTagAttr('command','node'),
'sessionid':request.getTagAttr('command','sessionid'),
'status':'executing'},
payload=replypayload)
self._owner.send(reply)
raise xmpp.NodeProcessed
def calcDataFormAccept(self, conn, request):
""" Load the calcType form filled in by requester, then reply with the result. """
# get the session data
sessionid = request.getTagAttr('command','sessionid')
session = self.sessions[sessionid]
# load the form
node = request.getTag(name='command').getTag(name='x',namespace=NS_DATA)
form = xmpp.DataForm(node=node)
# retrieve the data; if the entered value is not a number, return to second stage
try:
value = float(form.getField('radius').getValue())
except:
self.calcDataForm(conn, request, notavalue=True)
# calculate the answer
from math import pi
if session['data']['type'] == 'circlearea':
result = (value**2) * pi
else:
result = 2 * value * pi
# build the result form
form = xmpp.DataForm(
typ='result',
data=[xmpp.DataField(desc='result', name='result', value=result)])
# build the reply stanza
reply = request.buildReply('result')
reply.addChild(
name='command',
namespace=NS_COMMANDS,
attrs={
'node':request.getTagAttr('command','node'),
'sessionid':sessionid,
'status':'completed'},
payload=[form])
self._owner.send(reply)
# erase the data about session
del self.sessions[sessionid]
raise xmpp.NodeProcessed
def cancel(self, conn, request):
""" Requester canceled the session, send a short reply. """
# get the session id
sessionid = request.getTagAttr('command','sessionid')
# send the reply
reply = request.buildReply('result')
reply.addChild(
name='command',
namespace=NS_COMMANDS,
attrs={
'node':request.getTagAttr('command','node'),
'sessionid':sessionid,
'status':'cancelled'})
self._owner.send(reply)
# erase the data about session
del self.sessions[sessionid]
raise xmpp.NodeProcessed
class ConnectionError: pass
class AuthorizationError: pass
class NotImplemented: pass
class Bot:
""" The main bot class. """
def __init__(self, JID, Password):
""" Create a new bot. Connect to the server and log in. """
# connect...
jid = xmpp.JID(JID)
self.connection = xmpp.Client(jid.getDomain(), debug=['always', 'browser', 'testcommand'])
result = self.connection.connect()
if result is None:
raise ConnectionError
# authorize
result = self.connection.auth(jid.getNode(), Password)
if result is None:
raise AuthorizationError
# plugins
# disco - needed by commands
# warning: case of "plugin" method names are important!
# to attach a command to Commands class, use .plugin()
# to attach anything to Client class, use .PlugIn()
self.disco = xmpp.browser.Browser()
self.disco.PlugIn(self.connection)
self.disco.setDiscoHandler({
'info': {
'ids': [{
'category': 'client',
'type': 'pc',
'name': 'Bot'
}],
'features': [NS_DISCO_INFO],
}
})
self.commands = xmpp.commands.Commands(self.disco)
self.commands.PlugIn(self.connection)
self.command_test = TestCommand()
self.command_test.plugin(self.commands)
# presence
self.connection.sendInitPresence(requestRoster=0)
def loop(self):
""" Do nothing except handling new xmpp stanzas. """
try:
while self.connection.Process(1):
pass
except KeyboardInterrupt:
pass
bot = Bot(**options)
bot.loop()
|