Saturday, September 24, 2016

create a xmpp bot

to setup xmpp server you can follow the following line
http://www.atechnote.com/2016/09/configure-jabberxmpp-server-ejabberd.html

1- install sleekxmpp library
$ sudo pip install sleekxmpp

2- save the following as xmpp-bot.py
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):
        self.send_presence()
        self.get_roster()


    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 re.search(r"^exec\s+.*", tocheck):
            command = re.sub(r"^exec\s", "", tocheck)
            command1 = command.split()
            output = subprocess.Popen(command1 ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        msg.reply(output.stdout.read()).send()
        msg.reply(output.stderr.read()).send()
    elif re.search(r"^math\s+.*", tocheck):
            result = ""
            command = re.sub(r"^math\s", "", tocheck)
            toexec = "result = " + command
            exec(toexec)
        msg.reply(str(result)).send()


if __name__ == '__main__':

    logging.basicConfig(level=logging.DEBUG,
                        format='%(levelname)-8s %(message)s')

    xmpp = EchoBot('bot@test.qq', 'botpassword')
    xmpp.connect()
    xmpp.process(block=True)



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 xmpp-bot.py

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