Responding Intelligently
At this point, we’re receiving messages and sending back simple output. Let’s take some time to examine the data as it comes in and respond to it. We’ll allow the user to enter simple commands to our application and respond appropriately to the request.
The Basic Commands
We’re going to expand this application to accept basic commands and respond with the appropriate response. To do this, we must first understand the command format. To keep it simple, we’ll assume that any instant message that we receive is a command. The first word of that message is the command itself, and the rest of string represents any additional parameters for the command.
Let’s start by parsing out the command itself from the rest of the
message. Add the following code to your XMPPHandler
class:
class XMPPHandler(BaseHandler):
def post(self):
message = xmpp.Message(self.request.POST)
logging.info("XMPP sender: %s - body: %s" % (message.sender, message.body))
# The command from the user
cmd = message.body.split(' ')[0].lower()
# the rest of the message
body = message.body[len(cmd) + 1:]Because the format is , to parse out the command, we simply
need to grab anything before the first space character. We then convert
it to lowercase to make it easier to match in the next step, which
determines what we do with each command. Keep adding to that
method:command and
the rest of the string
# echo the data back to the client if cmd == 'echo': message.reply(body) # convert string to rot13 and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access