How to make an uptime command in nodejs tmijs chat bot - node.js

How would you make an uptime command with tmi.js, I thought it would be as simple as;
client.on("chat", function(channel, user, message, self, uptime){
client.say("CHANNEL", "Channel has been live for " + uptime
})
How would you go about making this command, the example I gave does not work and I would request you to let me know.

It doesn't look like channel metadata is available over the Twitch WebSocket API. If you want to get that information, you'll need to go through the "New Twitch API" and use the /streams endpoint.
You will also need to have a Client-ID to make requests to this endpoint. You can get one by following the instructions here: Apps & Authentication Guide.
Once you have a Client-ID, you can make a request. I'm using the node-fetch module to make requests easier. This example will get the 2 most active streams. You can adjust the query string parameters to get the appropriate stream.
const querystring = require("querystring"),
fetch = require("node-fetch");
const CLIENT_ID = "YOUR_CLIENT_ID";
const STREAMS_URL = "https://api.twitch.tv/helix/streams";
const qs = querystring.stringify({
first: 2
});
const qUrl = `${STREAMS_URL}?${qs}`;
const fetchArgs = {
headers: {
"Client-ID": CLIENT_ID
}
};
fetch(qUrl, fetchArgs)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
This would print out something like the following:
{
data: [{
id: '28378863024',
user_id: '19571641',
game_id: '33214',
community_ids: [],
type: 'live',
title: 'Morning Stream! | #Ninja on Twitter and Insta ;)',
viewer_count: 107350,
started_at: '2018-04-18T14:58:45Z',
language: 'en',
thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_ninja-{width}x{height}.jpg'
},
{
id: '28379115264',
user_id: '22859264',
game_id: '32399',
community_ids: [Array],
type: 'live',
title: 'LIVE: Astralis vs. Space Soldiers - BO1 - CORSAIR DreamHack Masters Marseille 2018 - Day 1',
viewer_count: 54354,
started_at: '2018-04-18T15:28:44Z',
language: 'nl',
thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_dreamhackcs-{width}x{height}.jpg'
}]
}
The started_at property is the timestamp of when the stream began. Bear in mind that this API is rate limited so you should probably cache the started_at so you don't immediately run out of requests.

Related

GCP Cloud Function for Slash command not working

so i'm trying to make an slash command on my slack using nodejs and Cloud Functions. I'm getting error 403 when the slash command goes out to the function, but i'm having problems to identify why it's giving me the error.
The code of the function is this:
const { WebClient } = require('#slack/web-api');
exports.slashCommand = (req, res) => {
// Verify that the request is coming from Slack
if (!req.body.token || req.body.token !== process.env.SLACK_TOKEN) {
res.status(403).end();
return;
}
// Parse the request body and extract the Slack user ID, command text, and response URL
const { user_id, text, response_url } = req.body;
// Use the Slack Web API client to post a message to the response URL
const web = new WebClient();
web.chat.postMessage({
channel: user_id,
blocks: [
{
type: 'section',
text: {
type: 'plain_text',
text: 'This is a section block'
}
},
{
type: 'divider'
},
{
type: 'section',
fields: [
{
type: 'plain_text',
text: 'This is a field'
},
{
type: 'plain_text',
text: 'This is another field'
}
]
}
]
});
// Send a 200 OK response to acknowledge receipt of the request
res.status(200).end();
};
I'm using nodeJS 18 to build
I also created gen 1 and gen2 with the same code, but the problem persists. I've given permission to allUsers to call the URL, but still no go. My SLACK_TOKEN is configured in the env. I'm suspecting that's something in the payload but i'm not understanding why this is happening. ( i'm new to this, so i'm sorry for the lack of details, if theres something i should add, let me know ).
Tried to give permission to allUsers, and still getting error. I'm really struggling to make slack validate the payload so my guess is the code checking if the payload and the token is valid is breaking everything.

Can't access the stripe check-out page

I have written my server-side code by nodejs .
I have implemented a route to create a stripe checkout session, which contains a bunch of data about the object that is going to be purchased.
router.get(
'/checkout-session/:productId',
catchAsync(async (req, res, next) => {
// 1) Get the currently ordered product
const product = await Product.findById(req.params.productId);
// 2) Create checkout session
const session = await stripe.checkout.sessions.create({
expand: ['line_items'],
payment_method_types: ['card'],
success_url: `https://nasim67reja.github.io/CareoCIty-ecommerce/`,
cancel_url: `https://nasim67reja.github.io/CareoCIty-ecommerce/#/${product.categories}`,
customer_email: req.user.email,
client_reference_id: req.params.productId,
line_items: [
{
price_data: {
currency: 'usd',
unit_amount: product.price * 100,
product_data: {
name: `${product.name} `,
description: product.summary,
images: [
`https://e-commerceapi.up.railway.app/Products/${product.categories}/${product.images[0]}`,
],
},
},
quantity: 1,
},
],
mode: 'payment',
});
// 3) Create session as response
res.status(200).json({
status: 'success',
session,
});
})
);
Then on the front-end (ReactJs), I created a function to request the checkout session from the server once the user clicks the buy button.
So once I hit that endpoint that I created on the backend, that will make a session and send it back to the client. Then based on that session, the stripe will automatically create a checkout page for us. where the user can then input
here is my client side code:
const buyProduct = async () => {
try {
const session = await axios.get(
`${URL}/api/v1/orders//checkout-session/${product}`
);
window.location.replace(session.data.session.url);
} catch (error) {
console.log(`error: `, error.response);
}
};
All was okay when I tried on the local server.But when I hosted my backend on the Railway, then I got an error
I have also tried to put the stripe public & private key on the authorization header. but still got that error.I searched a lot but didn't find any solution. I will be very happy to get help from you
Looks like your server on Railway doesn't have the correct secret key. It depends on how you initialize stripe in NodeJS, but normally if you read it from an environment variable, you want to make sure Railway also sets that value correctly.
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);

