I am new to Ionic, I had written the code but i am not able to read the sms that had received on my phone.with in the sms plugin i am not able to read the string.Is there any errors in my code:
Below is my code :
getSMS(){
var filter = {
box : 'inbox', // 'inbox' (default), 'sent', 'draft', 'outbox', 'failed', 'queued', and '' for all
// following 4 filters should NOT be used together, they are OR relationship
// read : 0, // 0 for unread SMS, 1 for SMS already read
// _id : 1234, // specify the msg id
address : 'IM-WAYSMS', // sender's phone number
// body : 'This is a test SMS', // content to match
// following 2 filters can be used to list page up/down
indexFrom : 0, // start from index 0
maxCount : 10, // count of SMS to return each time
};
this.logger.debug("getSms");
if(window.SMS) window.SMS.listSMS(filter, (data)=>{
//Filterd Data
this.logger.debug("checking the filter data " +JSON.stringify(data));
this.text=data[0].body;
this.logger.debug("checking the text " + this.text);
**this.otpNumber = this.text.substring(Number(this.text.indexOf("'"))+Number(1), Number(this.text.lastIndexOf("'")))**
this.logger.debug("checking the otpNumber "+this.otpNumber);
if(this.otpNumber){
//this.logger.post('')
// .subscribe(this.otpNumber,this.loginId, (result,data,id)=>{
//this is post call for validate Otp
let OtpObj={
loginId: this.mobile,
otp:this.otpNumber
}
this.logger.debug("checking the otpNumber "+this.otpNumber);
this.rest.post('/validateOTP' ,OtpObj)
.subscribe( (result)=>{
this.logger.debug("checking data of success " +JSON.stringify(result));
if(result == '1') {
this.access_token = result.access_token;
this.firstDiv=false;
this.secondDiv = true;
this.logger.debug("checking access tocken "+ this.access_token);
alert("otp success");
}
else{
this.logger.error("error of otp"+data);
}
});
}
else{
this.logger.info("no otpnumber");
}
// return _this.otpNumber;
}, (err)=>{
this.logger.debug("checking the err "+JSON.stringify(err));
});
}
Related
I'm coding a whitelist system for my discord bot that, on ready event (and after a 3 seconds delay), checks if every server it is in has it's ID added to the whitelist database on MongoDB. If not, the bot sends an embed and leaves the server. I managed to get it working on the guildCreate event, but on ready event it performs the message and leave actions on every single server without filtering conditions, even though those are added to the list. I cannot figure out why. Also, I'm still new to JavaScript, so it could be just a minor mistake.
//VARIABLES
const { Client, MessageEmbed } = require("discord.js")
const config = require('../../Files/Configuration/config.json');
const DB = require("../../Schemas/WhitelistDB");
//READY EVENT
module.exports = {
name: "ready",
once: false,
async execute(client) {
//[ ... ] <--- OTHER UNNECESSARY CODE IN BETWEEN
setTimeout(function() { // <--- 3 SECONDS DELAY
client.guilds.cache.forEach(async (guild) => { // <--- CHECK EVERY SERVER
await DB.find({}).then(whitelistServers => { // <--- CHECK MONGODB ID LIST
if(!whitelistServers.includes(guild.id)) {
const channel = guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').random(1)[0]; // <--- SEND MESSAGE TO RANDOM TEXT CHANNEL (It is sending to every server, when it should be sending only to the not whitelisted ones)
if(channel) {
const WhitelistEmbed = new MessageEmbed()
WhitelistEmbed.setColor(config.colors.RED)
WhitelistEmbed.setDescription(`${config.symbols.ERROR} ${config.messages.SERVER_NOT_WHITELISTED}`)
channel.send({embeds: [WhitelistEmbed]});
}
client.guilds.cache.get(guild.id).leave(); // <--- LEAVE SERVER (It is leaving every server, when it should be leaving only the not whitelisted ones)
} else { return }
});
});
}, 1000 * 3);
}
}
I found the solution myself!
Instead of finding the array of whitelisted ID's for each guild, find one at a time and instead of checking the content of the array, check if the array exists. This is the updated code:
//WHITELIST
setTimeout(function() {
client.guilds.cache.forEach(async (guild) => {
await DB.findOne({ GuildID: guild.id }).then(whitelistServers => {
if(!whitelistServers) {
const channel = guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').random(1)[0];
if(channel) {
const WhitelistEmbed = new MessageEmbed()
WhitelistEmbed.setColor(config.colors.RED)
WhitelistEmbed.setDescription(`${config.symbols.ERROR} ${config.messages.SERVER_NOT_WHITELISTED}`)
channel.send({embeds: [WhitelistEmbed]});
}
client.guilds.cache.get(guild.id).leave();
} else { return }
});
});
}, 1000 * 3);
I got this form from one of the free templates. Basic form.
Where I should input the email address to send the form to ?
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake
animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd
oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
If I'm not mistaken, JavaScript doesn't actually send the email. You're posting the user's Name, Email, and message to a PHP form, which will then do the work of sending the email. So you should have a place in the PHP form to input the email that will then receive the messages.
You link in your AJAX POST to url: php/form-process.php
How can I receive an attachment in form of an image through the Facebook Messenger API?
Their documentation only provides instructions on how to receive text-based messages.
I am not sure what language you are using to code your bot but since you are referring to the facebook documents where most of the messenger code snippets are in node.js
Here's something for you to try, let me know if this helps.
app.post('/webhook/', function (req, res) {
//Getting the mesagess
var messaging_events = req.body.entry[0].messaging;
//Looping through all the messaging events
for (var i = 0; i < messaging_events.length; i++) {
var event = req.body.entry[0].messaging[i];
//Checking for attachments
if (event.message.attachments) {
//Checking if there are any image attachments
if(atts[0].type === "image"){
var imageURL = atts[0].payload.url;
console.log(imageURL);
}
}
}
}
In February 2017 I came across the same issue and struggled to get this up and running for a very long time. Turns out that the message.attachments comes in as object, where the actual attachment is within the object.
The structure goes like this:
Attachments Object > JSON Response >Type & Payload > URL
app.post('/webhook/', function(req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
// Check if it's a message
if (event.message) {
//Create the attachment
let attachment = event.message.attachments
// Here we access the JSON as object
let object1 = attachment[0];
//Here we access the payload property
let payload = object1.payload;
// Finally we access the URL
let url = payload.url;
console.log(url)
}
else if (event.message && event.message.text) {
// Here you can handle the text
console.log("Just Text")
}
}
res.sendStatus(200)
})
The more compact version without explanations looks like this:
if (event.message) {
let attachment = event.message.attachments
console.log(attachment[0].payload.url)
}
As added bonus, you could also check if the type is an Image. You can achieve that by adding doing this adjustment:
if (event.message && ) {
let attachment = event.message.attachments[0]
if (attachment.type === "image") {
console.log(attachment.payload.url)
}
}
Hope this helps,
Julian
While in PYTHON to receive and save an image attachment in your facebook chatbot works:
#app.route('/', methods=['POST'])
def webhook(): # endpoint for processing incoming messaging events
data = request.get_json()
if data["object"] == "page":
for entry in data["entry"]:
for messaging_event in entry["messaging"]:
if messaging_event["message"].get("attachments"):
attachment_link = messaging_event["message"]["attachments"][0]["payload"]["url"]
print("Image received, boss!")
print(attachment_link)
good chatbot-thing!
Marco
In PHP,
When user sents it to bot, below response we get which contains attachement type and url
{
"object": "page",
"entry": [
{
"id": "000000000000000",
"time": 1511956708068,
"messaging": [
{
"sender": {
"id": "000000000000000"
},
"recipient": {
"id": "000000000000000"
},
"timestamp": 1511956707862,
"message": {
"mid": "mid.$xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"seq": 42172,
"sticker_id": 369239263222822,
"attachments": [
{
"type": "image",
"payload": {
"url": "https:\/\/scontent.xx.fbcdn.net\/v\/t39.1997-6\/851557_369239266556155_759568595_n.png?_nc_ad=z-m&_nc_cid=0&oh=9058fb52f628d0a6ab92f85ea310db0a&oe=5A9DAADC",
"sticker_id": 369239263222822
}
}
]
}
}
]
}
]
}
This is how you get different type of messages from user
//get the response from user
$input = json_decode(file_get_contents('php://input'), true);
//first check if attachment is present
$attachment = array_key_exists('attachments', $input['entry'][0]['messaging'][0]['message']);
//get the attachement type and url
$type = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['type'];
$file_url = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['payload']['url'];
Hope this helps you
https://developers.facebook.com/docs/messenger-platform/implementation#receive_message
Check this link out.
It says that,
"Messages may have an image, video or audio attachment."
UPDATE:
The above link is broken as Facebook recently updated their documentations in a weirdly downgraded version with many contents missing.
To elaborate as pointed out in the comment, when a user sends a request, your server will receive such a json:
{
"mid": "some mid",
"seq": 26,
"attachments": [{
"type": "image",
"payload": {
"url": "some image url"
}
}]
}
and you can maybe create a download function to download the image to your server.
To use this data, as mentioned above, you can use the webhook.
app.post('/webhook', function (req, res) {
var data = req.body;
// Make sure this is a page subscription
if (data.object == 'page') {
console.log(data.entry);
// Iterate over each entry
// There may be multiple if batched
data.entry.forEach(function(pageEntry) {
var pageID = pageEntry.id;
var timeOfEvent = pageEntry.time;
// Iterate over each messaging event
pageEntry.messaging.forEach(function(messagingEvent) {
receivedMessage(messagingEvent);
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know you've
// successfully received the callback. Otherwise, the request will time out.
res.sendStatus(200);
}
});
function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
if (senderID == PAGE_ID) {
console.error("Sender is self.");
return;
}
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
// You may get a text or attachment but not both
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
// If we receive a text message, check to see if it matches any special
// keywords and send back the corresponding example. Otherwise, just echo
// the text we received.
} else if (messageAttachments) {
messageAttachments.forEach(function(messageAttachment) {
var attachmentUrl = messageAttachment.payload.url;
console.log("Received Attachment");
download(attachmentUrl);
}
}
This code was taken from the sample code of Facebook.
Trying to get some messages from a db collection, I've tried that code (server side):
MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
if(err) throw err;
var history="";
var collection = db.collection('gt-chat');
console.log("******************************Printing docs from Cursor Each")
collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
console.log(doc)
if(doc != null) {
console.log("Doc from Each ");
history=history+console.dir(doc)+"\r\n";
console.dir(doc);
}
});
console.log("/////////////HISTORY//////////////////");
console.log(history); ; // data is shown there under the shell console, all is fine !
socket.emit('updatechat', 'SERVER', history); // should send the messages using socket
});
and then on the client side, I've tried :
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
date = new Date;
h = date.getHours();
if (h<10) {
h = "0"+h;
}
m = date.getMinutes();
if (m<10) {
m = "0"+m;
}
s = date.getSeconds();
if (s<10) {
s = "0"+s;
}
var time = h+":"+m+":"+s;
$('#conversation').append('<b><strong>' + time + '</strong> '+username + ':</b> ' + data + '<br>');
});
which doesn't show anything as expected :(
I am quite sure about the updatechat function because I can get message with it, as I've tried:
socket.emit('updatechat', 'SERVER',"this is history"); // < message is well sent, so no problem there!
but I don't get the all history.
So the goal is to get some messages from a mongodb collection and to display them under the browser using socket emit
Under the shell, to debug, it's showing:
Doc from Each { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' } { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' }
So, data and messages exist, but I can't read them from the browser. The shell says: 'history is not defined' ! What is wrong with concatenation? And my variable declaration? I don't understand, thanks for your help!
NOTE: Could somebody give me an example SAS string (with the block info appended in the right area) that needs to be sent to the Azure blob storage? I think that's the issue that I'm having. I need to figure out the order of the uri, key, etc. in the string that is sent to Azure with each block.
What I'm trying to accomplish is to grab a SAS key from a service, modify the string key so that azure knows that I'm sending in blocks, and then send the individual blocks of the file with the sas key from the web client. I'm chunking each file into 2MB blocks and sending those 2MB blocks with a JavaScript library at a time. So each "file" in the code below is just a 2MB chunk of a file.
THE PROBLEM: I can successfully grab the SAS key from the service, modify the key so that it has the block chunk info in it, send in the FIRST chunk, and then receive a response back from the blob storage server. When I send in the second chunk, however, the request for a stream to the blob storage hangs and then eventually times out. The time-out seems to happen specifically on the second request for a stream to the blob storage. This bit of code right here:
SERVER WEB CLIENT CODE:
using (Stream requestStream = request.GetRequestStream())
{
inputStream.CopyTo(requestStream, file.ContentLength);
}
What could be causing the second chunk to time out? Could it be that the window for the key closes too soon? Below is my code and some screenshots:
private void WriteToBlob(HttpPostedFileBase file, string BlockId, FileProp fp)
{
var inputStream = file.InputStream;
Microsoft.WindowsAzure.StorageCredentialsSharedAccessSignature credentials =
new Microsoft.WindowsAzure.StorageCredentialsSharedAccessSignature(fp.facct);
string queryString = (new Uri(fp.folderName)).Query;
string RequestUri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}{2}&comp=block&blockid={3}",
fp.folderName, fp.fileName, queryString, Convert.ToBase64String(Encoding.UTF8.GetBytes(BlockId)));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RequestUri);
request.Method = "PUT";
request.ContentLength = inputStream.Length;
using (Stream requestStream = request.GetRequestStream())
{
inputStream.CopyTo(requestStream, file.ContentLength);
}
}
JAVASCRIPT CODE SENDING THE CHUNKS TO THE WEB SERVER CLIENT:
var running = 0;
var chunksize = (Modernizr.blobconstructor) ? uploadChunkSize : null; //if browser support Blob API
window.xhrPool = [];
$('#fileupload').fileupload({
url: url,
//formData: [{ name: 'param1', value: 1 }, { name: 'param2', value: 2}],
singleFileUploads: true, //each file is using an individual XHR request
//limitMultiFileUploads: 2, //This option is ignored, if singleFileUploads is set to true.
multipart: true,
maxChunkSize: chunksize, //server side is in streaming mode
sequentialUploads: true, //Set this option to true to issue all file upload requests in a sequential order instead of simultaneous requests.
dataType: 'json',
autoUpload: true,
//acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
progressInterval: 100,
bitrateInterval: 100,
maxFileSize: uploadFileSizeLimit
}).on('fileuploadadd', function (e, data) {
var filename = data.files[0].name;
var filesize = data.files[0].size;
if (filesize == 0) {
var zeroSizeErrMsg = sceneLayoutService.format('This file {filename} is empty please select files again without it. ', { filename: filename });
sceneLayoutService.showErrorDialog(zeroSizeErrMsg);
return;
}
if (window.availableStorageSize != null && window.availableStorageSize != '') {
if (filesize > window.availableStorageSize) {
var overSizeErrMsg = sceneLayoutService.format('File size of {filename} exceeds available storage space in your cloud drive. ', { filename: filename });
sceneLayoutService.showErrorDialog(overSizeErrMsg);
return;
}
} else {
alert('Unable to retrieve the storage usage.');
}
data.jqXHR = data.submit();
window.xhrPool.push(data.jqXHR);
sceneLayoutService.addFileToProgressDialog(data, cancelButton);
}).on('fileuploadprocessalways', function (e, data) {
}).on('fileuploadprogressall', function (e, data) {
}).on('fileuploadsubmit', function (e, data) {
var filesize = data.files[0].size;
if (filesize == 0) {
return false;
}
if (window.availableStorageSize != null && window.availableStorageSize != '') {
if (filesize > window.availableStorageSize) {
return false;
}
}
$('#dlgProgress').parent().show();
running++;
sceneLayoutService.showProgressDialog('Uploading files to ' + currentUser + '\'s Cloud Storage ...', abortAllUploads);
return true;
}).on('fileuploaddone', function (e, data) {
running--;
updateStorageQuota(function () {
var usedStorageSize = (window.usedStorageSize != null) ? bytesToSize(window.usedStorageSize, 2) : 0;
var totalStorageSize = (window.totalStorageSize != null) ? bytesToSize(window.totalStorageSize, 2) : 0;
var usageFooterStr = sceneLayoutService.format("Using {used} of {total} (%)", { used: usedStorageSize, total: totalStorageSize });
$('div.dlgProgressFooter').text(usageFooterStr);
});
var docGridUrl = window.baseUrl + '/CloudStorage/ChangePage?page=1&rand=' + sceneLayoutService.getRandomString(4);
$('#docGridPartial').load(docGridUrl, function () {
grid.init({
pageNumber: 1,
url: window.baseUrl + '/CloudStorage/ChangePage',
sortColumn: '',
sortDirection: ''
});
});
sceneLayoutService.updateFileUploadFinalStatus(data, 'done');
if (!data.result.success) {
debugger;
var errMsg = "";
if (data.result != null) {
if (data.result.message != null) {
errMsg += data.result.message;
}
if (data.result.error != null)
errMsg += data.result.error;
}
sceneLayoutService.showErrorDialog(errMsg);
}
window.removeXHRfromPool(data);
if (running == 0) {
$('#dlgProgress').parent().hide();
$('#progresses').empty();
}
}).on('fileuploadfail', function (e, data) {
running--;
sceneLayoutService.updateFileUploadFinalStatus(data, 'fail');
window.removeXHRfromPool(data);
if (running == 0) {
$('#dlgProgress').parent().hide();
$('#progresses').empty();
}
}).on('fileuploadprogress', function (e, data) {
//XHR upload onProgress event not fired at server-defined intervals/not supported in IE8 and IE9,
//will be supported in IE10 in terms of XMLHttpRequest Level 2 specification, http://caniuse.com/xhr2
sceneLayoutService.updateFileUploadProgress(data);
});
Issue resolved. It turns out the format of the SAS URI was incorrect. Here is how a Sas URI (for a container, in my case) should look:
http://container_uri/filename?key