Ejemplo n.º 1
0
    def __init__(self,
                 user=None,
                 to=None,
                 show=None,
                 statuses=None,
                 priority=0):
        UserPresence.__init__(self, user, to, type=None)

        if show in ['away', 'xa', 'chat', 'dnd']:
            self.addElement('show', content=show)

        if statuses is not None:
            for lang, status in statuses.iteritems():
                s = self.addElement('status', content=status)
                if lang:
                    s[(NS_XML, "lang")] = lang

        if priority != 0:
            self.addElement('priority', content=unicode(int(priority)))

        if configuration.getConfig().contactIcon != None:
            x = self.addElement('x', defaultUri=NS_VCARD_UPDATE)
            x.addElement("photo",
                         content=configuration.getConfig().contactIconHash)
            x = self.addElement('x', defaultUri=NS_JABBER_AVATAR)
            x.addElement("hash",
                         content=configuration.getConfig().contactIconHash)
Ejemplo n.º 2
0
def updateHydras():
    config = configuration.getConfig()
    hydras = configuration.getHydras()
    logging.debug("** Updating Hydras **")
    result = []
    for key, hydra in config.items("HYDRAS"):
        result += [hydra]

    for hydra in hydras:
        try:
            get_url = hydra + '/apps/hydra'
            logging.debug("Getting hydras from " + get_url)
            headers = {
                'hydra_access_key': config.get("MAIN", "hydra_access_key")
            }
            request = urllib2.Request(get_url, headers=headers)
            response = urllib2.urlopen(request,
                                       timeout=int(
                                           config.get("MAIN", "timeout")))
            new_hydras = json.loads(response.read())
            if len(new_hydras) > 0:
                # Merge with no duplicates. Always config hydras first
                result = result + list(set(new_hydras) - set(result))
                break
            else:
                logging.error("Empty hydra list received from " + get_url)
        except Exception, e:
            logging.error("Exception updating hydras: " + str(e))
Ejemplo n.º 3
0
    def __init__(self, user=None, to=None, show=None, statuses=None, priority=0):
        UserPresence.__init__(self, user, to, type=None)

        if show in ['away', 'xa', 'chat', 'dnd']:
            self.addElement('show', content=show)

        if statuses is not None:
            for lang, status in statuses.iteritems():
                s = self.addElement('status', content=status)
                if lang:
                    s[(NS_XML, "lang")] = lang

        if priority != 0:
            self.addElement('priority', content=unicode(int(priority)))
        
        if configuration.getConfig().contactIcon != None:
            x = self.addElement('x', defaultUri=NS_VCARD_UPDATE)
            x.addElement("photo", content=configuration.getConfig().contactIconHash)
	    x = self.addElement('x', defaultUri=NS_JABBER_AVATAR)
            x.addElement("hash", content=configuration.getConfig().contactIconHash)
Ejemplo n.º 4
0
 def _onGetVCard(self, iq):
     tojid = jid.internJID(iq["to"])
     reply = domish.Element((NS_VCARD, "vCard"))
     
     if tojid.user == None:
         reply.addElement("FN", content=configuration.getConfig().serverName)
     else:
         reply.addElement("FN", content=getUser(tojid))
         reply.addElement("NICKNAME", content=getUser(tojid))
         reply.addElement("TEL").addElement("NUMBER", content=getUser(tojid))
         
         contactIcon = configuration.getConfig().contactIcon
         
         if contactIcon != None:
             photo = reply.addElement("PHOTO")
             photo.addElement("TYPE", content="image/png")
             
             photo_data = binascii.b2a_base64(contactIcon)
             photo.addElement("BINVAL", content=photo_data)
     
     return reply
