I have followed a tutorial and expanded on it to make this twitter bot. It takes the latest 100 tweets from the given twitter account and gives me the dates they were posted when I run the program in terminal. This bit works perfectly.
The 3 lines at the bottom are used to write the data to a spreadsheet although it only gives me one result. I'm wanting to know if there's anything I have done wrong or if there is anything I can add that will give me all the results in the spreadsheet?
This is the code I have written
//API
var Twit = require('twit');
// Getting the API keys from the config file.
var config = require('./config');
var T = new Twit(config);
//getting 5 tweets from the username entered in the top username.
//can get up to 3200 tweets
var params = {
screen_name: 'mascott10',
count: 100
}
T.get('statuses/user_timeline', params, gotData);
//function to be triggered when the data is collected.
function gotData(err, data, response) {
var tweets = data;
for (var i = 0; i < tweets.length; i++) {
console.log(tweets[i].created_at);
var date_posted = tweets[i].created_at.toString();
}
//console.log(data);
//write to file
var fs = require('fs');
fs.writeFile("/Users/mikey/Desktop/node/test.xls", date_posted);
};
This is some of the results in terminal
terminal view of bot result
This is the result in the spreadsheet
spreadsheet result
Your code is over-writing date_posted on each iteration of the for loop. Define your date_posted variable outside of the loop:
var date_posted;
And then inside of the loop concatenate each successive date:
date_posted += tweets[i].created_at.toString();
Related
I made a weighing Machine using an M5 stack. The measured data is being saved in the sheet called, "logsheet" and another sheet (called "chartsheet")to create a gauge chart using that live data. Now, I want to create 60 more weighing machines like this and want to display their live data in a single spreadsheet. Is it possible to create a sheet like this?
This is my Arduino code: (only postvalues funtion)
void postValues(float a){
DynamicJsonDocument doc(capacity);
doc["sensor"] = a;
serializeJson(doc, Serial);
Serial.println("");
serializeJson(doc, buffer, sizeof(buffer));
HTTPClient http;
Serial.println(http.begin(host));
http.addHeader("Content-Type", "application/json");
int status_code = http.POST((uint8_t*)buffer, strlen(buffer));
Serial.printf("status_code=%d\r\n", status_code);
if( status_code == 200 ){
Stream* resp = http.getStreamPtr();
DynamicJsonDocument json_response(255);
deserializeJson(json_response, *resp);
serializeJson(json_response, Serial);
Serial.println("");
}else{
Serial.println(http.getString());
}
http.end();
}
And My appSpript code:
function doPost(e) {
var postjsonString = e.postData.getDataAsString();
var postdata = JSON.parse(postjsonString);
var spreadsheet = SpreadsheetApp.openById("####"); //sheetName
var logSheet = spreadsheet.getSheetByName("logSheet") || spreadsheet.insertSheet("logSheet"); //logsheet
var chartSheet = spreadsheet.getSheetByName("chartSheet") || spreadsheet.insertSheet("chartSheet"); //chartsheet
sensor_data = postdata.sensor;
var date_time = Utilities.formatDate(new Date(), 'JST', 'yyyy年M月d日 H時m分s秒')
var values = [date_time, sensor_data];
logSheet.appendRow(values);
//chart
chartSheet.getRange("A1:B1").setValues([values]);
var max = 25;
var min = 0;
var charts = chartSheet.getCharts();
if (charts.length == 0) {
var chart = chartSheet.newChart().setChartType(Charts.ChartType.GAUGE).addRange(chartSheet.getRange('B1')).setPosition(3, 1, 0, 0).setOption('height', 300).setOption('width', 300).setOption('title', 'Weighing Gauge').setOption('max', max).setOption('min', min).build();
chartSheet.insertChart(chart);
}
}
First things to check
Make sure your web app is deployed to be accessible to "Anyone, even anonymous"
IMPORTANT! Try deploying the web app again with the Old Editor - the New IDE has issues with deployment of web apps and sometimes redeploying it in the old editor fixes things.
Sample web app
function doPost(e) {
let file = SpreadsheetApp.getActive();
let sheet = file.getSheetByName("Sheet1");
let id = e.parameter.id;
let weight1 = e.parameter.weight1;
let weight2 = e.parameter.weight2;
sheet.appendRow([id, weight1, weight2])
}
Then accessing with a simple POST request with CURL from any machine:
curl -d "id=0001&weight1=100&weight2=200" -X POST https://script.google.com/a/egs-sbt095.eu/macros/s/[SCRIPTID]/exec
Produces this:
This example uses cURL just to show that now the spreadsheet can receive data from anywhere. Here is another variation of the same POST request:
curl -X POST "https://script.google.com/a/egs-sbt095.eu/macros/s/[SCRIPTID]/exec?id=0001&weight1=100&weight2=200"
Finally, remember to make sure you are redeploying your web app every time you make changes!
So I've been trying to call this one website for a json of event data and I can't quite figure out how to get the first chunk of data in the json. This is the website https://api.tftech.de/Event/ I'm only trying to pull this data and then make each one of the values into a variable. [{"name": "Spooky Event","start": "2020-07-27T02:35:00-05:00","end": "2020-07-27T03:35:00-05:00","priority": "HIGH","color": "ff9800","intervalInMinutes": 7440}] Can anyone help?
You can use axios to make requests,
Here is the code block with the results put into variables
var axios = require("axios")
axios.get("https://api.tftech.de/Event/").then(data => {
var name = data.data[0].name;
var start = data.data[0].start;
var end = data.data[0].end;
var priority = data.data[0].priority;
var color = data.data[0].color;
var intervalInMinutes = data.data[0].intervalInMinutes;
})
The following is the code I use to get text out of slack and write it into a google sheet.
Actually everything works perfect except the fact that the "Success" message is only seen by the person that uses the command and I couldnt find any way to make it visible to all user in the channel.
So that is also my question: How do I change this? How do I make the "Success" message visible to all users in the channel?
function doPost(e) {
if (typeof e !== 'undefined') {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Doorbug');
var lastRow = sheet.getLastRow();
//relevant data
var parameter = e.parameter;
var text = parameter.text;
var userName = parameter.user_name;
var channel = parameter.channel_name;
var date = new Date();
//reg-number, Email, location, UA
var data = text.split(',');
var reg = data[0];
var email = data[1];
var location = data[2];
var ua = data[3];
var slackDetails = [date, reg, email, location, ua, userName, channel];
//paste the data in the sheet
sheet.getRange(lastRow + 1,1,1,7).setValues([slackDetails]);
}
//return message for the user
return ContentService.createTextOutput('Success :)');
}
I'm guessing this Apps Script project is published as a web application and this function is being used by a Slack slash command. Please update the question providing more context if this assumption isn't correct.
If so, you want to follow their instructions regarding message visibility when sending a response.
In particular, instead of sending a simple plain text response, you want to respond with a JSON-encoded message like this:
var response = "Success :)";
return ContentService.createTextOutput(JSON.stringify({
response_type: "in_channel",
text: response,
}));
Furthermore, you may want to reconsider the logic for crafting your response. As it stands, your function will always respond with "Success :)", even if the initial error checking evaluates to false and the function ends not inserting data into the sheet.
I'm trying to make a .js file that will constantly have the price of bitcoin updated (every five minutes or so). I've tried tons of different ways to web scrape but they always output with either null or nothing. Here is my latest code, any ideas?
var express = require('express');
var path = require('path');
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');
var app = express();
var url = 'https://blockchain.info/charts/';
var port = 9945;
function BTC() {
request(url, function (err, res, body) {
var $ = cheerio.load(body);
var a = $(".market-price");
var b = a.text();
console.log(b);
})
setInterval(BTC, 300000)
}
BTC();
app.listen(port);
console.log('server is running on '+port);
It successfully says what port it's running on, that's not the problem. This example (when outputting) just makes a line break every time the function happens.
UPDATE:
I changed the new code I got from Wartoshika and it stopped working, but im not sure why. Here it is:
function BTCPrice() {
request('https://blockchain.info/de/ticker', (error, response, body) => {
const data = JSON.parse(body);
var value = (parseInt(data.USD.buy, 10) + parseInt(data.USD.sell, 10)) / 2;
return value;
});
};
console.log(BTCPrice());
If I have it console.log directly from inside the function it works, but when I have it console.log the output of the function it outputs undefined. Any ideas?
I would rather use a JSON api to get the current bitcoin value instead of an HTML parser. With the JSON api you get a strait forward result set that is parsable by your browser.
Checkout Exchange Rates API
Url will look like https://blockchain.info/de/ticker
Working script:
const request = require('request');
function BTC() {
// send a request to blockchain
request('https://blockchain.info/de/ticker', (error, response, body) => {
// parse the json answer and get the current bitcoin value
const data = JSON.parse(body);
value = (parseInt(data.THB.buy, 10) + parseInt(data.THB.sell, 10)) / 2;
console.log(value);
});
}
BTC();
Using the value as callback:
const request = require('request');
function BTC() {
return new Promise((resolve) => {
// send a request to blockchain
request('https://blockchain.info/de/ticker', (error, response, body) => {
// parse the json answer and get the current bitcoin value
const data = JSON.parse(body);
value = (parseInt(data.THB.buy, 10) + parseInt(data.THB.sell, 10)) / 2;
resolve(value);
});
});
}
BTC().then(val => console.log(val));
As the other answer stated, you should really use an API. You should also think about what type of price you want to request. If you just want a sort of index price that aggregates prices from multiple exchanges, use something like the CoinGecko API. Also if you need real-time data you need a websocket-based API, not a REST API.
If you need prices for a particular exchange, for example you're building a trading bot for one or more exchanges, you;ll need to communicate with each exchange's websoceket API directly. For that I would recommend something like the Coygo API, a node.js package that connects you directly to each exchange's real-time data feeds. You want something that doesn't add a middleman since that would add latency to your data.
I'm just beginning my JS journey. Currently trying to update a MailChimp API call within Google Sheets Script. The issue is that the script (originally found here:https://medium.hackinrio.com/mailchimp-reports-in-google-sheets-88496a153ee2 1) only works when you SAVE the Google Scripts editor. I would like to create a JavaScript GAS function that is able to run every day that saves the Script Editor thereby updating the MailChimp count. Or some other solution that would allow this to work.
Google Scripts Function:
function getSubscribersCount(api_key, list_id) {
var API_KEY = api_key;
var LIST_ID = list_id;
var dc = '(my mailchimp API Key goes here)'.split('-')[1];
var api = 'https://'+ dc +'.api.mailchimp.com/2.0';
var membersPath = '/lists/members.json';
// MC api-specific parameters
var payload = {
"apikey": API_KEY,
"id": LIST_ID
};
// GAS specific parameters:
var params = {
"method": "POST",
"muteHttpExceptions": true,
"payload": payload
};
var apiCall = function(endpoint){
var apiResponse = UrlFetchApp.fetch(api+endpoint, params);
var json = JSON.parse(apiResponse);
return json;
};
var members = apiCall(membersPath);
return members.total;
}
Is there a function I can add that will enable me to save the function, or perhaps emulate a CMD + s keyboard event?
Instead of writing a formula into your spreadsheet to invoking your script you should write another function that modifies the spreadsheet directly.
function updateSubscriberCount() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
sheet = ss.getSheetByName("Sheet1"),
api_key = sheet.getRange("B1").getValue(),
list_id = sheet.getRange("C1").getValue();
sheet.getRange("A1").setValue(getSubscribersCount(api_key, list_id));
}
Then you click on "edit/current project's triggers" and set up a timer to run that function at regular intervals.
However you have to run that function manually at least once to grant the script the permissions it needs.