def __init__(self,
                 credentials,
                 encryption=False,
                 env=None,
                 top_layers=None):
        """
        :param credentials: number and registed password
        :param bool encryptionEnabled:  E2E encryption enabled/ disabled
        :param string env:  yowsup environment string
        :params top_layers: tuple of layer between :class:`yowsup_gateway.layer.CeleryLayer`
        and Yowsup Core Layers
        """
        if env and isinstance(env, str):
            YowsupEnv.setEnv(env)

        top_layers = top_layers + (CeleryLayer, ) if top_layers else (
            CeleryLayer, )
        layers = stacks.YowStackBuilder.getDefaultLayers(
            axolotl=encryption) + top_layers
        try:
            super(YowsupStack, self).__init__(layers, reversed=False)
        except ValueError as e:
            raise exceptions.ConfigurationError(e.args[0])
        self.setCredentials(credentials)
        self.detached_queue = Queue.Queue()
        self.facade = self.getLayerInterface(CeleryLayer)
        self.listening = False
    def process(self):
        super(RegistrationArgParser, self).process()

        config = self.getConfig(
            self.args["config"]) if self.args["config"] else {}

        if self.args["env"]:
            YowsupEnv.setEnv(self.args["env"])

        if self.args["mcc"]:
            config["mcc"] = self.args["mcc"]

        if self.args["mnc"]:
            config["mnc"] = self.args["mnc"]

        if self.args["phone"]:
            config["phone"] = self.args["phone"]

        if self.args["cc"]:
            config["cc"] = self.args["cc"]

        if not "mcc" in config:
            config["mcc"] = "000"

        if not "mnc" in config:
            config["mnc"] = "000"

        if not "sim_mcc" in config:
            config["sim_mcc"] = "000"

        if not "sim_mnc" in config:
            config["sim_mnc"] = "000"

        try:
            assert self.args["requestcode"] or self.args[
                "register"], "Must specify one of the modes -r/-R"
            assert "cc" in config, "Must specify cc (country code)"
            assert "phone" in config, "Must specify phone number"
        except AssertionError as e:
            self.tryPrint(e)
            self.tryPrint("\n")
            return False

        if not config["phone"].startswith(config["cc"]):
            self.tryPrint(
                "Error, phone number does not start with the specified country code\n"
            )
            return False

        config["phone"] = config["phone"][len(config["cc"]):]

        if self.args["requestcode"]:
            self.handleRequestCode(self.args["requestcode"], config)
        elif self.args["register"]:
            self.handleRegister(self.args["register"], config)
        else:
            return False

        return True
Exemple #3
0
    def __init__(self):
        YowsupEnv.setEnv('android')

        super(YowsupWebLayer, self).__init__()
        YowInterfaceLayer.__init__(self)

        self.connected = False
        self.username = None
        self.sendReceipts = False
        self.sendRead = False
        self.credentials = None

        self.jidAliases = {
            # "NAME": "*****@*****.**"
        }
Exemple #4
0
    def __init__(self, cc, p_in, idx):
        super(WAExistsRequest, self).__init__()

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("id", idx)
        self.addParam("lg", "en")
        self.addParam("lc", "GB")
        self.addParam("token", YowsupEnv.getCurrent().getToken(p_in))
        self.addParam("mistyped", '6')
        self.addParam('network_radio_type', '1')
        self.addParam('simnum', '1')
        self.addParam('s', '')
        self.addParam('copiedrc', '1')
        self.addParam('hasinrc', '1')
        self.addParam('rcmatch', '1')
        self.addParam('pid', os.getpid())
        self.addParam('extexist', '1')
        self.addParam('extstate', '1')

        self.url = "v.whatsapp.net/v2/exist"

        self.pvars = [
            "status", "reason", "sms_length", "voice_length", "result",
            "param", "pw", "login", "type", "expiration", "kind", "price",
            "cost", "currency", "price_expiration"
        ]

        self.setParser(JSONResponseParser())
