I have this code:
function graphStreamPublish(){
var params = {};
params['message'] = '';
params['name'] = '';
params['description'] = '';
params['link'] = '';
params['picture'] = '';
params['caption'] = '';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else { }
which works awesome and it posts to my wall or my friend's wall when I change /me/feed to /MY_FRIENDS_ID/feed
But what I want is to post to 25 friends at a time (with one click) by randomly selecting my friends IDs .
Is there any PHP code or anything that can do that? For example accessing and extracting my friends IDs to a some kind of file and then putting them in to the /FRIENDS_ID/feed code?
Sorry for my english. I just started to learn facebook apps yesterday, sorry if I sound too amateur.
I heard there is some php code called 'loop' and it works... Please if anyone can help me. I would appreciate that!
First, you can get all friends IDs using the API. You can then select 25 random indices from that array.
Here is an example of how to do it:
Getting a random value from a JavaScript array
You can then iterate through the (randomly) selected indices, and for each iteration, you can do the FB.api call.
The graphStreamPublish could take one parameter, which is the ID of the person whose wall you want to post to, so it could look something like this:
function graphStreamPublish(targetID) {
var params = {};
params['message'] = '';
params['name'] = '';
params['description'] = '';
params['link'] = '';
params['picture'] = '';
params['caption'] = '';
FB.api('/' + targetID +'/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {});
Also, I'm thinking the params object can also be sent as a parameter.
And finally, here's how this function would look in the mentioned context:
for(i = 0; i < selectedFriendIDs.length; i++)
graphStreamPublish(selectedFriendIDs[i]);
Hope this helps. Have a great day!
Related
I'm trying to edit a script that was intended to send an email if column D is checked (true) but instead of sending an email, I now want it to send a chat. I've created a webhook for the chat group, and it is sort of working, but it's sending a message on EVERY edit made to the sheet.
I'm just a high school teacher way out of my depth here. If anyone can help me figure out how to fix the script, I'd be quite grateful.
When I associate my function with the on edit trigger it sends a chat for every action. If I use the on open trigger, it does nothing.
Screenshot of code
function myFunction() {
var WebWhooklink = "link to my group chat goes here"
var message = { text: "Student has returned"};
var payload = JSON.stringify(message);
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
var response = UrlFetchApp.fetch(WebWhooklink, options ).getContentText();
}
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Electronic Hall Pass" ) { //checks that we're on Sheet1 or not
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks that the cell being edited is in column A
var nextCell = r.offset(0, 1);
if( nextCell.getValue() === '' ) //checks if the adjacent cell is empty or not?
nextCell.setValue(new Date());
}
}
}
function onEdit2(e) {
if(e.value != "TRUE" ) return;
e.source.getActiveSheet().getRange(e.range.rowStart,e.range.columnStart+2).setValue(new Date());
}
You may try something like this that checks if the edit was made in Column D (the fourth column):
function onEdit(e){
if(e.range.getColumn()==4){
--> Put your function here
}
}
Thanks so much Martin! That fixed it!
function sendMailEdit(e){
if (e.range.columnStart != 4 || e.value != "TRUE") return;
let sName = e.source.getActiveSheet().getRange(e.range.rowStart,1).getValue();
var WebWhooklink = "webhook link to chat goes here"
var message = { text: "Student has returned"};
var payload = JSON.stringify(message);
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
var response = UrlFetchApp.fetch(WebWhooklink, options ).getContentText();
}
var totalList_grps = element.all(by.css('p.group-name-text'));
totalList_grps.getText().then(function(text){
console.log('Total list of joined groups : ' + text);
});
Tried the above code for printing list of group names.
Got Output :Total list of joined groups : Party,Innovation,capsLock,Gym,Sunrisers
AW,Big Boss.
Now i need to search for a particular name using if else condition and i tried the second set of code, but its not displaying any output not even a error.
totalList_grps.getText().then(function(itemList) {
expect(itemList).toContain('Big Boss');
});
Here is developers code
1) use by.cssContainingText():
var bigBoss = element(by.cssContainingText('p.group-name-text', 'Big Boss'));
// then you can call click(), getText(), getAttribute('') on found element as following:
bigBoss.click();
2) use elements.filter():
var bigBoss = element.all(by.css('p.group-name-text'))
.filter(function(it){
return it.getText().then(function(txt){
console.log('txt: ' + txt);
return txt === 'Big Boss' || txt.includes('Big Boss');
});
})
.first();
3) use await with combination of if/else
var allNames = element.all(by.css('p.group-name-text'));
var length = await allNames.count();
var matchedIndex = -1;
for(var i=0;i<length;i++) {
var name = await allNames.get(i).getText();
if (name === 'Big Boss' || name.includes('Big Boss')) {
matchedIndex = i;
console.log('matchedIndex = ' + matchedIndex);
break;
}
}
var bigBoss = allNames.get(matchedIndex);
We can implement option 3 without using await, but the code will be not easy readable and more complex than current.
FYI, If you want to use await/async, you need to disable protractor promise management (know as control flow). You can't use both in your code at same time.
The overarching requirement I am trying to implement is to show comments (made on a list, item by item basis).
I added the feature on the authoring side by enabling versioning on the list and adding a text field with the option "Append Changes to Existing Text" set to true.
This indeed allows me to comment on items and displays them chronologically, but on the authoring side only.
The issue is that the UI part will be done on another site collection and I can't find a straightforward way to get all comments there.
So far, every resource I have found points to
<SharePoint:AppendOnlyHistory runat="server" FieldName="YourCommentsFieldName" ControlMode="Display"/>
The thing is, I can't (don't know how to) use this inside a display template.
So far, I am getting all my data using the REST API, via
var siteUrl=_spPageContextInfo.webAbsoluteUrl.replace("publishing","authoring");
$.ajax({
url: siteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
type: 'GET',
async:false,
headers: {"accept": "application/json;odata=verbose",},
dataType: 'JSON',
success: function(json) {
console.log(json);
//var obj = $.parseJSON(JSON.stringify(json.d.results));
//alert(obj);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error :"+XMLHttpRequest.responseText);
}
});
What this gives me is the latest comment only. I need a simple way to get a hold of the entire thread.
I ended up using javascript object model to get them like so:
function GetComments(listname, itemId) {
var siteUrl = _spPageContextInfo.webAbsoluteUrl.replace("publishing", "authoring");
if ($(".comments-history").length) {
$().SPServices({
operation: "GetVersionCollection",
async: false,
webURL: siteUrl,
strlistID: listname,
strlistItemID: itemId,
strFieldName: "Comments",
completefunc: function (xData, Status) {
$(xData.responseText).find("Version").each(function (data, i) {
var xmlComment = $(this)[0].outerHTML;
var arr = xmlComment.split(/comments|modified|editor/g);
var comment = arr[1].trim().substring(2, arr[1].length-2);
var dateSt = Date.parse((arr[2].substring(1, arr[2].length)).replace('/"', ''));
var user = getUsername(arr[3]);
var st = "<div class='comment-item'><div class='comment-user'>" + user + "(" + FormatDate(dateSt) + ")</div>";
st += "<div class='comment-text'>" + comment + "</div></div>";
$(".comments-history").append(st);
});
}
});
}
}
the parsing could be better, but this is just an initial working idea
It worked perfectly fine for a few month, but suddenly stopped recognizing CUSTOM privacy settings. If custom settings allows a list of friends, get a "friends value was not recognized" error, if it denies list of friends, privacy is simply set to "SELF".
$custom = ',"friends": "SOME_FRIENDS","allow": "' + $ids + '"';
var params = {};
params['message'] = $message;
params['name'] = $name;
params['link'] = $url;
params['caption'] = $caption;
params['privacy'] = '{"value":"'+$privacy + '"' + $custom + '}';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert(response.error.message);
} else {
if (response && response.id) {
alert("success");
}
});
Anyone ran into this issue? Any help is appreciated!
I'm looking for a JavaScript solution (or whatever else) that will refresh a webpage ONLY once, after 5 seconds it has been opened. Is this possible without being stuck in a refresh loop?
try this:
setTimeout(function ()
{
if (self.name != '_refreshed_'){
self.name = '_refreshed_';
self.location.reload(true);
} else {
self.name = '';
}
}, 5000);
You could do this in many different ways, but I think the easiest would be to add a query string to the url after the refresh, allowing us to tell if the refresh has already occurred:
//Function to get query string value. Source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
//check if our query string is already set:
if(getQuerystring(r) !== 1){
setTimeout(function(){window.location.href = window.location.href + '?r=1'},5000)
}
If there is the possibility that a query string is already present, you will have to account for that and change the '?' to an '&'.
Sure, if you don't mind using jquery you can do it via an ajax call after waiting 5 seconds. Just throwing you some sample code:
How to wait 5 seconds with jQuery?
$(document).ready(function() {
// Get data
$.ajax({
url : '/tommyStockExchange/Data',
dataType : 'html',
data : {
'format' : 'H',
'type' : 'E'
},
success : function(data) {
$("#executions").html(data);
},
statusCode : {
404 : function() {
alert('executions url 404 :(');
}
}
});
});
Make it redirect to the same page with a different #hash and in JS only register the redirect if the hash isn't set.
You just need to pass some sort of data between page loads. This can be done in a multitude of ways — use a cookie, a URL query parameter, or something on the server side. Query parameter example:
if (!location.search.match(/(\?|&|^)stopRefreshing(=|&|$)/))
{
setTimeout(function ()
{
var search = location.search;
location.search = search ? search + '&stopRefreshing' : 'stopRefreshing';
}, 5000);
}
Demo: http://jsbin.com/ofawuz/edit