Ejemplo n.º 5
0
    def _onGetVCard(self, iq):
        tojid = jid.internJID(iq["to"])
        reply = domish.Element((NS_VCARD, "vCard"))

        if tojid.user == None:
            reply.addElement("FN",
                             content=configuration.getConfig().serverName)
        else:
            reply.addElement("FN", content=getUser(tojid))
            reply.addElement("NICKNAME", content=getUser(tojid))
            reply.addElement("TEL").addElement("NUMBER",
                                               content=getUser(tojid))

            contactIcon = configuration.getConfig().contactIcon

            if contactIcon != None:
                photo = reply.addElement("PHOTO")
                photo.addElement("TYPE", content="image/png")

                photo_data = binascii.b2a_base64(contactIcon)
                photo.addElement("BINVAL", content=photo_data)

        return reply
Ejemplo n.º 6
0
def getNagios():
    config = configuration.getConfig()
    result = {}
    try:
        if config.has_section("NAGIOS"):
            nagios = parseStatusDat.parseFile(
                config.get("NAGIOS", "nagios_dat_file"))
            for key, path in config.items("NAGIOS")[1:]:
                splitted = path.split(":")
                value = nagios
                for i in range(len(splitted)):
                    value = value[splitted[i]]
                result[key] = value
    except Exception, e:
        logging.error("Exception in getNagios: " + str(e))
Ejemplo n.º 7
0
    def processReport(self, jid, args):
        # get configuration
        conf = configuration.getConfig()

        # catch missing or empty msg_id string
        try:
            if len(args["msg_id"][0]) <= 0: return "MSGID MISSING"
            msgdata = database.getMessage(JID(jid), args["msg_id"][0])
        except exceptions.KeyError:
            return "MSGID MISSING"

        # create a new message
        status = domish.Element((None, "message"))
        status["to"] = jid

        if msgdata != None:
            status["from"] = msgdata["rcpt"] + "@" + conf.jabberComponentName

        # add subject
        status.addElement("subject", content=u"Statusbericht")

        try:
            # update message state in the database
            database.updateMessageState(JID(jid), args["msg_id"][0],
                                        args["status"][0])

            # create a message for notify the user
            msg = u"Der Status ihrer SMS hat sich geändert: " + unicode(
                args["status"][0])
            if msgdata != None:
                msg += u"\n\n-- Nachrichtentext --\n"
                msg += msgdata["content"]

            # add the message to the body
            status.addElement("body", content=msg)
        except exceptions.KeyError:
            status.addElement("body")

        if database.isReportRequested(JID(jid)):
            # send the message
            self.xmpp.send(status)

        # update the balance in the status
        self.xmpp.updateBalance(jid)

        return "OK"
Ejemplo n.º 8
0
def checkProcessAndPortAndGetSystemInfo():
    config = configuration.getConfig()
    hydras = configuration.getHydras()
    data = {"state": stateEnum.NOT_RUNNING, "uri": config.get("MAIN", "uri")}
    try:
        # Check process
        f = open(config.get("MAIN", "pid_file"), 'r+')
        PID = f.read()
        f.close()
        logging.debug("Checking PID " + PID.strip())

        # ORIGINAL
        #connections = len(psutil.Process(int(PID)).get_connections(kind='inet'))

        # ALTERNATIVE 1 (add)
        connections = len(
            psutil.Process(int(PID)).get_connections(kind='inet')) - 1

        # ALTERNATIVE 2 (replace)
        #connections = 0
        #for connection in psutil.Process(int(PID)).get_connections(kind='inet'):
        #    # WARINING!!!!!!!!! Changed in 1.0.0: 'status' field is no longer a string but a constant object (psutil.CONN_*).
        #    if connection.status == 'ESTABLISHED':
        #        connections = connections + 1

        data["connections"] = connections

        # Check CPU and Memory
        logging.debug("Checking CPU and Memory")
        data["cpuLoad"] = psutil.cpu_percent(interval=0.5, percpu=False)
        #data["memLoad"] = psutil.virtual_memory().percent
        data["memLoad"] = psutil.phymem_usage().percent

        # Check port open (if option exists)
        if config.get("MAIN", "check_enabled") == "true" and config.has_option(
                "MAIN", "check_host") and config.has_option(
                    "MAIN", "check_port"):
            logging.debug("Checking Host and Port")
            data["state"] = isPortOpen(config.get("MAIN", "check_host"),
                                       int(config.get("MAIN", "check_port")))
        else:
            data["state"] = stateEnum.READY

    except Exception, e:
        logging.debug(str(e))
        data["state"] = stateEnum.NOT_RUNNING