Exemple #5
0
    def __init__(self, *args, **kwargs):
        super(DemosArgParser, self).__init__(*args, **kwargs)
        self.description = "Run a yowsup demo"

        configGroup = self.add_argument_group("Configuration options for demos")
        credentialsOpts = configGroup.add_mutually_exclusive_group()
        credentialsOpts.add_argument("-l", "--login", action="store", metavar="phone:b64password",
                                     help = "WhatsApp login credentials, in the format phonenumber:password, where password is base64 encoded.")
        credentialsOpts.add_argument("-c", "--config", action="store",
                                     help = "Path to config file containing authentication info. For more info about config format use --help-config")

        configGroup.add_argument('-E', '--env',
                                  action = "store",
                                  help = "Set the environment yowsup simulates",
                                  choices = YowsupEnv.getRegisteredEnvs())

        configGroup.add_argument("-M", "--unmoxie", action="store_true", help="Disable E2E Encryption")

        cmdopts = self.add_argument_group("Command line interface demo")
        cmdopts.add_argument('-y', '--yowsup', action = "store_true", help = "Start the Yowsup command line client")

        echoOpts = self.add_argument_group("Echo client demo")
        echoOpts.add_argument('-e', '--echo', action = "store_true", help = "Start the Yowsup Echo client")

        sendOpts = self.add_argument_group("Send client demo")
        sendOpts.add_argument('-s', '--send', action="store", help = "Send a message to specified phone number, "
                                                                     "wait for server receipt and exit",
                              metavar=("phone", "message"), nargs = 2)
        syncContacts = self.add_argument_group("Sync contacts")
        syncContacts.add_argument('-S','--sync', action = "store" , help = "Sync ( check valid ) whatsapp contacts",metavar =("contacts"))
    def generateAuthBlob(self, nonce):
        keys = KeyStream.generateKeys(self.credentials[1], nonce)
        currentEnv = YowsupEnv.getCurrent()

        inputKey = KeyStream(keys[2], keys[3])
        outputKey = KeyStream(keys[0], keys[1])

        # YowCryptLayer.setProp("inputKey", inputKey)

        nums = bytearray(4)

        # nums = [0] * 4

        username_bytes = list(map(ord, self.credentials[0]))
        nums.extend(username_bytes)
        nums.extend(nonce)

        utcNow = str(int(TimeTools.utcTimestamp()))
        time_bytes = list(map(ord, utcNow))
        nums.extend(time_bytes)

        strCat = "\x00\x00\x00\x00\x00\x00\x00\x00"
        strCat += currentEnv.getOSVersion() + "\x00"
        strCat += currentEnv.getManufacturer() + "\x00"
        strCat += currentEnv.getDeviceName() + "\x00"
        strCat += currentEnv.getBuildVersion()

        nums.extend(list(map(ord, strCat)))

        encoded = outputKey.encodeMessage(nums, 0, 4, len(nums) - 4)
        authBlob = "".join(map(chr, encoded))

        return (inputKey, outputKey, authBlob)
Exemple #7
0
def recv_message():
    layers = (
        EchoLayer,
        YowParallelLayer([
            YowAuthenticationProtocolLayer, YowMessagesProtocolLayer,
            YowReceiptProtocolLayer, YowAckProtocolLayer
        ]),
        AxolotlControlLayer,
        YowParallelLayer((AxolotlSendLayer, AxolotlReceivelayer)),
    ) + YOWSUP_CORE_LAYERS

    stack = YowStack(layers)
    # Setting credentials
    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)

    # WhatsApp server address
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE,
                  YowsupEnv.getCurrent().getResource())

    # Sending connecting signal
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
    try:
        # Program main loop
        stack.loop()
    except AuthError as e:
        print('Authentication error %s' % e.message)
        sys.exit(1)
