SMS or MMS Message (v2)
@constructor
@param {Object} client Catapult client
544388
function (client) {
	this._createIrisRequestOptions = function (params) {
		var auth = params.auth;
		var baseUrl = "https://dashboard.bandwidth.com/v1.0";
		var accountPath = "/api/accounts/" + auth.accountId;
		var xml = null;
		var headers = {
			"User-Agent" : client.getUserAgentHeader()
		};
		if (params.body){
			headers["Content-Type"] = "application/xml";
			xml = convert.js2xml(params.body, {compact: true});
		}
		return {
			url                : baseUrl + accountPath + "/" + params.path,
			headers            : headers,
			qs                 : params.qs,
			method             : params.method || "GET",
			auth               : {
				user : auth.userName,
				pass : auth.password
			},
			json               : false,
			body               : xml,
			rejectUnauthorized : false, // for some reason this is required for bootcamp ssl
			encoding           : params.encoding || undefined
		};
	};

	this._handleResponse = function (response) {
		var body = convert.xml2js(response.body || "<Response></Response>", {compact: true, nativeType: true});
		var code = findFirstDescendant(body, "ErrorCode");
		var description = findFirstDescendant(body, "Description");
		if(!code){
			var error = findFirstDescendant(body, "Error");
			if(error){
				code = (error.Code || {})._text;
				description = (error.Description || {})._text;
			}
			else{
				var errs =  findDescendants(body, "Errors");
				if(errs.length === 0){
					code = findFirstDescendant(body, "resultCode");
					description = findFirstDescendant(body, "resultMessage");
				}
				else{
					throw new UnexpectedResponseError(errs.map(function(e){
						return (error.Code || {})._text + ": " + (error.Description || {})._text;
					}).join("\n"), res.statusCode);
				}
			}
		}
		if(code && description && code !== "0"){
			throw new UnexpectedResponseError(code + ": " + description, response.statusCode);
		}
		if (response.statusCode >= 400){
			throw new UnexpectedResponseError("Http code " + response.statusCode, response.statusCode);
		}
		return [body, response];
	};

	this._makeIrisRequest = function (params) {
		return request(this._createIrisRequestOptions(params)).then(this._handleResponse.bind(this));
	};

	this._createApplication = function (auth, data) {
		return this._makeIrisRequest({
			path       : "applications",
			method     : "POST",
			auth       : auth,
			body: {
				"Application": {
					"AppName": {_text: data.name},
					"CallbackUrl": {_text: data.callbackUrl},
					"CallBackCreds": data.callbackAuthData ? {
						"UserId": {_text: data.callbackAuthData.userName},
						"Password": {_text: data.callbackAuthData.password}
					} : null
				}
			}
		}).then(function(result){
			return findFirstDescendant(result[0], "ApplicationId");
		});
	};

	this._createLocation = function (auth, data) {
		return this._makeIrisRequest({
			path       : "sites/" + auth.subaccountId + "/sippeers",
			method     : "POST",
			auth       : auth,
			body: {
				"SipPeer": {
					"PeerName": {_text: data.locationName},
					"IsDefaultPeer": {_text: data.isDefaultLocation}
				}
			}
		}).then(function(result){
			var response = result[1];
			var location = response.headers.location;
			return location.substring(location.lastIndexOf("/") + 1);
		});
	};

	this._enableSms = function (auth, options, application) {
		if (!options || !options.enabled) {
			return Promise.resolve();
		}
		return  this._makeIrisRequest({
			path       : "sites/" + auth.subaccountId + "/sippeers/" + application.locationId + "/products/messaging/features/sms",
			method     : "POST",
			auth       : auth,
			body: {
				"SipPeerSmsFeature": {
					"SipPeerSmsFeatureSettings": {
						"TollFree": {_text: !!options.tollFreeEnabled},
						"ShortCode": {_text: !!options.shortCodeEnabled},
						"Protocol": {_text: "HTTP"},
						"Zone1": {_text: true},
						"Zone2": {_text: false},
						"Zone3": {_text: false},
						"Zone4": {_text: false},
						"Zone5": {_text: false}
					},
					"HttpSettings": {
						"ProxyPeerId": {_text: "539692"}
					}
				}
			}
		});
	};

	this._enableMms = function (auth, options, application) {
		if (!options || !options.enabled) {
			return Promise.resolve();
		}
		return  this._makeIrisRequest({
			path       : "sites/" + auth.subaccountId + "/sippeers/" + application.locationId + "/products/messaging/features/mms",
			method     : "POST",
			auth       : auth,
			body: {
				"MmsFeature": {
					"MmsSettings": {
						"protocol": {_text: "HTTP"}
					},
					"Protocols": {
						"HTTP": {
							"HttpSettings": {
								"ProxyPeerId": {_text: "539692"}
							}
						}
					}
				}
			}
		});
	};

	this._assignApplicationToLocation = function (auth, application) {
		return  this._makeIrisRequest({
			path       : "sites/" + auth.subaccountId + "/sippeers/" + application.locationId + "/products/messaging/applicationSettings",
			method     : "POST",
			auth       : auth,
			body: {
				"ApplicationsSettings": {
					"HttpMessagingV2AppId": {_text: application.applicationId}
				}
			}
		});
	};

	/**
	* Create messaging application on Bandwidth Dashboard (its id is required to send messages)
	* @param {Object} auth Bandwidth Dashboard auth data {accountId: "accountId",	userName: "userName", password: "password",	subaccountId: "subaccountId"}
	* @param {Object} data Options of new application
	* @param {String} data.name Application name
	* @param {String} data.callbackUrl callback url to receive messages events
	* @param {Object} data.callbackAuthData optional callback basic auth data ({userName: "", pasword: ""})
	* @param {String} data.locationName Location name
	* @param {Boolean} data.isDefaultLocation is location default
	* @param {Object} data.smsOptions SMS options
	* @param {Boolean} data.smsOptions.enabled are SMSes enabled
	* @param {Boolean} data.smsOptions.tollFreeEnabled can toll free numbers to be used with SMS
	* @param {Boolean} data.smsOptions.shortCodeEnabled can short numbers to be used with SMS
	* @param {Object} data.mmsOptions MMS options
	* @param {Boolean} data.mmsOptions.enabled are MMSes enabled
	* @returns {Object} Created application data {applicationId: "", locationId: ""}
	*
	* @example
	* client.v2.Message.createMessagingApplication(authData, {
	*   name: "My Messaging App",
	*   callbackUrl: "http://your/callback/handler",
	*   locationName: "Current",
	*   smsOptions: {enabled: true},
	*   mmsOptions: {enabled: true}
	* }).then(function (application) {});
	*/
	this.createMessagingApplication = function (auth, data, callback) {
		var app;
		var self = this;
		return Promise.all([self._createApplication(auth, data), self._createLocation(auth, data)])
			.then(function (result) {
				app = {
					applicationId: result[0],
					locationId: result[1]
				};
				return self._enableSms(auth, data.smsOptions, app);
			})
			.then(function () {
				return self._enableMms(auth, data.mmsOptions, app);
			})
			.then(function () {
				return self._assignApplicationToLocation(auth, app);
			})
			.then(function () {
				return app;
			})
			.asCallback(callback);
	};

	/**
	* Look for and reserve phone numbers on Bandwidth Dashboard
	* @param {Object} auth Bandwidth Dashboard auth data {accountId: "accountId",	userName: "userName", password: "password",	subaccountId: "subaccountId"}
	* @param {Object} app Application data (result of createMessagingApplication())
	* @param {AreaCodeSearchAndOrderNumbersQuery|RateCenterSearchAndOrdeNumbersQuery|NpaNxxSearchAndOrderNumbersQuery|TollFreeVanitySearchAndOrderNumbersQuery|TollFreeWildCharSearchAndOrderNumbersQuery|StateSearchAndOrderNumbersQuery|CitySearchAndOrderNumbersQuery|ZipSearchAndOrderNumbersQuery|LataSearchAndOrderNumbersQuery|CombinedSearchAndOrderNumbersQuery} query Search query
	* @returns {Array} Array of reserved phone number
	*
	* @example
	* client.v2.Message.searchAndOrderNumbers(authData, new client.AreaCodeSearchAndOrderNumbersQuery({areaCode: "910", quantity: 3})).then(function (numbers) {});
	*/
	this.searchAndOrderNumbers = function (auth, app, query, callback) {
		var self = this;
		query = query || {};
		var timeout = (query.timeout || 60) * 1000;
		var queryXml = util.isFunction(query.toXml) ? query.toXml() : query;
		queryXml["SiteId"] = {_text: auth.subaccountId};
		queryXml["PeerId"] = {_text: app.locationId};
		return self._makeIrisRequest({
			path       : "orders",
			method     : "POST",
			auth       : auth,
			body: {
				"Order": queryXml
			}
		})
		.then(function (result) {
			return findFirstDescendant(result[0], "Order").id._text;
		})
		.then(function (orderId) {
			return new Promise(function (resolve, reject) {
				var timer = null;
				var timeoutReached = false;
				var checkTimeout = function () {
					if (timeoutReached) {
						clearInterval(timer);
						reject(new UnexpectedResponseError("Timeout", 400));
					}
				};
				setTimeout(function () {
					timeoutReached = true;
				}, timeout);
				timer = setInterval(function () {
					return self._makeIrisRequest({
						path       : "orders/" + orderId,
						method     : "GET",
						auth       : auth
					})
					.then(function (result) {
						var status = findFirstDescendant(result[0], "OrderStatus");
						if (["COMPLETE", "PARTIAL"].indexOf(status) >= 0) {
							var completedNumbers = findFirstDescendant(result[0], "CompletedNumbers");
							clearInterval(timer);
							return resolve(findDescendants(completedNumbers, "FullNumber"));
						}
						if (status === "FAILED") {
							clearInterval(timer);
							return reject(new UnexpectedResponseError("Error on reserving phone numbers", 400));
						}
						checkTimeout();
					});
				}, 500);
			});
		})
		.asCallback(callback);
	};

	/**
	 * Send a new SMS or MMS message
	 * @param  {Object} params Parameters for sending a new message.
	 * @param  {String} params.text The message text to send
	 * @param  {String} params.from The message sender"s telephone number (or short code)
	 * This must be a Catapult Dashboard number that you own
	 * @param  {String|Array} params.to Message recipient telephone number (or short code)
	 * @param  {Array} [params.media] Json array containing list of media urls to be sent as content for an mms.
	 * Valid URLs are: https://api.catapult.inetwork.com/v1/users/<user-id>/media/
	 * We also support media URLs that are external to Bandwidth API, http:// or https:// format:
	 * Example: http://customer-web-site.com/file.jpg
	 * @param  {String} [params.tag] A string that will be included in the callback events of the message
	 * @param  {String} applicationId A Dashboard application Id
	 * @param  {Function} [callback] A callback for the new message object
	 * @returns {Object} A promise for the new message object
	 * @example
	 * client.v2.Message.send({
	 *   from : "+19195551212",
	 *   to   : ["+19195551213"],
	 *   text : "Thank you for susbcribing to Unicorn Enterprises!",
	 *   applicationId : "appId" // app.applicationId
	 * })
	 * .then(function(message){
	 *   console.log(message);
	 * });
	 */
	this.send = function (params, callback) {
		return client.makeRequest({
            apiBaseUrl : "https://messaging.bandwidth.com/api",
			apiVersion : "v2",
			path       : "messages",
			method     : "POST",
			body       : params
		})
		.then(function (response) {
			return response.body;
		})
		.asCallback(callback);
	};
}
1190835
function postMessage(channelState, messageJson) {
  var writePromise = writeMessage(channelState.channelName, channelState.uuid, messageJson, channelState.paths);
  channelState.writeBlockPromise = channelState.writeBlockPromise.then(
  /*#__PURE__*/
  _asyncToGenerator(
  /*#__PURE__*/
  _regeneratorRuntime.mark(function _callee3() {
    var _ref4, msgObj, pingStr, writeToReadersPromise;

    return _regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return new Promise(function (res) {
              return setTimeout(res, 0);
            });

          case 2:
            _context3.next = 4;
            return Promise.all([writePromise, refreshReaderClients(channelState)]);

          case 4:
            _ref4 = _context3.sent;
            msgObj = _ref4[0];
            emitOverFastPath(channelState, msgObj, messageJson);
            pingStr = '{"t":' + msgObj.time + ',"u":"' + msgObj.uuid + '","to":"' + msgObj.token + '"}|';
            writeToReadersPromise = Promise.all(Object.values(channelState.otherReaderClients).filter(function (client) {
              return client.writable;
            }) // client might have closed in between
            .map(function (client) {
              return new Promise(function (res) {
                client.write(pingStr, res);
              });
            }));
            /**
             * clean up old messages
             * to not waste resources on cleaning up,
             * only if random-int matches, we clean up old messages
             */

            if (randomInt(0, 20) === 0) {
              /* await */
              getAllMessages(channelState.channelName, channelState.paths).then(function (allMessages) {
                return cleanOldMessages(allMessages, channelState.options.node.ttl);
              });
            }

            return _context3.abrupt("return", writeToReadersPromise);

          case 11:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  })));
  return channelState.writeBlockPromise;
}
789381
public function sendSmsToViettelWithMPSGateway()
    {
        $this->logger->debug(__FUNCTION__, 'Input Data Send SMS to Viettel MPS Gateway => ' . json_encode($this->inputData));
        $getConfig    = $this->getConfigData();
        $phone_number = $this->inputData['phone_number'];
        $msg          = $this->inputData['msg'];
        $alias        = $this->inputData['alias'];
        $params       = $this->inputData['params'];
        $this->logger->debug(__FUNCTION__, 'MT Message Length: ' . $this->lengthMtMessage($msg));
        $phone_number = $this->phoneNumber->vn_convert_phone_number($phone_number, 'new');
        $content      = trim($msg);
        $url          = $this->wsConfig['api_link'];
        $username     = $this->wsConfig['username'];
        $password     = $this->wsConfig['password'];
        $shortcode    = $this->wsConfig['shortcode'];
        $timeout      = $this->wsConfig['timeout'];
        // Request Data với XML thuần
        $data_xml = '<?xml version="1.0"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://smsws/xsd"><soapenv:Header/><soapenv:Body><xsd:smsRequest><xsd:username>' . $username . '</xsd:username><xsd:password>' . $password . '</xsd:password><xsd:msisdn>' . $phone_number . '</xsd:msisdn><xsd:content>' . $content . '</xsd:content><xsd:shortcode>' . $shortcode . '</xsd:shortcode><xsd:alias>' . $alias . '</xsd:alias><xsd:params>' . $params . '</xsd:params></xsd:smsRequest></soapenv:Body></soapenv:Envelope>';
        $this->logger->info(__FUNCTION__, 'Send Request to URL ' . $url);
        $this->logger->info('Send Request Data ' . $data_xml);
        $requestSms = $this->requests->xmlRequest($url, $data_xml, $timeout); // Gửi Request SMS
        $this->logger->info(__FUNCTION__, 'SendSms Result: ' . json_encode($requestSms));
        $returnResult = $this->requests->xmlGetValue($requestSms, "<return>", "</return>"); // Display the result
        if ($returnResult == self::SEND_SMS_SUCCESS) {
            $result = array(
                'status'        => self::EXIT_SUCCESS,
                'msg'           => 'Gửi tin nhắn thành công',
                'data'          => array('returnResult' => $returnResult, 'requestResult' => $requestSms),
                'request_data'  => array('url' => $url, 'params' => $data_xml, 'method' => 'POST'),
                'response_data' => $requestSms,
                'content_data'  => array(
                    'phone_number' => $phone_number,
                    'msg'          => $msg,
                    'mo'           => isset($this->inputData['mo']) ? $this->inputData['mo'] : NULL,
                    'note'         => isset($this->inputData['note']) ? $this->inputData['note'] : NULL,
                    'subCode'      => isset($this->inputData['subCode']) ? $this->inputData['subCode'] : NULL
                )
            );
        } else {
            if (array_key_exists($returnResult, $getConfig[self::CONFIG_KEY_SMS_GATEWAY_VIETTEL]['responseMap'])) {
                $result = array(
                    'status'        => self::EXIT_ERROR,
                    'msg'           => 'Gửi tin nhắn thất bại',
                    'data'          => array(
                        'returnResult'     => $returnResult,
                        'returnResultDesc' => Utils::strToEn($getConfig['responseMap'][$returnResult]),
                        'requestResult'    => $requestSms
                    ),
                    'request_data'  => array('url' => $url, 'params' => $data_xml, 'method' => 'POST'),
                    'response_data' => $requestSms,
                    'content_data'  => array(
                        'phone_number' => $phone_number,
                        'msg'          => $msg,
                        'mo'           => isset($this->inputData['mo']) ? $this->inputData['mo'] : NULL,
                        'note'         => isset($this->inputData['note']) ? $this->inputData['note'] : NULL,
                        'subCode'      => isset($this->inputData['subCode']) ? $this->inputData['subCode'] : NULL
                    )
                );
            } else {
                $result = array(
                    'status'        => self::EXIT_CONFIG,
                    'msg'           => 'Lỗi hệ thống',
                    'data'          => array('returnResult' => $returnResult, 'requestResult' => $requestSms),
                    'request_data'  => array('url' => $url, 'params' => $data_xml, 'method' => 'POST'),
                    'response_data' => $requestSms,
                    'content_data'  => array(
                        'phone_number' => $phone_number,
                        'msg'          => $msg,
                        'mo'           => isset($this->inputData['mo']) ? $this->inputData['mo'] : NULL,
                        'note'         => isset($this->inputData['note']) ? $this->inputData['note'] : NULL,
                        'subCode'      => isset($this->inputData['subCode']) ? $this->inputData['subCode'] : NULL
                    )
                );
            }
        }
        if ($this->responseIsObject) {
            $result = Utils::arrayToObject($result);
        }
        $this->sendSmsResult = $result;
        $this->logger->info(__FUNCTION__, 'Send SMS Result: ' . json_encode($this->sendSmsResult));

        return $this;
    }