Ejemplo n.º 9
0
    def processReport(self, jid, args):
        # get configuration
        conf = configuration.getConfig()

        # catch missing or empty msg_id string
        try:
            if len(args["msg_id"][0]) <= 0: return "MSGID MISSING"
            msgdata = database.getMessage(JID(jid), args["msg_id"][0])
        except exceptions.KeyError:
            return "MSGID MISSING"

        # create a new message
        status = domish.Element((None, "message"))
        status["to"] = jid
        
        if msgdata != None:
            status["from"] = msgdata["rcpt"] + "@" + conf.jabberComponentName
        
        # add subject
        status.addElement("subject", content=u"Statusbericht")

        try:
            # update message state in the database
            database.updateMessageState(JID(jid), args["msg_id"][0], args["status"][0])

            # create a message for notify the user
            msg = u"Der Status ihrer SMS hat sich geändert: " + unicode(args["status"][0])
	    if msgdata != None:
	        msg += u"\n\n-- Nachrichtentext --\n"
		msg += msgdata["content"]
            
            # add the message to the body
            status.addElement("body", content=msg)
        except exceptions.KeyError:
            status.addElement("body")
        
        if database.isReportRequested(JID(jid)):
            # send the message
            self.xmpp.send(status)
        
        # update the balance in the status
        self.xmpp.updateBalance(jid)

        return "OK"
Ejemplo n.º 10
0
def getContacts(jid):
    try:
        cursor = db.getCursor()
        cursor.execute("SELECT contact FROM contacts WHERE jid = %s", (jid.userhost(),) )
        
        ret = []
        row = cursor.fetchone()
        
        while (row != None):
            if row[0] != "":
                ret.append(JID(row[0] + "@" + configuration.getConfig().jabberComponentName))
                
            row = cursor.fetchone()
            
        cursor.close()
        
        return ret
    except (AttributeError, MySQLdb.OperationalError):
        db.reconnect()
        return getContacts(jid)
Ejemplo n.º 11
0
def demoServer():
    config = configuration.getConfig()
    global PASSWORD
    global LOCK_TIME
    global HALT_TIME
    global STRESS_TIME
    PASSWORD = config.get("MAIN", "demo_password")
    LOCK_TIME = int(config.get("MAIN", "demo_lock_time"))
    HALT_TIME = int(config.get("MAIN", "demo_halt_time"))
    STRESS_TIME = int(config.get("MAIN", "demo_stress_time"))
    server_class = ThreadedHTTPServer
    httpd = server_class((LISTEN_HOST, LISTEN_PORT), MyHandler)
    print time.asctime(), "Demo Server Starts - %s:%s" % (LISTEN_HOST,
                                                          LISTEN_PORT)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Demo Server Stops - %s:%s" % (LISTEN_HOST,
                                                         LISTEN_PORT)