Exemple #8
0
    def __init__(self,cc, p_in, idx):
        super(WAExistsRequest,self).__init__()

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("id", idx)
        self.addParam("lg", "en")
        self.addParam("lc", "GB")
        self.addParam("token", YowsupEnv.getCurrent().getToken(p_in))
        self.addParam("mistyped", '6')
        self.addParam('network_radio_type', '1')
        self.addParam('simnum', '1')
        self.addParam('s', '')
        self.addParam('copiedrc', '1')
        self.addParam('hasinrc', '1')
        self.addParam('rcmatch', '1')
        self.addParam('pid', os.getpid())
        self.addParam('extexist', '1')
        self.addParam('extstate', '1')

        self.url = "v.whatsapp.net/v2/exist"

        self.pvars = ["status", "reason", "sms_length", "voice_length", "result","param", "pw", "login", "type", "expiration", "kind",
                    "price", "cost", "currency", "price_expiration"
                    ]

        self.setParser(JSONResponseParser())
    def generateAuthBlob(self, nonce):
        keys = KeyStream.generateKeys(self.credentials[1], nonce)
        currentEnv = YowsupEnv.getCurrent()

        inputKey = KeyStream(keys[2], keys[3])
        outputKey = KeyStream(keys[0], keys[1])

        #YowCryptLayer.setProp("inputKey", inputKey)


        nums = bytearray(4)

        #nums = [0] * 4


        username_bytes = list(map(ord, self.credentials[0]))
        nums.extend(username_bytes)
        nums.extend(nonce)

        utcNow = str(int(TimeTools.utcTimestamp()))
        time_bytes =  list(map(ord, utcNow))
        nums.extend(time_bytes)

        strCat = "\x00\x00\x00\x00\x00\x00\x00\x00"
        strCat += currentEnv.getOSVersion() + "\x00"
        strCat += currentEnv.getManufacturer() + "\x00"
        strCat += currentEnv.getDeviceName() + "\x00"
        strCat += currentEnv.getBuildVersion()
        nums.extend(list(map(ord, strCat)))

        encoded = outputKey.encodeMessage(nums, 0, 4, len(nums) - 4)
        authBlob = "".join(map(chr, encoded))

        return (inputKey, outputKey, authBlob)
Exemple #10
0
    def process(self):
        super(RegistrationArgParser, self).process()

        config = self.getConfig(self.args["config"]) if self.args["config"] else {}

        if self.args["env"]:
            YowsupEnv.setEnv(self.args["env"])

        if self.args["mcc"]     : config["mcc"]     = self.args["mcc"]
        if self.args["mnc"]     : config["mnc"]     = self.args["mnc"]
        if self.args["phone"]   : config["phone"]   = self.args["phone"]
        if self.args["cc" ]     : config["cc"]      = self.args["cc"]
        #if self.args["sim_mnc"] : config["sim_mnc"] = self.args["sim_mnc"]
        #if self.args["sim_mcc"] : config["sim_mcc"] = self.args["sim_mcc"]

        if not "mcc"     in config: config["mcc"] = "000"
        if not "mnc"     in config: config["mnc"] = "000"
        if not "sim_mcc" in config: config["sim_mcc"] = "000"
        if not "sim_mnc" in config: config["sim_mnc"] = "000"




        try:
            assert self.args["requestcode"] or self.args["register"], "Must specify one of the modes -r/-R"
            assert "cc"      in config, "Must specify cc (country code)"
            assert "phone"   in config, "Must specify phone number"
        except AssertionError as e:
            print(e)
            print("\n")
            return False

        if not config["phone"].startswith(config["cc"]):
            print("Error, phone number does not start with the specified country code\n")
            return False

        config["phone"] = config["phone"][len(config["cc"]):]

        if self.args["requestcode"]:
            self.handleRequestCode(self.args["requestcode"], config)
        elif self.args["register"]:
            self.handleRegister(self.args["register"], config)
        else:
            return False

        return True
Exemple #11
0
    def process(self):
        super(DemosArgParser, self).process()

        if self.args["env"]:
            YowsupEnv.setEnv(self.args["env"])

        if self.args["yowsup"]:
            self.startCmdline()
        elif self.args["echo"]:
            self.startEcho()
        elif self.args["send"]:
            self.startSendClient()
        elif self.args["sync"]:
            self.startSyncContacts()
        else:
            return False
        return True