614261
function onMessage(data) {
    if (data.type == "utf8") {
        message = JSON.parse(data.utf8Data);
        switch (message.command) {
            case "setJoints":
                console.log("Client has request to add joints: " + message.data);
                nuimotion.jointsTracking = message.data;
                break;

            case "addListener":
                console.log("Client has request to add events: " + message.data);
                if (!nuimotion._eventCallbackDict[message.data]) {
                    nuimotion.addListener(message.data, onEvent);
                }
                break;

            case "addGesture":
                console.log("Client has request to add gestures: " + message.data);
                if (!nuimotion._gestureCallbackDict[message.data]) {
                    nuimotion.addGesture(message.data, onEvent);
                }
                break;
        }
    }
}
332894
function sendMessage( ws, type, content )
{
	let sMessage	= JSON.stringify([type, content]);
	if ( ws.readyState !== ws.OPEN )
	{
		return console.log( "readyState=" + ws.readyState + ' on peer ' + ws.peer + ', will not send ' + sMessage );
	}

	//	...
	console.log( "SENDING " + sMessage + " to " + ws.peer );
	ws.send( sMessage );
}
384766
def format_sms_payload(self, message, to, sender='elkme', options=[]):
        
        self.validate_number(to)

        if not isinstance(message, str):
            message = " ".join(message)

        message = message.rstrip()

        sms = {
            'from': sender,
            'to': to,
            'message': message
        }

        for option in options:
          if option not in ['dontlog', 'dryrun', 'flashsms']:
            raise ElksException('Option %s not supported' % option)
          sms[option] = 'yes'

        return sms
