twitter api - nodejs problems - javascript

i am fairly new to NodeJS and the twitter api and I encountered some problems. Disclaimer: Because the terms of usage for the twitter api are strict i want to make clear that i am not going to profit anything off this project and i am not going to harm anyone's privacy using it.
So i have this html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="bot.css" type="text/css">
<title>document</title>
</head>
<body>
<div class="main">
<h1></h1>
</div>
<script src="bot.js"></script>
<script src="config.js"></script>
</body>
</html>
config.js :
module.exports = {
consumer_key: '',
consumer_secret: '',
access_token: '',
access_token_secret: '',
timeout_ms: 60*1000, // optional HTTP request timeout to apply to all requests.
strictSSL: true, // optional - requires SSL certificates to be valid.
}
and the bot.js :
var Twit=require('twit');
var config=require('./config');
var T = new Twit(config);
let params = {
q: 'polar-bear since:2011-07-11',
count: 2
}
function getData(err, data, response){
for(let i=0;i<data.statuses.length;i++){
console.log(`Tweet number ${i+1} : ${data.statuses[i].text}`);
}
}
T.get('search/tweets', params, getData)
let page=document.querySelector('h1');
when i run only the bot.js file in terminal it works fine however
when i run the code on the web console i get 2 Reference
ReferenceError: Can't find variable: require ...
ReferenceError: Can't find variable: module

Related

Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function

Uncaught (in promise) TypeError: window.showOpenFilePicker() is not a function
I am trying to experiment with reading and writing in File System Web API but I keep getting TypeError Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function, I have no idea what is going.
Here is react code snippet:
const FileReader = () => {
const openThisFile = async () => {
const [fileHandle] = await window.showOpenFilePicker(); // error: Property 'showOpenFilePicker' does not exist on type 'Window & typeof globalThis'
console.log(fileHandle);
};
return (
<div>
<button onClick={openThisFile}>Open file</button>
</div>
);
};
export default FileReader;
And so I thought it's not working in react and then I tried Vanilla Javascript but still I keep getting TypeError Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function in the console. Here is the code snippet.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Open file</title>
</head>
<body>
<button onclick="getFile()">Open file</button>
<script>
const pickerOpts = {
types: [
{
description: "Images",
accept: {
"image/*": [".png", ".gif", ".jpeg", ".jpg"],
},
},
],
excludeAcceptAllOption: true,
multiple: false,
};
let fileHandle;
async function getFile() {
[fileHandle] = await window.showOpenFilePicker(pickerOpts);
// run code with our fileHandle
}
console.log(fileHandle);
</script>
</body>
</html>
Any idea on what I am doing wrong?
I suppose you are seeing the issue above because of the following:
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Consider looking into the docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/showOpenFilePicker

Picking random image from array 60+ choices javascript

I understand this question has tons of answers already, but I am trying to figure out how to do this in the most efficient way. I have a website that sends an image with a button click to a phone number, but I want to choose between 60 or so photos and manually entering all of these image locations into an array does not seem ideal.
Here is my js file that performs the email action, this is all hosted on a free hosting service.
// server.js
const express = require("express")
const app = express()
app.use(express.static("public"))
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
/* this sends the "index.html" file when people go to app.glitch.me/ */
})
app.get("/send", (req, res) => {
// where node app starts
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.USER,
pass: process.env.PASS,
}
});
var mailOptions = {
from: process.env.USER,
to: process.env.RECIP,
subject: "As you requested",
text: '',
attachments: [
{
/*image location*/
path: 'https://post.healthline.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg',
}
]
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.redirect("/sent.html") // after sending the email, redirect back to "index.html" at app.glitch.me/
})
app.listen(3000); //open for traffic
Here is my HTMl if its even relevant to my question
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- import the webpage's stylesheet -->
<link rel="stylesheet" href="/style_index.css">
click me for snazzy pics<!-- script to ping --!>
<!-- import the webpage's javascript file -->
<script src="/script.js" defer></script>
</head>
<body>
<h1>hello</h1>
<p>
I made this.
</p>
</body>
</html>
Try first logging all of your images from where they are hosted. If it is not a database you can call upon then you may need to create an array of them manually. Once they are in an object, you can simply use a variable to determine which position in the array that image link should come from. I hope the below helps.
For example:
imageChoices = ["https://post.healthline.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg", "https://post.healthline.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg", etc.]
randomIndexChooser = Math.floor(Math.random() * 60) + 1;
var mailOptions = {
from: process.env.USER,
to: process.env.RECIP,
subject: "As you requested",
text: '',
attachments: [
{
/*image location*/
path: imageChoices[randomIndexChooser],
}
]
};
you need to make an ajax service that calls an api, the api loops through all the files that are in the specified folder and returns the list of file paths. after you get the list from the api, you append them to the wanted array in your javascript code.
I will provide you a sample in asp.net c# , you may be working on another framework, but you can benefit from the idea at least.
here is a function in an api
[HttpGet]
public List<string> GetImageFilesPaths()
{
//getfiles returns all found files' paths in a specified directory
List<string> imageFilePaths = Directory.GetFiles("folderpath", "*.png", SearchOption.AllDirectories).ToList();
}
ajax service that calls the API
$.ajax({
url:'hostname/apiname/GetImageFilesPaths'
contentType: "application/json",
dataType: 'json',
success: function(result){
//here you append the result which is the list of file path
//into your wanted array, you can also loop
result.forEach((imagePath)=>{
arrayOfImages.push(imagePath)
})
}
})

How do I display real-time firebase data on my website?

