Looping reply when developer twitter bot in Nodejs - javascript

I'm working on a project where I have a twitter bot that reply every tweets in its acount.
Here's my code:
var replybot = function() {
//The word that we are going to search in tweets
var word = 'hello';
//Variables to store the twitter user id and screen name to make a reply
var id_str, screen_name;
console.log('Bot started looking for the word ' + word + '.');
stream.on('tweet', tweetEvent );
function tweetEvent(tweet) {
var info_text = tweet.text;
if (info_text.indexOf(word) > -1) {
console.log(tweet.text); //Displays the tweet with the word
//We store the twitter id and the user screen name to make a reply
id_str = tweet.id_str;
screen_name = tweet.user.screen_name;
console.log('need do it once');
//Now we are going to reply the tweet
Twitter.post('statuses/update', {in_reply_to_status_id: id_str,
status: '#' + screen_name + ' I think you mean "goodbye"'},
function(error, tweet, response){
if(error) {
console.log(' Error');
}
else{
console.log('. Success!!!');
} // Tweet body
});
}
}
console.log('done');
}
replybot();
// 'reply' a tweet in every 25 minutes
setInterval(replybot, 1500000);
Im following this repo to work: https://github.com/ttezel/twit .
But i had an issue : when i run this code above, the bot reply so many time on one tweet, and i dont know why.
Although i've set interval for this function.
Im new with node and any help would be great ! Thanks

Oh so sorry i got a loop forever in here :
function(error, tweet, response)
it shouldn't be tweet arg

Related

How to add the value from an input box to an array and then output its contents?

How can I go about adding the value of an input box into an array and then display the contents of that array?
This is what I've come up with and I'm not sure why it's not working - the console.log doesn't post anything to the console, either.
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(user);
return false;
console.log(items);
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
The rest of the code in the file is below, just in case it helps... (changed the return statement, as per the first answer)
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(users);
console.log(items);
return false;
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
//Counts the number of users online
socket.on('count', function (data) {
$('.user-count').html(data);
});
//Receives messages and outputs it to the chat section
socket.on('message', function (data) {
$('.chat').append('<p><strong>' + data.user + '</strong>: ' + data.message + '</p>');
$('.chat').scrollTop($('.chat').height());
});
//SENDING OF THE MESSAGE
//Submit the form through HTTPS
$('form').submit(function (e) {
e.preventDefault();
// Retrieve the message from the user
var message = $(e.target).find('input').val();
// Send the message to the server
socket.emit('message', {
user: user || 'Anonymous',
message: message
});
// Clears the message box after the message has been sent
e.target.reset();
$(e.target).find('input').focus();
});
Answer
Your implementation is fine, but you have a bug which is preventing it from working as you've described.
The call to console.log(items) does not print anything, because that line of code never runs.
When you return from a function, the subsequent lines of code will not be ran. You should return as the last line within your function, or wrap it in a conditional.
For example:
function userArray() {
items.push(user);
console.log(items);
return false;
}
How to debug
Learning the techniques to figure this issue out yourself is an invaluable tool. You can leverage a debugger, such as the Chrome Devtools, to add breakpoints to your code. These will allow you to stop execution on a particular line, view the value of variables, and step through the remaining lines of code.
Doing so would make it clearly visible that the line of code is never running.
Find more details here: https://developers.google.com/web/tools/chrome-devtools/javascript

Websocket message to Specific Room - Golang Kataras/Iris

I am trying to send Message to Particular Room, but it doesn't work and It sends message to all room along with my message being received twice from my name and with first chat room user name. Message from 1 Room is broadcasted to all Chat Room.
I have used Example Code from here- https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go. and
https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go
Below is the Code, I am using, that is giving me the error :
var myChatRoom = strconv.Itoa(room.ID)
ws := websocket.New(websocket.Config{})
ws.OnConnection(func(c websocket.Connection) {
c.Join(myChatRoom)
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Joined Chat!"))
c.OnMessage(func(data []byte) {
message := string(data)
if message == "leave" {
c.Leave(myChatRoom)
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Left Chat!"))
return
}
c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + ": " + message))
})
c.OnDisconnect(func() {
fmt.Printf("Connection with ID: %s has been disconnected!\n", c.ID())
})
})
HTML Code:
<div id="messages" style="border-width: 1px; border-style: solid; height: 200px;overflow:auto"></div>
<input type="text" id="messageTxt" />
<button type="button" id="sendBtn">Send</button>
Javascript Code:
<script>
var messageTxt;
var messages;
var HOST = 'localhost'
jQuery(function() {
messageTxt = jQuery("#messageTxt");
messages = jQuery("#messages");
w = new WebSocket("ws://" + HOST + "/my_endpoint");
w.onopen = function() {
console.log("Websocket connection enstablished");
};
w.onclose = function() {
appendMessage(jQuery("<div><center><h3>Disconnected</h3></center></div>"));
};
w.onmessage = function(message) {
console.log("Message Appended: " + message)
appendMessage(jQuery("<div>" + message.data + "</div>"));
};
jQuery("#sendBtn").click(function() {
w.send(messageTxt.val().toString());
messageTxt.val("");
});
})
function appendMessage(messageDiv) {
messageDiv.appendTo(jQuery("#messages"));
}
</script>
Error:
It sends message to all ROOM and not specific Room.
User who created room first automatically joins all the ROOM
People sending message in other ROOM see their message being Repeated/cloned in their ROOM by "FirstUser" who created first room in chat. (Irrespective of whether he is member of the chat group or not)
Expecting:
People can send/receive message to only those room where they have joined.
First User should not be able to join CHATRoom automatically.
People should not see their message being repeated again with "FirstUser" name.
It was a tiny bug, fixed just moments ago. Please upgrade with:
go get -u github.com/kataras/iris
A new release "v10.6.3" was also pushed.
Thank you a lot #Belarus, you're great!
Sincerely,
Gerasimos Maropoulos,
Author of the Iris web framework.