Ejemplo n.º 12
0
def postDataToHydra(attributes):
    config = configuration.getConfig()
    hydras = configuration.getHydras()
    hostname = None
    try:
        hostname = config.get("MAIN", "hostname")
    except Exception:
        hostname = socket.gethostname()
    hydra_data = {hostname: attributes}
    answer = json.dumps(hydra_data)
    logging.debug("Data to post:")
    logging.debug(answer)

    for hydra in hydras:
        lines = hydra.split(":")
        post_url = lines[0] + ":" + lines[1] + ":" + config.get(
            "MAIN", "hydra_admin_port") + "/apps/" + config.get(
                "MAIN", "app_id") + "/Instances"
        logging.debug("Posting to " + post_url)
        opener = urllib2.build_opener(urllib2.HTTPHandler)
        headers = {
            'hydra_access_key': config.get("MAIN", "hydra_access_key"),
            'hydra_secret_key': config.get("MAIN", "hydra_secret_key")
        }
        try:
            request = urllib2.Request(post_url, answer, headers=headers)
            request.add_header("content-type", "application/json")
            url = opener.open(request,
                              timeout=int(config.get("MAIN", "timeout")))
            if url.code != 200:
                logging.error(
                    "Error connecting with hydra {0}: Code: {1}".format(
                        post_url, url.code))
            else:
                logging.debug("Posted OK")
                break
        except Exception, e:
            logging.error(str(e))
            logging.error(
                "Exception connecting with hydra {0}".format(post_url))
Ejemplo n.º 13
0
 def render_GET(self, request):
     """ reveive http get requests from sms77.de """
     
     # get configuration
     conf = configuration.getConfig()
  
     # split the path into parameter
     params = request.path.rsplit("/")
     
     # catch wrong uri
     if len(params) < 4: return "WRONG URI"
     
     # check the httpkey for prevent spam
     if not database.checkHTTPGetKey(params[2], params[3]): return "WRONG KEY";
     
     # check first for incoming message or statusreport
     if params[1] == "message":
         return self.processMessage(params[2], request.args)
     elif params[1] == "status":
         return self.processReport(params[2], request.args)
     else:
         return "WRONG TYPE"
Ejemplo n.º 14
0
    def processMessage(self, jid, args):
        # get configuration
        conf = configuration.getConfig()

        # catch missing or empty sender string
        try:
            if len(args["from"][0]) <= 0: return "SENDER MISSING"
            
            # modify incoming phone number
            phonenumber = args["from"][0]
            if phonenumber.startswith("00"):
                phonenumber = "+" + phonenumber[2:]
        except exceptions.KeyError:
            return "SENDER MISSING"
        
        # create a new message
        status = domish.Element((None, "message"))
        status["to"] = jid        
        status["from"] = phonenumber + "@" + conf.jabberComponentName
        
        if database.getMessageAsChat(JID(jid)):
            status.attributes["type"] = "chat"
        else:
            status.addElement("subject", content="Eingehende SMS")

        try:
            body = args["text"][0].decode("latin1")
            status.addElement("body", content=body)
        except exceptions.KeyError:
            status.addElement("body")
        
        # send the message
        self.xmpp.send(status)
        
        # update the balance in the status
        self.xmpp.updateBalance(jid)

        return "OK"
Ejemplo n.º 15
0
    def processMessage(self, jid, args):
        # get configuration
        conf = configuration.getConfig()

        # catch missing or empty sender string
        try:
            if len(args["from"][0]) <= 0: return "SENDER MISSING"

            # modify incoming phone number
            phonenumber = args["from"][0]
            if phonenumber.startswith("00"):
                phonenumber = "+" + phonenumber[2:]
        except exceptions.KeyError:
            return "SENDER MISSING"

        # create a new message
        status = domish.Element((None, "message"))
        status["to"] = jid
        status["from"] = phonenumber + "@" + conf.jabberComponentName

        if database.getMessageAsChat(JID(jid)):
            status.attributes["type"] = "chat"
        else:
            status.addElement("subject", content="Eingehende SMS")

        try:
            body = args["text"][0].decode("latin1")
            status.addElement("body", content=body)
        except exceptions.KeyError:
            status.addElement("body")

        # send the message
        self.xmpp.send(status)

        # update the balance in the status
        self.xmpp.updateBalance(jid)

        return "OK"