Exemple #12
0
    def process(self):
        self.args = vars(self.parse_args())

        if self.args["debug"]:
            logger.setLevel(logging.DEBUG)
            yowlogger.setLevel(level=logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
            yowlogger.setLevel(level=logging.INFO)

        YowsupEnv.setEnv("android")

        config_manager = ConfigManager()
        profile_name = None
        config_loaded_from_profile = True
        if self.args["config"]:
            config = config_manager.load(self.args["config"])
            if not os.path.isfile(self.args["config"]):
                profile_name = self.args["config"]
            elif not self.args["config"].startswith(
                    StorageTools.getStorageForProfile(config.phone)):
                config_loaded_from_profile = False
        else:
            raise ValueError("Must specify --config")

        if config is None:
            config = Config()

        if not config_loaded_from_profile:
            # config file was explicitly specified and is not that of profile,
            # load profile config and override values
            internal_config = config_manager.load(config.phone,
                                                  profile_only=True)
            if internal_config is not None:
                for property in config.keys():
                    if property != "version" and config[property] is not None:
                        internal_config[property] = config[property]
                config = internal_config

        if self._profile is None or self._profile.config is None:
            self._profile = YowProfile(profile_name or config.phone, config)

        if self._profile.config.phone is None:
            print("Invalid config")
            sys.exit(1)
Exemple #13
0
def workerwhatsapp():
    stackBuilder = YowStackBuilder()
    stack = stackBuilder.pushDefaultLayers(True).push(laye).build()
    stack.setCredentials(CREDENTIALS)
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE,
                  YowsupEnv.getCurrent().getResource())
    stack.loop(timeout=0.5, discrete=0.5)
Exemple #14
0
    def __init__(self, stackClassesArr = None, reversed = True, props = None):
        stackClassesArr = stackClassesArr or ()
        self.__stack = stackClassesArr[::-1] if reversed else stackClassesArr
        self.__stackInstances = []
        self._props = props or {}

        self.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[random.randint(0,len(YowConstants.ENDPOINTS)-1)])
        self.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
        self.setProp(YowCoderLayer.PROP_RESOURCE, YowsupEnv.getCurrent().getResource())
        self._construct()
Exemple #15
0
    def __init__(self, *args, **kwargs):
        super(RegistrationArgParser, self).__init__(*args, **kwargs)
        self.description = "WhatsApp Registration options"

        configGroup = self.add_argument_group("Configuration options",
                                              description = "Config file is optional. Other configuration arguments have higher priority if given, and will override those specified in the config file")

        configGroup.add_argument("-c", '--config',
                                 action = "store",
                                 help = 'Path to config file. If this is not set then you must set at least --phone and --cc arguments')

        configGroup.add_argument('-E', '--env',
                                  action = "store",
                                  help = "Set the environment yowsup simulates",
                                  choices = YowsupEnv.getRegisteredEnvs())

        configGroup.add_argument("-m", '--mcc',
                                 action = "store",
                                 help = "Mobile Country Code. Check your mcc here: https://en.wikipedia.org/wiki/Mobile_country_code")
        configGroup.add_argument("-n", '--mnc',
                                 action = "store",
                                 help = "Mobile Network Code. Check your mnc from https://en.wikipedia.org/wiki/Mobile_country_code")

        # configGroup.add_argument("-M", '--sim-mcc',
        #                          action = "store",
        #                          help = "Mobile Country Code. Check your mcc here: https://en.wikipedia.org/wiki/Mobile_country_code"
        #                          )
        # configGroup.add_argument("-N", '--sim-mnc',
        #                          action= "store",
        #                          help = "SIM MNC"
        #                          )

        configGroup.add_argument("-p", '--phone',
                                 action= "store",
                                 help = " Your full phone number including the country code you defined in 'cc', without preceeding '+' or '00'")
        configGroup.add_argument("-C", '--cc',
                                 action = "store",
                                 help = "Country code. See http://www.ipipi.com/networkList.do. This is now required")

        # configGroup.add_argument("-i", '--id',
        #                          action="store",
        #                          help = "Identity"
        #                          )

        regSteps = self.add_argument_group("Modes")
        regSteps = regSteps.add_mutually_exclusive_group()

        regSteps.add_argument("-r", '--requestcode', help='Request the digit registration code from Whatsapp.', action="store", required=False, metavar="(sms|voice)")
        regSteps.add_argument("-R", '--register', help='Register account on Whatsapp using the code you previously received', action="store", required=False, metavar="code")
Exemple #16
0
    def __init__(self, stackClassesArr=None, reversed=True, props=None):
        stackClassesArr = stackClassesArr or ()
        self.__stack = stackClassesArr[::-1] if reversed else stackClassesArr
        self.__stackInstances = []
        self._props = props or {}

        self.setProp(
            YowNetworkLayer.PROP_ENDPOINT,
            YowConstants.ENDPOINTS[random.randint(
                0,
                len(YowConstants.ENDPOINTS) - 1)])
        self.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
        self.setProp(YowCoderLayer.PROP_RESOURCE,
                     YowsupEnv.getCurrent().getResource())
        self._construct()