256184
def send_mass_sms(datatuple, fail_silently=False,
             auth_user=None, auth_password=None, connection=None):
    

    from sendsms.message import SmsMessage
    connection = connection or get_connection(
        username = auth_user,
        password = auth_password,
        fail_silently = fail_silently
    )
    messages = [SmsMessage(message=message, from_phone=from_phone, to=to, flash=flash)
                for message, from_phone, to, flash in datatuple]
    connection.send_messages(messages)
194050
function(msg) {
        var ack;

        if (msg.type === asyncMessageType.MESSAGE_ACK_NEEDED || msg.type === asyncMessageType.MESSAGE_SENDER_ACK_NEEDED) {
          ack = function() {
            pushSendData({
              type: asyncMessageType.ACK,
              content: {
                messageId: msg.id
              }
            });
          }
        }

        switch (msg.type) {
          case asyncMessageType.PING:
            handlePingMessage(msg);
            break;

          case asyncMessageType.SERVER_REGISTER:
            handleServerRegisterMessage(msg);
            break;

          case asyncMessageType.DEVICE_REGISTER:
            handleDeviceRegisterMessage(msg.content);
            break;

          case asyncMessageType.MESSAGE:
            fireEvent("message", msg);
            break;

          case asyncMessageType.MESSAGE_ACK_NEEDED:
          case asyncMessageType.MESSAGE_SENDER_ACK_NEEDED:
            ack();
            fireEvent("message", msg);
            break;

          case asyncMessageType.ACK:
            fireEvent("message", msg);
            if (ackCallback[msg.senderMessageId] == "function") {
              ackCallback[msg.senderMessageId]();
              delete ackCallback[msg.senderMessageId];
            }
            break;

          case asyncMessageType.ERROR_MESSAGE:
            fireEvent("error", {
              errorCode: 4002,
              errorMessage: "Async Error!",
              errorEvent: msg
            });
            break;
        }
      }