Ejemplo n.º 16
0
def getContacts(jid):
    try:
        cursor = db.getCursor()
        cursor.execute("SELECT contact FROM contacts WHERE jid = %s",
                       (jid.userhost(), ))

        ret = []
        row = cursor.fetchone()

        while (row != None):
            if row[0] != "":
                ret.append(
                    JID(row[0] + "@" +
                        configuration.getConfig().jabberComponentName))

            row = cursor.fetchone()

        cursor.close()

        return ret
    except (AttributeError, MySQLdb.OperationalError):
        db.reconnect()
        return getContacts(jid)
Ejemplo n.º 17
0
    def render_GET(self, request):
        """ reveive http get requests from sms77.de """

        # get configuration
        conf = configuration.getConfig()

        # split the path into parameter
        params = request.path.rsplit("/")

        # catch wrong uri
        if len(params) < 4: return "WRONG URI"

        # check the httpkey for prevent spam
        if not database.checkHTTPGetKey(params[2], params[3]):
            return "WRONG KEY"

        # check first for incoming message or statusreport
        if params[1] == "message":
            return self.processMessage(params[2], request.args)
        elif params[1] == "status":
            return self.processReport(params[2], request.args)
        else:
            return "WRONG TYPE"
Ejemplo n.º 18
0
from wokkel import generic, disco
from wokkel.component import Component

from httpreceiver import HTTPReceiver
from xmpp import XMPPComponent, DiscoResponder, PresenceHandler, RegisterHandler, VCardHandler, GatewayHandler
import database
import messages

from twisted.words.xish import domish

application = service.Application("smsgateway")
sc = service.IServiceCollection(application)

# read configuration
configuration.init()
conf = configuration.getConfig()
readXmlConfig("/opt/smsgateway/config.xml", configuration.getConfig())

# initialize database
database.init(conf.mysqlHost, conf.mysqlUsername, conf.mysqlPassword, conf.mysqlDatabase)

# start xmpp component
xmpp = Component(conf.jabberHost, conf.jabberPort, conf.jabberComponentName, conf.jabberPassword)
xmpp.logTraffic = False
handler = XMPPComponent()
handler.setHandlerParent(xmpp)

# fallback handling
generic.FallbackHandler().setHandlerParent(xmpp)

# version handling
Ejemplo n.º 19
0
 def __init__(self, email, password):
     self.API = IQ_Option(email, password)
     self.config = configuration.getConfig()
     self.connection()