Exemple #17
0
def start_server():
    layers = (
        EchoLayer,
        YowParallelLayer([YowAuthenticationProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer]),YowAxolotlLayer
    ) + YOWSUP_CORE_LAYERS

    stack = YowStack(layers)
    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)         #setting credentials
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])    #whatsapp server address
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE, YowsupEnv.getCurrent().getResource())          #info about us as WhatsApp client

    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))   #sending the connect signal

    stack.loop()
Exemple #18
0
    def __init__(self, credentials, encryptionEnabled=True):
        stackBuilder = YowStackBuilder()

        self.stack = stackBuilder\
            .pushDefaultLayers(encryptionEnabled)\
            .push(CadastroLayer)\
            .build()

        self.stack.setCredentials(credentials)
        self.stack.setProp(YowNetworkLayer.PROP_ENDPOINT,
                           YowConstants.ENDPOINTS[0])  #whatsapp server address
        self.stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
        self.stack.setProp(YowCoderLayer.PROP_RESOURCE,
                           YowsupEnv.getCurrent().getResource()
                           )  #info about us as WhatsApp client
        self.stack.setProp(PROP_IDENTITY_AUTOTRUST, True)
Exemple #19
0
    def __init__(self,
                 cc,
                 p_in,
                 mcc="000",
                 mnc="000",
                 sim_mcc="000",
                 sim_mnc="000",
                 method="sms"):
        super(WACodeRequest, self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        self.p_in = p_in
        self.__id = idx
        self.cc = cc

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("lc", "GB")
        self.addParam("lg", "en")
        self.addParam("sim_mcc", sim_mcc.zfill(3))
        self.addParam("sim_mnc", sim_mnc.zfill(3))
        self.addParam("mcc", sim_mcc.zfill(3))
        self.addParam("mnc", sim_mnc.zfill(3))
        self.addParam("method", method)

        self.addParam("mistyped", "6")
        self.addParam("network_radio_type", "1")
        self.addParam("simnum", "1")
        self.addParam("s", "")
        self.addParam("copiedrc", "1")
        self.addParam("hasinrc", "1")
        self.addParam("rcmatch", "1")
        self.addParam("pid", int(random.uniform(100, 9999)))
        self.addParam("rchash", hashlib.sha256(os.urandom(20)).hexdigest())
        self.addParam("anhash", os.urandom(20))
        self.addParam("extexist", "1")
        self.addParam("extstate", "1")

        self.addParam("token", YowsupEnv.getCurrent().getToken(p_in))

        self.url = "v.whatsapp.net/v2/code"

        self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
                    ["login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration"]

        self.setParser(JSONResponseParser())
Exemple #20
0
    def __init__(self, config):
        """
        :param config:
        :type config: yowsup.config.v1.config.Config
        """
        super(WAExistsRequest,self).__init__(config)
        if config.id is None:
            raise ValueError("Config does not contain id")

        self.url = "v.whatsapp.net/v2/exist"

        self.pvars = ["status", "reason", "sms_length", "voice_length", "result","param", "login", "type",
                      "chat_dns_domain", "edge_routing_info"
                    ]

        self.setParser(JSONResponseParser())
        self.addParam("token", YowsupEnv.getCurrent().getToken(self._p_in))
def main():
    botLayer = BotLayer()
    stack = YowStackBuilder.getDefaultStack(botLayer,
                                            axolotl=True,
                                            groups=True,
                                            media=True,
                                            privacy=True,
                                            profiles=True)
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE,
                  YowsupEnv.getCurrent().getResource())
    stack.setCredentials(getCredentials())
    stack.setProp(PROP_IDENTITY_AUTOTRUST, True)

    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
    stack.loop()
