Saturday, September 24, 2016

create a xmpp bot

to setup xmpp server you can follow the following line

1- install sleekxmpp library
$ sudo pip install sleekxmpp

2- save the following as
import logging

from sleekxmpp import ClientXMPP
from sleekxmpp.exceptions import IqError, IqTimeout
from math import *
import os
import re
import sys
import subprocess

class EchoBot(ClientXMPP):

    def __init__(self, jid, password):
        ClientXMPP.__init__(self, jid, password)

        self.add_event_handler("session_start", self.session_start)
        self.add_event_handler("message", self.message)

    def session_start(self, event):

    def message(self, msg):
        #if msg['type'] in ('chat', 'normal'):
        #    msg.reply("Thanks for sending\n%(body)s" % msg).send()
    #print >>sys.stderr, str(dir(msg))
    #print >>sys.stderr, msg.values
    tocheck = msg['body']
    print >>sys.stderr, tocheck
    print >>sys.stderr, "***************"
    if"^exec\s+.*", tocheck):
            command = re.sub(r"^exec\s", "", tocheck)
            command1 = command.split()
            output = subprocess.Popen(command1 ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    elif"^math\s+.*", tocheck):
            result = ""
            command = re.sub(r"^math\s", "", tocheck)
            toexec = "result = " + command

if __name__ == '__main__':

                        format='%(levelname)-8s %(message)s')

    xmpp = EchoBot('bot@test.qq', 'botpassword')

3- the options available of the bot are
- exec to execute command on server
- math to do basic math

4- before the bot are operational we have
  - create bot account on xmpp server with username: bot@test.qq and password: botpassword
  - the user that wish to interact with the bot, have to add bot as friend and chat to run the option

5- run the bot with the following command
$ python

5- example of usage
- read passwd on  bot host
exec cat /etc/passwd

- math usage
math cos(pi)
math sin(pi/4)
math 3 ** 4

- snapshot of the interaction with the bot

No comments:

Post a Comment