Ejemplo n.º 20
0
def main(prefix=''):

    if utils.inputMatch([]):

        utils.print_header("Cluster")
        utils.print_option("full", "launch [regular]-> keys")
        utils.print_option("launch", "launch cluster with various setup", True)
        utils.print_option("destroy/kill", "kill all instances")
        utils.print_option("list", "list all instances, using cache")
        utils.print_option(
            "list-clean", "list all instances after cleaning cache")
        utils.print_option("keys", "setup ssh keys on full cluster")
        utils.print_option("disks", "handle disk creation and deletion", True)
        utils.print_option(
            "rsync", "shortcuts to various synchronisation commands", True)
        utils.print_header("")
        utils.print_option("tunnel", "create a tunnel for connection")
        utils.print_option("network", "open network 8080")
        utils.print_option(
            "runall", "[runall command] run a command on every computer")

    if utils.inputMatch(['launch']):
        utils.print_header("Cluster Launch")
        utils.print_option(
            "launch regular", "launch cluster with localdata and commondata (ro)")
        utils.print_option(
            "launch naked", "launch naked cluster (no common, no local)")
        utils.print_option(
            "launch master-commonwritable", "launch master with common writable")
        utils.print_option(
            "launch master-naked", "launch master without stuff")
        utils.print_option(
            "launch commondata-only", "launch cluster with common (ro), but no local storage")
        utils.print_header("")

    if utils.inputMatch(['launch', 'regular']):
        mainLaunchRegular()

    if utils.inputMatch(['launch', 'naked']):
        mainLaunchNaked()

    if utils.inputMatch(['launch', 'commondata-only']):
        mainLaunchCommonDataOnly()

    if utils.inputMatch(['launch', 'master-commonwritable']):
        mainLaunchMasterCommonWritable()

    if utils.inputMatch(['launch', 'master-naked']):
        mainLaunchMasterNaked()

    if utils.inputMatch(['disks']):
        utils.print_header("disk handling")
        utils.print_option("disks create", "create data disks")
        utils.print_option("disks delete", "delete data disks")
        utils.print_header("")

    if utils.inputMatch(['disks', 'create']):
        clusterCreateDiskLocalData()

    if utils.inputMatch(['disks', 'delete']):
        clusterDeleteDiskLocalData()

    if utils.inputMatch(['list']):
        utils.print_header("INSTANCES")
        (listnodes, nodes) = instanceListAll()
        print listnodes
        print nodes

    if utils.inputMatch(['network']):
        networkOpen()

    if utils.inputMatch(['tunnel']):
        tunnel()

    if utils.inputMatch(['screenrc']):
        setScreenRc()

    if utils.inputMatch(['list-clean']):
        utils.print_header("Cleaning instance list ...")
        instanceListClean()
        utils.print_header("INSTANCES")

        (listnodes, nodes) = instanceListAll()
        print listnodes
        print nodes

    if utils.inputMatch(['keys']):
        sshKeysDeploy()

    if utils.inputMatch(['kill']) or utils.inputMatch(['destroy']):
        instanceKillAll()

    if utils.inputMatch(['rsync'], doPartial=False):
        utils.print_header("Cluster rsync")
        utils.print_option(
            "rsync to-master", "[sourceDir targetDir option1 option2] For syncrhonisation on master only")

        utils.print_option(
            "rsync from-master", "[sourceDir targetDir option1 option2] For syncrhonisation on master only")

        utils.print_option(
            "rsync all", "[sourceDir targetDir] For synchronisation on all nodes")

        utils.print_option(
            "rsync to-any", "[hostname sourceDir targetDir option1 option2] For syncrhonisation on hostname only")

        utils.print_option(
            "rsync from-any", "[hostname sourceDir targetDir option1 option2] For syncrhonisation from hostname only")

    if utils.inputMatch(['rsync', 'to-master'], doPartial=True):
        source = sys.argv[3]
        target = sys.argv[4]

        opts = sys.argv[5:]

        utils.rsyncLocalhostToOther(ipGetMaster(), source, target, opts)

    if utils.inputMatch(['rsync', 'from-master'], doPartial=True):
        source = sys.argv[3]
        target = sys.argv[4]

        opts = sys.argv[5:]

        utils.rsyncOtherToLocalhost(ipGetMaster(), source, target, opts)

    if utils.inputMatch(['rsync', 'to-any'], doPartial=True):
        host = sys.argv[3]
        source = sys.argv[4]
        target = sys.argv[5]

        opts = sys.argv[6:]

        utils.rsyncLocalhostToOther(ipGetAny(host), source, target, opts)

    if utils.inputMatch(['rsync', 'from-any'], doPartial=True):
        host = sys.argv[3]
        source = sys.argv[4]
        target = sys.argv[5]

        opts = sys.argv[6:]

        utils.rsyncOtherToLocalhost(ipGetAny(host), source, target, opts)

    if utils.inputMatch(['rsync', 'all'], doPartial=True):
        source = sys.argv[3]
        target = sys.argv[4]

        rsyncOnAllNodesLocalhostToLocalAsync(source, target)

    if utils.inputMatch(['full']):
        mainLaunchRegular()
        sshKeysDeploy()
        setScreenRc()

    if utils.inputMatch(['runall'], doPartial=True):
        command = sys.argv[2]
        runOnAllNodesAsync(command)

    if utils.inputMatch(['config']):
        print configuration.getConfig()
Ejemplo n.º 21
0
from wokkel import generic, disco
from wokkel.component import Component

from httpreceiver import HTTPReceiver
from xmpp import XMPPComponent, DiscoResponder, PresenceHandler, RegisterHandler, VCardHandler, GatewayHandler
import database
import messages