371257
function send() {
  var message = arguments.length <= 0 || arguments[0] === undefined ? 'hello mqtt-controls' : arguments[0];
  var topic = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];

  var t = undefined;
  if (topic === null) {
    t = topics.publish;
  } else {
    t = topic;
  }
  client.publish(t, message);
}
756806
function () {
		if (connectionRequestID) {
			var data = {
				actions: []
			};
			if (status.actions.eChipSet) {
				data.actions.push(MESSENGER_CONST.ACTION.ECHIP_SET);
			}
			if (status.actions.eChipGet) {
				data.actions.push(MESSENGER_CONST.ACTION.ECHIP_GET);
			}
			composeMessage(connectionRequestID, MESSENGER_CONST.TYPE.RESPONSE, MESSENGER_CONST.ACTION.CONNECT, data);
		}
	}
210632
function clickSendMessage() {
    var currentText = $('#message_text').val().trim();

    if (!currentText.length) {
        return;
    }

    $('#message_text').val('').focus();

    sendMessage(currentText, null);
}
489932
function addMessage(oMessage) {
			var oReportMessage = {
					code : oMessage.code,
					message : oMessage.message,
					technical : oMessage.technical
				};

			Object.keys(oMessage).forEach(function (sProperty) {
				if (sProperty[0] === '@') {
					if (sProperty.endsWith(".numericSeverity")) {
						oReportMessage.numericSeverity = oMessage[sProperty];
					} else if (sProperty.endsWith(".longtextUrl") && oError.requestUrl
							&& sResourcePath) {
						oReportMessage.longtextUrl =
							_Helper.makeAbsolute(oMessage[sProperty], oError.requestUrl);
					}
				}
			});

			if (typeof oMessage.target !== "string") {
				aUnboundMessages.push(oReportMessage);
			} else if (oMessage.target[0] === "$" || !sResourcePath) {
				// target for the bound message cannot be resolved -> report as unbound message
				oReportMessage.message = oMessage.target + ": " + oReportMessage.message;
				aUnboundMessages.push(oReportMessage);
			} else {
				oReportMessage.target = oMessage.target;
				oReportMessage.transition = true;
				aBoundMessages.push(oReportMessage);
			}
		}