Edit Reply Message (comment) to a Discussion - SharePoint Online JavaScript

I need to do this in JavaScript since the entire solution is current in JavaScript and this is the last part.
I need to be able to update a reply message (comment) to an existing discussion. I am able to change the discussion fields but not the message fields. I know the message and the discussion are two different content types and that the reply messages are under a folder for the discussion but I don't know how to edit the reply message. (There is a utility to add the reply message but not to edit it).
This is a sample of the discussion (in the list) in which you can see there are 5 replies, I want to change the body text of one of the replies via JavaScript.
Image of the Discussion Showing Replies I would like to update
And for example, I want to change the message below:
Image of Replies that I want to change the body text
I have tried to update using this code, but it only changes the discussion and not the message.
I have a feeling I need to tell the system to go into that folder to find the message and change its body text, but I am not sure how to do this and after a 2 day search on the interwebs, I can't find an answer.
Code that does not work:
function aeditListItem() {
var clientContext = new SP.ClientContext();
var oList = clientContext.get_web().get_lists().getById('40b2fbd4-4f87-d92fb05f8044'); //ID changed to protect client
this.oListItem = oList.getItemById(getParameterByName('commentid'));
oListItem.set_item('Body', document.getElementById("ideaDetails").value.replace(/\r?\n/g, '<br />'));
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded() {
alert('Item Updated: ' + oListItem.get_id());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
Many Many THANKS!
Apparently at the line:
this.oListItem = oList.getItemById(getParameterByName('commentid'));
getParameterByName('commentid') does not return the proper message id, make sure the message list item id is specified.
As a proof of concept the following example shows how to:
find a message by body
replace the message with a new body
Example
var listTitle = "Discussions";
var oldMessageBody = "";
var newMessageBody = "";
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var items = list.getItems(createMessageFindQuery('Body',oldMessageBody));
ctx.load(items);
ctx.executeQueryAsync(
function(){
if(items.get_count() == 1){
var foundItem = items.getItemAtIndex(0);
foundItem.set_item('Body',newMessageBody);
foundItem.update();
ctx.executeQueryAsync(
function(){
console.log("Updated");
},
function(sender,args){
console.log(args.get_message());
});
}
else
console.log('Not found or multiple items are found')
},
function(sender,args){
console.log(args.get_message());
});
});
function createMessageFindQuery(fieldName,fieldVal){
var qry = new SP.CamlQuery;
qry.set_viewXml(String.format('<View Scope="RecursiveAll"><Query><Where><Contains><FieldRef Name="{0}" /><Value Type="Text">{1}</Value></Contains></Where></Query></View>',fieldName,fieldVal));
return qry;
}

CasperJS; opening dynamic url

I am using casperJS to got ta a page and collect an id from the URL, this is what my start function is doing. I would then like to put the id in to a new url and go there.
This works for the user var, this is coming in from the terminal. However sid is undefined and not the value I updated it to.
Any help would be appreciated. I am wondering if I found a limitation with casperJS. please not that this is not the full code (as that is much longer), if you message me I can provide you the whole script.
var user = decodeURIComponent(casper.cli.get(0).replace(/\+/g, ' '))
var sid
casper.start('https://editor.storify.com/', function() {
sid = this.getCurrentUrl()
sid = sid.split('/')[3]
})
casper.thenOpen('https://storify.com/' + sid, function() {
console.log('lets view the posts')
console.log(token)
console.log(sid)
if (dev)
this.capture('storeheading.png')
})
you can solve this problem by warping the thenOpen inside of a then
casper.then(function() {
casper.thenOpen('https://storify.com/' + sid, function() {
console.log('lets view the posts')
console.log(token)
console.log(sid)
if (dev)
this.capture('storeheading.png')
})
})

Notification not displaying supplied image

I'm trying to show a notification using an image I receive over a socket as an arrayBuffer. The notification shows, but without the image supplied. The standard firefox logo/icon is used instead. Any help would be appreciated. The code seems to run without any errors, or rather, no errors are are thrown/stack trace printed when the notification is created.
Here is the code to create the notification:
ps_worker.port.on("notification", function(notification){
//DISPLAY LINK TO USER
var arrayBuffer_icon = notification.icon;
var arrayBuffer_largeicon = notification.largeicon;
var str = String.fromCharCode.apply(null,arrayBuffer_icon);
var base64String = utils.btoa(str).replace(/.{76}(?=.)/g,'$&\n');
var dataUri = "data:image/png;base64,"+ base64String;
notifications.notify({
title: notification.app + ": " + notification.title,
text: notification["subject"] + "\n" + notification.content,
data: "did gyre and gimble in the wabe", // data is a string passed through to the on click listener
iconURL: dataUri,
onClick: function (data) {
console.log(data);
}
});
});
the utils.btoa call is implemented as described here: https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/Unit_testing
The relevant server code is (node.js):
function send_notification_to_socket(user, notification, target){
fs.readFile(notification.iconpath, function(err, buf){
if(socketstore.get_socket_by_id(user)){
socket = socketstore.get_socket_by_id(user);
notification["icon"] = buf;
socket.emit('notification', notification);
}else{
console.log("No socket for user " + user);
}
});
}
Any ideas on what I might be doing wrong?

Categories

Resources