How to get INTERESTS in the "facebook-nodejs-business-sdk"

I am developing an application to consume the facebook api using the package "facebook-nodejs-business-sdk" in version v9.0.
I'm looking for a method to get interests, but I can't find it.
I looked in the examples available in the package, but I can't find anything that allows me to search the search node.
Using the graph api explorer I can see that the code to make these calls with javascript is as follows:
FB.api( '/search','GET', {"type":"adinterest","q":"Golf","limit":"10000","locale":"pt_BR"}, function(response) { // Insert your code here } );
But the application is using the mentioned package and generally has specific methods for calls.
I'm a beginner in programming so I'm lost.
Can someone help me?
Thanks!
I didn't find any reference to this in the SDK but seems you could call the targeting search api by yourself with the following example:
const bizSdk = require('facebook-nodejs-business-sdk');
const access_token = '<the_token>';
const api = bizSdk.FacebookAdsApi.init(access_token);
const showDebugingInfo = true; // Setting this to true shows more debugging info.
if (showDebugingInfo) {
api.setDebug(true);
}
const params = {
'type' : 'adinterest',
'q' : 'Golf',
'limit' : '10000',
'locale' : 'pt_BR',
};
api.call('GET',['search'], params).then((response) => {
console.log(response)
}).catch(error => {
console.log("something bad happened somewhere", error);
});
This code will output something like:
{
data: [
{
id: '6003631859287',
name: 'Golf',
audience_size: 218921,
path: [Array],
description: null,
disambiguation_category: 'Negócio local',
topic: 'News and entertainment'
},
{
id: '6003510075864',
name: 'Golfe',
audience_size: 310545288,
path: [Array],
description: '',
topic: 'Sports and outdoors'
....
Hope this help

Stripe processed, now what?

I'm trying to build a serverless NuxtJS app, utilizing firebase for authentication, netlify for deployment (and functions) and stripe for payment.
This whole payment-process and serverless functions on netlify is all new to me, so this might be a nooby question.
I've followed serveral docs and guides, and accomplished an app with firebase authentication, netlify deployment and serverless functions making me able to process a stripe payment - now I just cant figure out the next step. My stripe success_url leads to a /pages/succes/index.js route containing a success message -> though here I'd need some data response from Stripe, making me able to present the purchased item and also attaching the product id as a "bought-product" entry on the user object in firebase (the products will essentially be an upgrade to the user profile).
Click "buy product" function
async buyProduct(sku, qty) {
const data = {
sku: sku,
quantity: qty,
};
const response = await fetch('/.netlify/functions/create-checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((res) => res.json());
console.log(response);
const stripe = await loadStripe(response.publishableKey);
const { error } = await stripe.redirectToCheckout({
sessionId: response.sessionId,
});
if (error) {
console.error(error);
}
}
create-checkout Netlify function
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const inventory = require('./data/products.json');
exports.handler = async (event) => {
const { sku, quantity } = JSON.parse(event.body);
const product = inventory.find((p) => p.sku === sku);
const validatedQuantity = quantity > 0 && quantity < 11 ? quantity : 1;
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
billing_address_collection: 'auto',
shipping_address_collection: {
allowed_countries: ['US', 'CA'],
},
success_url: `${process.env.URL}/success`,
cancel_url: process.env.URL,
line_items: [
{
name: product.name,
description: product.description,
images: [product.image],
amount: product.amount,
currency: product.currency,
quantity: validatedQuantity,
},
],
});
return {
statusCode: 200,
body: JSON.stringify({
sessionId: session.id,
publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
}),
};
};
Please let me know if you need more information, or something doesnt make sense!
tldr; I've processed a Stripe payment in a serverless app using Netlify function, and would like on the success-page to be able to access the bought item and user information.
When you create your Checkout Session and define your success_url, you can append session_id={CHECKOUT_SESSION_ID} as a template where Stripe will auto-fill in the session ID. See https://stripe.com/docs/payments/checkout/accept-a-payment#create-checkout-session
In your case you'd do:
success_url: `${process.env.URL}/success?session_id={CHECKOUT_SESION_ID}`,
Then when your user is redirected to your success URL you can retrieve the session with the session ID and do any purchase fulfilment.

Why are the Stripe Payments Incomplete?

My Stripe payments show up on my dashboard, but they have an 'Incomplete' status, and hovering over shows the tip, "The customer has not entered their payment method." I thought I accounted for payment method in my sessions.create() method.
My Angular component creates a StripeCheckout and sends the session data to my API. API then includes it in the response to the browser (my first attempt was to use this sessionId to redirect to checkout, but I chose this because it was smoother).
Angular/TS StripeCheckout and handler:
let headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append(
"authentication",
`Bearer ${this.authServ.getAuthenticatedUserToken()}`
);
this.handler = StripeCheckout.configure({
key: environment.stripe_public_key,
locale: "auto",
source: async source => {
this.isLoading = true;
this.amount = this.amount * 100;
this.sessionURL = `${this.stringValServ.getCheckoutSessionStripeURL}/${this.activeUser.id}/${this.amount}`;
const session = this.http
.get(this.sessionURL, {
headers: new HttpHeaders({
"Content-Type": "application/json",
authentication: `Bearer ${this.authServ.getAuthenticatedUserToken()}`
})
})
.subscribe(res => {
console.log(res);
});
}
});
//so that the charge is depicted correctly on the front end
this.amount = this.amount / 100;
}
async checkout(e) {
this.stripeAmountEvent.emit(this.amount);
this.handler.open({
name: "[REDACTED]",
amount: this.amount * 100,
description: this.description,
email: this.activeUser.email
});
e.preventDefault();
}
NodeJS API picks it up
exports.getCheckoutSession = catchAsync(async (req, res, next) => {
const currentUserId = req.params.userId;
const paymentAmount = req.params.amount;
const user = await User.findById(currentUserId);
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
success_url: `${process.env.CLIENT_URL}`,
cancel_url: `${process.env.CLIENT_URL}`,
customer_email: user.email,
client_reference_id: user.userId,
line_items: [
{
name: `Donation from ${user.userName}`,
description: '[REDACTED]',
amount: paymentAmount,
currency: 'usd',
quantity: 1,
customer: user.userId
}
]
});
const newPayment = await Payment.create({
amount: paymentAmount,
createdAt: Date.now(),
createdById: user._id
});
res.status(200).send({
status: 'success',
session
});
});
The payment gets created in my db, and the payment shows up on my Stripe dashboard. The payments show as 'Incomplete' when I expected it to charge the card.
Thanks in advance.
The latest version of Checkout lets you accept payments directly on a Stripe-hosted payment page. This includes collecting card details, showing what's in your cart and ensuring the customer pays before being redirected to your website.
At the moment, though, your code is mixing multiple products in one place incorrectly. The code you have client-side uses Legacy Checkout. This is an older version of Stripe's product that you could use to collect card details securely. This is not something you should use anymore.
Then server-side, you are using the newer version of Checkout by creating a Session. This part is correct but you never seem to be using it.
Instead, you need to create the Session server-side, and then client-side you only need to redirect to Stripe using redirectToCheckout as documented here.

Resources