Exemple #22
0
    def __init__(self,cc, p_in, idx):
        super(WAExistsRequest,self).__init__()

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("id", idx)
        self.addParam("lg", "en")
        self.addParam("lc", "GB")
        self.addParam("token", YowsupEnv.getCurrent().getToken(p_in))

        self.url = "v.whatsapp.net/v2/exist"

        self.pvars = ["status", "reason", "sms_length", "voice_length", "result","param", "pw", "login", "type", "expiration", "kind",
                    "price", "cost", "currency", "price_expiration"
                    ]

        self.setParser(JSONResponseParser())
Exemple #23
0
    def __init__(self, config):
        """
        :param config:
        :type config: yowsup.config.v1.config.Config
        """
        super(WAExistsRequest, self).__init__(config)
        if config.id is None:
            raise ValueError("Config does not contain id")

        self.url = "v.whatsapp.net/v2/exist"

        self.pvars = [
            "status", "reason", "sms_length", "voice_length", "result",
            "param", "login", "type", "chat_dns_domain", "edge_routing_info"
        ]

        self.setParser(JSONResponseParser())
        self.addParam("token", YowsupEnv.getCurrent().getToken(self._p_in))
    def __init__(self, *args, **kwargs):
        super(DemosArgParser, self).__init__(*args, **kwargs)

        self.description = "Run a yowsup demo"

        configGroup = self.add_argument_group(
            "Configuration options for demos")
        credentialsOpts = configGroup.add_mutually_exclusive_group()

        credentialsOpts.add_argument(
            "-l",
            "--login",
            action="store",
            metavar="phone:b64password",
            help=
            "WhatsApp login credentials, in the format phonenumber:password, where password is base64 encoded."
        )

        credentialsOpts.add_argument(
            "-c",
            "--config",
            action="store",
            help=
            "Path to config file containing authentication info. For more info about config format use --help-config"
        )

        configGroup.add_argument('-E',
                                 '--env',
                                 action="store",
                                 help="Set the environment yowsup simulates",
                                 choices=YowsupEnv.getRegisteredEnvs())

        configGroup.add_argument("-M",
                                 "--unmoxie",
                                 action="store_true",
                                 help="Disable E2E Encryption")

        cmdopts = self.add_argument_group("Command line interface demo")

        cmdopts.add_argument('-n',
                             '--news',
                             action="store",
                             metavar="date",
                             help="Start the news bot")
Exemple #25
0
    def __init__(self,cc, p_in, mcc= "000", mnc = "000", sim_mcc = "000", sim_mnc = "000", method="sms"):
        super(WACodeRequest,self).__init__()
        idx = StorageTools.getIdentity(cc + p_in)

        self.p_in = p_in
        self.__id = idx
        self.cc = cc

        self.addParam("cc", cc)
        self.addParam("in", p_in)
        self.addParam("lc", "GB")
        self.addParam("lg", "en")
        self.addParam("sim_mcc", sim_mcc.zfill(3))
        self.addParam("sim_mnc", sim_mnc.zfill(3))
        self.addParam("mcc", sim_mcc.zfill(3))
        self.addParam("mnc", sim_mnc.zfill(3))
        self.addParam("method", method)

        self.addParam("mistyped", "6")
        self.addParam("network_radio_type", "1")
        self.addParam("simnum", "1")
        self.addParam("s", "")
        self.addParam("copiedrc", "1")
        self.addParam("hasinrc", "1")
        self.addParam("rcmatch", "1")
        self.addParam("pid", int(random.uniform(100,9999)))
        self.addParam("rchash", hashlib.sha256(os.urandom(20)).hexdigest())
        self.addParam("anhash", os.urandom(20))
        self.addParam("extexist", "1")
        self.addParam("extstate", "1")

        self.addParam("token", YowsupEnv.getCurrent().getToken(p_in))

        self.url = "v.whatsapp.net/v2/code"

        self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
                    ["login", "pw", "type", "expiration", "kind", "price", "cost", "currency", "price_expiration"]

        self.setParser(JSONResponseParser())
