Twitter API only posting to developer linked account? - javascript

I have been trying to play around with Twitter API and using the npm i twitter-lite library. I want for others to post something through my website when they click on post and sign in, however, it only posts to my developer account. The following is my code:
const config = require('./config');
const twitter = require('twitter-lite');
const client = new twitter(config);
client
.getRequestToken("website")
.then(res =>
console.log({
reqTkn: res.oauth_token,
reqTknSecret: res.oauth_token_secret
})
)
.catch(console.error);
client.post('statuses/update', { status: 'testing' }).then(result => {
console.log('You successfully tweeted this : "' + result.text + '"');
}).catch(console.error);
Appreciate any advice.

Related

How to do 'signTransaction' after authenticated by 'signPersonalMessage' by WalletConnect of '#walletconnect/react-native-dapp'?

I am developing a react native mobile app where user can connect their existing wallet(rainbow, metamask and many more) to app.
I have already done the authentication part, like user can successfully connect their app wallet to app by this code.
import { useWalletConnect } from '#walletconnect/react-native-dapp';
const connector = useWalletConnect();
await connector.connect();
const message = `App name is XYZ - ${new Date().toUTCString()}`;
const hexMsg = convertUtf8ToHex(message);
const address = connector.accounts[0];
await setItemToStorage('address', address);
const msgParams = [hexMsg, address];
connector.signPersonalMessage(msgParams).then(async result => {
let data = {
message,
signature: result,
};
Now every thing is working as expected.
And then I have to transfer my wallet amount to other address, and to achieve this I know I have to get permission from wallet app,
To achieve this I am trying to do like
let txObj = {
gas: Web3js.utils.toHex(100000),
to: receiver_address!,
data: data,
from: userWallet,
};
console.log('Start transaction...');
const singTrasaction = await connector.signTransaction(txObj);
The connector.signTransaction(txObj) open the wallet app but not prompted me to confirm.
I am just confused and nothing get help me.
Please help me anyone I am getting stuck on this since a week.

Node.js Cheerio Live Update/Instant Refresh page on every HTML body change

I am using Axios and cheerio to scrape the cricket score website and convert its data to JSON format.
But the problem is that scores and other information are not updating instantly on my API response.
I want to have kind of useEffect (I know, it's React Hook and don't work in Express) functionality in my express server so that whenever the score changes on the main website, my server re-scrapes the page and show updated data.
axios(link).then(response => {
const html = response.data
const $ = cheerio.load(html)
const score = []
$('.scorecard-container', html).each(function(){
const title = $(this).text()
const url = link + $(this).find('a').attr('href')
score.push({
id: score.length + 1,
title,
url
})
})
res.json(score)
}).catch(err => {res.send('Something went wrong'); console.log(err)})
Thanks in Advance :)
example express endpoint
get("/stats", async (req, res) => {
let { data } = await axios.get(someUrl)
let $ = cheerio.load(data)
res.json({
title: $('title').text()
})
})
in react
useEffect(() => {
fetch("/stats").then(r=> r.json().then(data => setStats(data)))
}, [])

How to send notification to multiple device token using firebase cloud functions

I am new in using Firebase Cloud Functions and JavaScript and I was able to send notification to a single device using Firebase Cloud Functions(JavaScript). Now I am trying to send push notification to multiple device token and I think I have a problem on it.
I want to send the notification to these device tokens in my firebase database:
/receivers
/event1
/uid1: device_token1
/uid2: device_token2
/uid3: device_token3
/uid4: device_token4
This is my code so far but it doesn't work..
exports.sendSOSNotif = functions.database.ref('/SOSNotifs/{sosId}').onWrite((data, context) => {
const eventId=data.after.child("eventId").val();
const uid=data.after.child("uid").val();
const displayName=data.after.child("displayName").val();
const photoUrl=data.after.child("photoUrl").val();
const status=data.after.child("status").val();
console.log("eventId:", eventId);
console.log("displayName:", displayName);
console.log("uid", uid);
const payload = {
notification: {
title: "SOS Alert",
body: displayName + " sent an alert!",
sound: "default"
},
data: {
eventId: eventId,
displayName: displayName
}
};
return Promise.all([admin.database().ref("/receivers/event1").once('value')]).then(results => {
const tokens = results[0];
if (!tokens.hasChildren()) return null;
const tokensList = Object.keys(tokens.val());
return admin.messaging().sendToDevice(tokensList, payload);
});
});
First of all, you shouldn't be adding tokens like below, if that's how you've organised your DB. There might be multiple token for a single uid
/receivers
/event1
/uid1: device_token1
/uid2: device_token2
/uid3: device_token3
/uid4: device_token4
And for sending notifications to multiple UIDs, I've written a script here
Also, update your question about what exactly the problem you are facing.

Firebase functions FCM

I'm building an app with Firebase and as they added functions I wanted to try this out but ran into a few errors as I am unfamiliar with this language... I'm trying to send an FCM to every user of a group (when a new one is added to the database) and I used the example I found online but still ran into some trouble.
exports.sendPush = functions.database.ref('/groups/{groupId}').onWrite(event => {
const groupId = event.params.groupId;
... // defining constants like msg
const participators = admin.database().ref('/groups/' + groupId + '/users').once('value');
let getDeviceTokensPromise = []
for (let part in participators) {
getDeviceTokensPromise.push(admin.database().ref('/users/' + part + '/notificationtoken')).once('value');
}
return Promise.all([getDeviceTokensPromise, participators]).then(results => {
const tokensSnapshot = results[0];
const follower = results[1];
// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
console.log('Fetched follower profile', follower);
// Notification details.
const payload = {
notification: {
title: 'New meeting!',
body: msg
}
};
// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// For each message check if there was an error.
...
So I guess my mistake must be in the first few lines as all the rest follows this code (I left out the unimportant bits)... Here is my firebase architecture:
The groups branch of the firebase database
One user under the branch users
Regards
Your code is fine. Just change the following
const participators = admin.database().ref('/groups/' + groupId + '/users').once('value');
and
getDeviceTokensPromise.push(admin.database().ref('/users/' + part + '/notificationtoken')).once('value');
to these :-
const participators = admin.database().ref(`/groups/${groupId}/users`).once('value');
and
getDeviceTokensPromise.push(admin.database().ref(`/users/${part}/notificationtoken`)).once('value');
Also, make sure that you use `` and not ' ' inside the ref part.

window.WebSocket - window is not defined

I am a bit out of my comfort zone here, so looking for a bit of guidance. I am trying to access an api to display live metrics, using phonic-elixir (https://www.npmjs.com/package/phoenix-elixir) - am just sort of trying to get it running first, so have loaded up their example code and connecting to an api (forgive me if the terminology is all wrong, I am new at this!)
This is my code:
import {Socket} from 'phoenix-elixir';
let socket = new Socket('ws://API_URL_HERE', {params: {'auth-token': 'AUTH_TOKEN'}})
socket.connect()
let channel = socket.channel('updates:new', {})
channel.join()
.receive('ok', resp => { console.log('Joined successfully', resp) })
.receive('error', resp => { console.log('Unable to join', resp) })
channel.on('update', payload => {
console.log('Received: ' + payload);
console.log(payload);
})
export default socket
When I run babel index.js | node I am getting the error: this.transport = opts.transport || window.WebSocket || LongPoll; and ReferenceError: window is not defined
Just some advice to point me in the right direction would be fantastic. Is window not defined because it needs a dom? Do I need a server to run this in?
Thank you :)
I just ported the client to be compatible with node.JS.
Here is the link https://github.com/mcampa/phoenix-channels
The difference with the original client is that this does not use long-polling and you need to pass the absolute url instead of the relative url.
To install it run:
npm install --save phoenix-channels
Same API as the original:
const { Socket } = require('phoenix-channels')
let socket = new Socket("ws://example.com/socket")
socket.connect()
// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("room:lobby", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
phoenix-elixir is client-side library that is supposed to be used in browsers not in node environment. You should create html page with your code and open it in browser to test it out.

Categories

Resources