412650
function(message){
							if (!message) // the message is already gone
								return cb();
							var objDeviceMessage = JSON.parse(message);
							//if (objDeviceMessage.to !== row.to)
							//    throw "to mismatch";
							console.log('sending stalled '+row.message_hash);
							sendPreparedMessageToHub(row.hub, row.pubkey, row.message_hash, objDeviceMessage, {ifOk: cb, ifError: function(err){ cb(); }});
						}
808122
function _handleMessagePing() {
  _handleMessagePing = _asyncToGenerator(
  /*#__PURE__*/
  _regeneratorRuntime.mark(function _callee18(state, msgObj) {
    var messages, useMessages;
    return _regeneratorRuntime.wrap(function _callee18$(_context18) {
      while (1) {
        switch (_context18.prev = _context18.next) {
          case 0:
            if (state.messagesCallback) {
              _context18.next = 2;
              break;
            }

            return _context18.abrupt("return");

          case 2:
            if (msgObj) {
              _context18.next = 8;
              break;
            }

            _context18.next = 5;
            return getAllMessages(state.channelName, state.paths);

          case 5:
            messages = _context18.sent;
            _context18.next = 9;
            break;

          case 8:
            // get single message
            messages = [getSingleMessage(state.channelName, msgObj, state.paths)];

          case 9:
            useMessages = messages.filter(function (msgObj) {
              return _filterMessage(msgObj, state);
            }).sort(function (msgObjA, msgObjB) {
              return msgObjA.time - msgObjB.time;
            }); // sort by time
            // if no listener or message, so not do anything

            if (!(!useMessages.length || !state.messagesCallback)) {
              _context18.next = 12;
              break;
            }

            return _context18.abrupt("return");

          case 12:
            _context18.next = 14;
            return Promise.all(useMessages.map(function (msgObj) {
              return readMessage(msgObj).then(function (content) {
                return msgObj.content = content;
              });
            }));

          case 14:
            useMessages.forEach(function (msgObj) {
              state.emittedMessagesIds.add(msgObj.token);

              if (state.messagesCallback) {
                // emit to subscribers
                state.messagesCallback(msgObj.content.data);
              }
            });

          case 15:
          case "end":
            return _context18.stop();
        }
      }
    }, _callee18);
  }));
  return _handleMessagePing.apply(this, arguments);
}
693661
function (ws, message) {
  let clientMessage;

  try {
    clientMessage = JSON.parse(message);
    /* jshint ignore:start */
    if (_.get(clientMessage, 'type') === 'message') {
      ws.send(JSON.stringify({
        ok: true,
        reply_to: _.get(clientMessage, 'id'),
        ts: Date.now(),
        message: _.get(clientMessage, 'text', message),
        type: _.get(clientMessage, 'type', 'message'),
        user: _.get(clientMessage, 'user', 'U1234567'),
        channel: _.get(clientMessage, 'channel', 'C1234567'),
      }));
    }
    /* jshint ignore:end */
  } catch (err) {
    logger.info('Invalid socket data ', message);
  }
}
178970
def message(from, to, body, callback_url=nil)
      callback = callback_url ? {:StatusCallback => callback_url} : {}
      Twilio.post("/SMS/Messages", :body => {:From => from, :To => to, :Body => body}.merge(callback))
    end
180279
function generateMessage(type, data)
{
  var message;

  switch (type)
  {
    // default message type, no need to perform special actions, will be sent as is
    case types.MESSAGE:
      message = data;
      break;

    case types.TEXT:
      // `text` must be UTF-8 and has a 320 character limit
      // https://developers.facebook.com/docs/messenger-platform/send-api-reference/text-message
      message = {text: data.substr(0, 320)};
      break;

    case types.AUDIO:
    case types.FILE:
    case types.IMAGE:
    case types.VIDEO:
      message = {attachment: {type: type, payload: {url: data}}};
      break;

    case types.QUICK_REPLIES:
      // `quick_replies` is limited to 10
      // https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies
      message = {text: data.text, quick_replies: data.quick_replies.slice(0, 10)};
      break;

    case types.GENERIC:
      message = templates.generic.call(this, data);
      break;

    case types.BUTTON:
      message = templates.button.call(this, data);
      break;

    case types.RECEIPT:
      message = templates.receipt.call(this, data);
      break;

    default:
      this.logger.error({message: 'Unrecognized message type', type: type, payload: data});
  }

  return message;
}