Exemple #26
0
    def __init__(self, method, config):
        """
        :type method: str
        :param config:
        :type config: yowsup.config.v1.config.Config
        """
        super(WACodeRequest,self).__init__(config)

        self.addParam("mcc", config.mcc.zfill(3))
        self.addParam("mnc", config.mnc.zfill(3))
        self.addParam("sim_mcc", config.sim_mcc.zfill(3))
        self.addParam("sim_mnc", config.sim_mnc.zfill(3))
        self.addParam("method", method)
        self.addParam("reason", "")
        self.addParam("token", YowsupEnv.getCurrent().getToken(self._p_in))
        self.addParam("hasav", "1")

        self.url = "v.whatsapp.net/v2/code"

        self.pvars = ["status","reason","length", "method", "retry_after", "code", "param"] +\
                    ["login", "type", "sms_wait", "voice_wait"]
        self.setParser(JSONResponseParser())
Exemple #27
0
    def __init__(self, credentials, messages):
        layers = (SendMedia, ) + (
            YOWSUP_PROTOCOL_LAYERS_FULL, ) + YOWSUP_CORE_LAYERS

        stackBuilder = YowStackBuilder()

        self.stack = stackBuilder\
            .pushDefaultLayers(True)\
            .push(SendMedia)\
            .build()

        #envi = YowsupEnv()
        ##self.stack = YowStack(layers)
        self.stack.setProp(SendMedia.PROP_MESSAGES, messages)
        self.stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
        self.stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS,
                           credentials)
        self.stack.setProp(YowNetworkLayer.PROP_ENDPOINT,
                           YowConstants.ENDPOINTS[0])
        self.stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
        #self.stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource())
        self.stack.setProp(YowCoderLayer.PROP_RESOURCE,
                           YowsupEnv.getCurrent().getResource())
Exemple #28
0
def send_message(destination, message):
    '''
    destination is <phone number> without '+'
    and with country code of type string,
    message is string
    e.g send_message('11133434343','hello')
    '''
    messages = [(destination, message)]
    layers = (
        EchoLayer,
        YowParallelLayer([
            YowAuthenticationProtocolLayer, YowMessagesProtocolLayer,
            YowReceiptProtocolLayer, YowAckProtocolLayer
        ]),
        AxolotlControlLayer,
        YowParallelLayer((AxolotlSendLayer, AxolotlReceivelayer)),
    ) + YOWSUP_CORE_LAYERS
    stack = YowStack(layers)
    stack.setProp(EchoLayer.PROP_MESSAGES, messages)
    stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
    # Setting credentials
    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)

    # WhatsApp server address
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE,
                  YowsupEnv.getCurrent().getResource())

    # Sending connecting signal
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
    try:
        # Program main loop
        stack.loop()
    except AuthError as e:
        print('Authentication error %s' % e.message)
        sys.exit(1)
Exemple #29
0
 def getUserAgent(self):
     return YowsupEnv.getCurrent().getUserAgent()
Exemple #30
0

if __name__==  "__main__":
    #if credentials are unavailable, launch auth window.
    if len(CREDENTIALS[0]) < 2:
        #print(CREDENTIALS[0])
        auth_w = auth_window()

    #initialize yowsup stack, with the layers we need.
    StackBuilder = YowStackBuilder()
    stack = StackBuilder.getDefaultStack(layer=YowsupCliLayer, axolotl=True)
    
    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS) #setting credentials
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])     #whatsapp server address
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE, YowsupEnv.getCurrent().getResource())     #info about us as WhatsApp client
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))             #sending the connect signal

    
    for i in range(9):
        #print(str(i)+" = "+str(stack.getLayer(i)))
        if str(stack.getLayer(i)) == "CLI Interface Layer":
               InterfaceLayer = stack.getLayer(i)
               break
            
    #print(X)
    
    #setting bot and cli layer to know each other.
    BOT = InterfaceLayer.getBot()
    BOT.getCliLayer(InterfaceLayer)
    def __init__(self, *args, **kwargs):
        super(RegistrationArgParser, self).__init__(*args, **kwargs)

        self.description = "WhatsApp registration options"

        configGroup = self.add_argument_group(
            "Configuration options",
            description=
            "Config file is optional. Other configuration arguments have higher priority if given, and will override those specified in the config file"
        )

        configGroup.add_argument(
            "-c",
            '--config',
            action="store",
            help=
            'Path to config file. If this is not set then you must set at least --phone and --cc arguments'
        )

        configGroup.add_argument('-E',
                                 '--env',
                                 action="store",
                                 help="Set the environment yowsup simulates",
                                 choices=YowsupEnv.getRegisteredEnvs())

        configGroup.add_argument(
            "-m",
            '--mcc',
            action="store",
            help=
            "Mobile Country Code. Check your mcc here: https://en.wikipedia.org/wiki/Mobile_country_code"
        )

        configGroup.add_argument(
            "-n",
            '--mnc',
            action="store",
            help=
            "Mobile Network Code. Check your mnc from https://en.wikipedia.org/wiki/Mobile_country_code"
        )

        configGroup.add_argument(
            "-p",
            '--phone',
            action="store",
            help=
            " Your full phone number including the country code you defined in 'cc', without preceeding '+' or '00'"
        )

        configGroup.add_argument(
            "-C",
            '--cc',
            action="store",
            help=
            "Country code. See http://www.ipipi.com/networkList.do. This is now required"
        )

        regSteps = self.add_argument_group("Modes")
        regSteps = regSteps.add_mutually_exclusive_group()

        regSteps.add_argument(
            "-r",
            '--requestcode',
            help='Request the digit registration code from Whatsapp.',
            action="store",
            required=False,
            metavar="(sms|voice)")

        regSteps.add_argument(
            "-R",
            '--register',
            help=
            'Register account on Whatsapp using the code you previously received',
            action="store",
            required=False,
            metavar="code")