from twisted.words.xish import domish

application = service.Application("smsgateway")
sc = service.IServiceCollection(application)

# read configuration
configuration.init()
conf = configuration.getConfig()
readXmlConfig("/opt/smsgateway/config.xml", configuration.getConfig())

# initialize database
database.init(conf.mysqlHost, conf.mysqlUsername, conf.mysqlPassword,
              conf.mysqlDatabase)

# start xmpp component
xmpp = Component(conf.jabberHost, conf.jabberPort, conf.jabberComponentName,
                 conf.jabberPassword)
xmpp.logTraffic = False
handler = XMPPComponent()
handler.setHandlerParent(xmpp)

# fallback handling
generic.FallbackHandler().setHandlerParent(xmpp)
Ejemplo n.º 22
0
 def _onSetGateway(self, iq):
     reply = domish.Element((NS_GATEWAY, "query"))
     reply.addElement("prompt",
                      content=str(iq.query.prompt) + "@" +
                      configuration.getConfig().jabberComponentName)
     return reply
Ejemplo n.º 23
0
# -*- coding: utf-8 -*-

import requests
from utils import shoppe
import mysql.connector
import configuration
import re

category_id = 9824

config = configuration.getConfig()

mysql_config = config['mysql']

mydb = mysql.connector.connect(host=mysql_config['host'],
                               user=mysql_config['user'],
                               passwd=mysql_config['passwd'],
                               database=mysql_config['database'])

mycursor = mydb.cursor()

# lay id san pham da co trong he thong boi category_id
# --> can where theo type shop
mycursor.execute("SELECT item_id FROM product WHERE category_id = " +
                 str(category_id))
product_indb = mycursor.fetchall()
product_indb = [row[0] for row in product_indb]

data = shoppe.getProduct(category_id, 100)

items = data['items']
Ejemplo n.º 24
0
    Bem vindo ao exemplo de MHI via Telegram!.

    Use os comandos abaixo!
  '''

  for command in all_commands:
    msg += f" {command} - {all_commands[command]['description']}\n"
  Thread(target=send_message, args=( data, msg )).start()



while True:
  x = getUpdateResult()
  print('aguardando mensagem!')
  if len(x['result']) > 0:
    for data in x['result']:
      Thread(target=del_update, args=(data, )).start()
      if 'entities' in data['message']:
        if data['message']['entities'][0]['type'] == 'bot_command':
          if '/start' in data['message']['text']:
            command_start(data)
          else:
            for command in all_commands:
              if command in data['message']['text']:
                config_mhi = getConfig()
                callback = all_commands[command]['callback']
                callback( data, send_message, config_mhi )
                break
      else:
        Thread( target=send_message, args=(data, "Desculpa, não sei o que fazer!") ).start()
  time.sleep(0.25)
Ejemplo n.º 25
0
    updateLog.append(log)
    return db


if __name__ == '__main__':
    from argparse import ArgumentParser
    description = "Update the database"
    parser = ArgumentParser(description=description)
    parser.add_argument("events",
                        nargs='*',
                        metavar="EVENTS",
                        help='A list of events to update')
    args = parser.parse_args()

    print "Fetching configuration..."
    config = getConfig(u'Module:WL_data')
    try:
        with open('db.json', 'r') as f:
            db = json.load(f)
    except Exception as e:
        print u'Erro ao abrir db.json:', repr(e)
        db = {}
    print "Found %s events in the configuration." % len(config)

    commonsdb = DB()

    if args.events:
        print "Updating only %s event(s): %s." % (len(args.events), ', '.join(
            args.events))
        for event_name in args.events:
            event_configuration = config.get(event_name)
Ejemplo n.º 26
0
 def _onSetGateway(self, iq):
     reply = domish.Element((NS_GATEWAY, "query"))
     reply.addElement("prompt", content=str(iq.query.prompt) + "@" + configuration.getConfig().jabberComponentName)
     return reply