I am trying to post the data from a moisture sensor on a website. I am using Arduino to update and send the data to a Real-Time Firebase database. From there I am using Glitch.com for my website. I am using a moisture sensor, and have the variable 'Moisture' in my database where the values are stored and updated every 0.3 seconds. I currently have the following code:
HTML File
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
};
firebase.initializeApp(config);
</script>
<script>
var database = firebase.database();
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "plant-patrol"
var childKey = snapshot.child("plant-patrol/Moisture").key; // "Moisture"
});
</script>
<script>
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
</script>
<script src="/script.js" defer></script>
</head>
</html>
JS File
auth.onAuthStateChanged(currentUser => console.log(currentUser));
auth.signInAnonymously();
I have no idea what this JS code does, but I copied it from another question on Stack Overflow.
Now as stated before, the path in the Realtime Firebase db I want to display is 'Moisture', that is also the only data in the db. I have tried messing around a bit with the childkey and snapshot, and tried reading into what they actually do. Sadly I was not able to display any form of data, not even in the console.
The read & write lines in Firebase have both been set to True as security is not relevant (school project). I was also wondering if it is possible to update the data on the website without having to refresh the page.
Update
Made a bit of progress,read my comments below!

How configure redirect to api on AWS S3 hosting static website?

The idea is basically redirect calls to /api to some origin.
for example ==> http://my-production-api.com/
I have my html file,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Redirect - API</title>
<script>
const api = 'https://jsonplaceholder.typicode.com';
fetch(api + '/todos/1')
.then(response => response.json())
.then(json => console.log(json)).catch(console.log);
const ENV_API = '/api';
fetch(ENV_API + '/todos/1')
.then(response => response.json())
.then(json => console.log(json)).catch(console.log);
</script>
</head>
<body>
<div id="app">
Redirect api
</div>
</body>
</html>
and the next routing rule:
<RoutingRules>
<RoutingRule>
<Condition>
<KeyPrefixEquals>/api</KeyPrefixEquals>
</Condition>
<Redirect>
<ReplaceKeyWith>https://jsonplaceholder.typicode.com</ReplaceKeyWith>
</Redirect>
</RoutingRule>
but, the result in console is : Failed to load resource: the server responded with a status of 403 (Forbidden).
thanks for aswer my question!!
I did resolved with :
<RoutingRules>
<RoutingRule>
<Condition>
<KeyPrefixEquals>api/</KeyPrefixEquals>
</Condition>
<Redirect>
<HostName>jsonplaceholder.typicode.com</HostName>
<ReplaceKeyPrefixWith></ReplaceKeyPrefixWith>
</Redirect>
</RoutingRule>

Spotify web player gives Websocket error on raspberry pi

I am trying to set up spotify player to my raspberry pi. I have codes that work's like a charm on my macbook/chrome but the same codes wont work on raspbian/chromium.
I am getting following errors:
Error while parsing the 'allow' attribute: 'encrypted-media' is an invalid feature name.
{message: "Failed to initialize player"} script.js:44
WebSocket connection to 'wss://gew-dealer.spotify.com/?access_token=removed_my_token'
failed: Error in connection establishment: net:: ERR_NOT_IMPLEMENTED
{message: "Authentication failed"} script.js:45
Here is my script.js:
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'removed_my_client_id';
const redirectUri = 'http://localhost:1337';
const scopes = [
'streaming',
'user-read-birthdate',
'user-read-private',
'user-read-email',
'user-modify-playback-state'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token&show_dialog=true`;
}
// Set up the Web Playback SDK
window.onSpotifyPlayerAPIReady = () => {
const player = new Spotify.Player({
name: 'Web Playback SDK Template',
getOAuthToken: cb => { cb(_token); }
});
// Error handling
player.on('initialization_error', e => console.error(e));
player.on('authentication_error', e => console.error(e));
player.on('account_error', e => console.error(e));
player.on('playback_error', e => console.error(e));
// Playback status updates
player.on('player_state_changed', state => {
console.log(state)
$('#current-track').attr('src', state.track_window.current_track.album.images[0].url);
$('#current-track-name').text(state.track_window.current_track.name);
});
// Ready
player.on('ready', data => {
console.log('Ready with Device ID', data.device_id);
// Play a track using our new device ID
play(data.device_id);
});
// Connect to the player!
player.connect();
}
// Play a specified track on the Web Playback SDK's device ID
function play(device_id) {
$.ajax({
url: "https://api.spotify.com/v1/me/player/play?device_id=" + device_id,
type: "PUT",
data: '{"uris": ["spotify:track:5ya2gsaIhTkAuWYEMB0nw5"]}',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
success: function(data) {
console.log(data)
}
});
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Spotify Web Playback SDK Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<!-- Include the Web Playback SDK -->
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<!-- Include our Javascript -->
<script src="script.js" defer></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Web Playback SDK Template</h1>
<h4>This app uses the implicit grant authorization flow to get an access token and initialise the Web Playback SDK. It then uses the Spotify Connect Web API to play a song.</h4>
<p>If everything is set up properly, you should hear some music!</p>
<img id="current-track"/>
<h3 id="current-track-name"></h3>
<a class="btn btn-salmon btn-lg" href="https://glitch.com/edit/#!/spotify-web-playback">Get started!</a>
</body>
</html>
This code should do:
Initialize the web player
Select one hard coded song
Play the song
Show the image
I have absolutely no idea what could be the problem here. I have been trying a lot of things to fix this but the problem is that i don't know what causes this so i have been just doing stuff without any idea is it going to help. So my question is how i can make this work on raspberry?

Categories