Exemple #32
0
if __name__ == "__main__":

    setup()

    stackBuilder = YowStackBuilder()

    send_layer = SendLayer()

    stack = stackBuilder.pushDefaultLayers(True).push(send_layer).build()

    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE,
                  YowsupEnv.getCurrent().getResource())
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))

    try:

        print("Starting thread")

        t = Thread(target=check_for_reminder_messages, args=(send_layer, ))
        t.start()

        print("Starting the loop")
        stack.loop(timeout=0.5, discrete=0.5)
        print("Done")
    except AuthError as e:
        print("Authentication Error: %s" % e.message)
Exemple #33
0
        AxolotlSendLayer,
        YowLoggerLayer,
        YowCoderLayer,
        YowCryptLayer,
        YowStanzaRegulator,
        YowNetworkLayer
    ) + YOWSUP_CORE_LAYERS

    stack = YowStack(layers)
    # Setting credentials
    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)

    # WhatsApp server address
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
    stack.setProp(YowCoderLayer.PROP_RESOURCE, YowsupEnv.getCurrent().getResource())

    # Sending connecting signal
    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
    print('Iniciado.')
    try:
        # Program main loop
        stack.loop()
    except KeyboardInterrupt as e:
        print('Saindo...')
else:
    print('Syntax: {} <config_file>'.format(sys.argv[0]))



Exemple #34
0
 def getUserAgent(self):
     return YowsupEnv.getCurrent().getUserAgent()
Exemple #35
0
from yowsup.layers.protocol_receipts           import YowReceiptProtocolLayer
from yowsup.layers.protocol_acks               import YowAckProtocolLayer
from yowsup.layers.network                     import YowNetworkLayer
from yowsup.layers.coder                       import YowCoderLayer
from yowsup.layers.protocol_iq                 import YowIqProtocolLayer
from yowsup.stacks import YowStack
from yowsup.common import YowConstants
from yowsup.layers import YowLayerEvent
from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS
from yowsup.layers.axolotl                     import YowAxolotlLayer
from yowsup.env import YowsupEnv


CREDENTIALS = ("CC9999999999", "password-here") # replace with your phone and password

if __name__==  "__main__":
    layers = (
        EchoLayer,
        YowParallelLayer([YowAuthenticationProtocolLayer, YowIqProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer]),YowAxolotlLayer
    ) + YOWSUP_CORE_LAYERS

    stack = YowStack(layers)
    stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, CREDENTIALS)         #setting credentials
    stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])    #whatsapp server address
    stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)              
    stack.setProp(YowCoderLayer.PROP_RESOURCE, YowsupEnv.getCurrent().getResource())          #info about us as WhatsApp client

    stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))   #sending the connect signal

    stack.loop() #this is the program mainloop
Exemple #36
-2
    def process(self):
        super(DemosArgParser, self).process()

        if self.args["env"]:
            YowsupEnv.setEnv(self.args["env"])

        if self.args["news"]:
            self.startNews()
        else:
            return False
        return True