Why is my Music Bot Lagging? (discord.js) - discord.js

I have a discord bot with multiple stuff but the music is very laggy. Does anyone know why? (I'm using v12-master)
Code:
const ytdl = require('ytdl-core-discord')
const connection = await message.member.voice.channel.join();
const dispatcher = await connection.play(await ytdl(url), { type: 'opus' });

There are few things if you are using Heroku as your host it will lag for sure
or Thats your Bandwidth issue Upgrade your internet plan or use Amazon web server or any other hosting services with better bandwidth

Related

Bypassing Firestore Security Rules in jest tests

Currently working on a React/Typescript/Firebase Firestore project. When writing Jest-tests for some actions/functions that are called from the UI, I ran into the following problem:
In the test file I'm able to setup the firestore client using the v9 api and make it talk to emulator
const app = initializeApp(config.firebase);
const firestore = getFirestore(app);
connectFirestoreEmulator(firestore, "localhost", 8080);
In addition I also found out how to setup the admin client and make it talk to emulator
process.env.FIRESTORE_EMULATOR_HOST = "localhost:8080";
const serviceAccount = require("../../../my-key.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
...config.firebase
});
The test itself looks something like this:
describe("createCompanyAndRating action", () => {
test("call createCompanyAndRating and make sure it creates a proper rating entity", async () => {
// omitted: set testRatingFormState and other test data that are passed as args and
// pass in the firestore db client
const {
ratingId,
companyId,
} = await createCompanyAndRating({
ratingFormState: testRatingFormState,
visitorId: testVisitorId,
firestore,
});
// verify result by fetching the rating entity from the emulator db using the admin client
const ratingPath = `companies/${companyId}/ratings/${ratingId}`;
const ratingSnap = await admin.firestore().doc(ratingPath).withConverter(ratingConverter).get();
const rating: Rating | undefined = ratingSnap.data();
// omitted: verify result with some Jest expect-statetments...
});
})
My problem is now that the Firestore security rules apply and only authenticated users can write docs in the collections used in the createCompanyAndRating function, so the test already throws an error when calling that function.
In this scenario I'm not interested in testing the security rules per se.
Is there a way to bypass the security rules for the test?
If yes, how do I have to setup the firestore client?
Is there even the possibility to somehow impersonate a user in the test?
In addition, please note that I can't to pass the admin client into the createCompanyAndRating function as the admin client API is different from the v9 firebase API that I'm relying on in the createCompanyAndRating function implementation (tried and it didn't work and not only because some type errors in the way).
Maybe my whole approach is a little misguided and I should rather concentrate on testing the internals of the createCompanyAndRating function where I do a lot of factory stuff that could be tested without db interaction.
Anyway, any help/guidance is much appreciated.
Thanks for confirming that I was looking in the right place (i.e. #firebase/rules-unit-testing). Finally figured out what the problem was, missed an "await" in createCompanyAndRating, so the firestore admin instance wasn't getting the data (and I though it was a admin config issue...) Thanks!

How do I identify cause of Axios "Network Error"?

I can't get an Axios "get" request working for a front-end/back-end pair after moving the code from CentOS 7 to a CentOS 8 instance. The code in question works just fine on a different AWS EC2 instance. I can't make it work on the new EC2 instance running Rocky Linux v8.5.
When I catch the exception to look at the error, I see a most unhelpful:
Error: Network Error
I can find NO information about the complaint was or how to fix it. I can't get ANY useful information about what is causing the issue. I'm sure it's something stupid and easy to fix -- it would be much easier if I can somehow get the technology stack to tell me what the issue is.
I use the axios component to access a Node Express service running on the same instance that hosts the React app. The service is listening to https on port 7003. The React app calls this server, and returns data provided by the service.
I use axios for all communication between the React app and the rest of the world, so I need to fix this.
I use VisualStudio Code (VSC) to develop my React and NodeJS code.
When I exercise the service using wget, it seems to work:
$ wget "https://my.domain.name.com:7003/getEnvironment"
--2022-02-24 21:46:46-- https://my.domain.name.com:7003/getEnvironment
Resolving my.domain.name.com (my.domain.name.com)... 172.30.2.147
Connecting to my.domain.name.com (my.domain.name.com)|172.30.2.147|:7003... connected.
HTTP request sent, awaiting response... 200 OK
Length: 11205 (11K) [application/json]
Saving to: ‘getEnvironment’
getEnvironment 100%[===================================>] 10.94K --.-KB/s in 0s
2022-02-24 21:46:46 (220 MB/s) - ‘getEnvironment’ saved [11205/11205]
I notice that wget says it's using "HTTP" even though I've given it "https" in the command-line.
I run the front-end in VSC using the React/VSC development server. That server listens on port 3003.
I've turned on cors for the service, and it is listening on port 7003 as expected. That's why the wget works.
The back-end (service) code looks something like this:
...
var cors = require('cors');
...
var app = express();
...
app.use(cors({origin: true, credentials: true}));
...
The front-end code that is failing looks like this:
checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.data;
} else {
const error = new Error(`HTTP Error ${response.statusText}`);
error.status = response.statusText;
error.response = response;
console.log(error);
throw error;
}
}
privateLoadEnvironmentUsingURL(url) {
return axios
.get(url)
.then((response) => {return this.checkStatus(response)})
.catch((error) => {
console.log(error);
throw error;
});
}
I've exercised this with both front-end and service in VSC. The axios call is failing and so far as I can tell is doing so before ever invoking the service.
It takes awhile to fail, leading me to suspect a timeout is in play. I see no indication in the nodejs service code that the request is actually hitting the service.
It therefore appears that the "preflight" negotiation is blocking this call. Turning on cors is pretty much all I know how to do -- I don't have deep insight into cors.
I've been waving voodoo chickens at this code all afternoon to no avail.
How do other developers discover how to fix problems like this when the technology stack presents so little information about what is actually happening?
How do I get this working?
I found and solved the problem, a network configuration issue completely outside axios/nodejs/react. The fact remains that I think it should somehow be possible for a developer to get at least a hint from the exception raised by axios.
For those who are interested, the problem turned out to be the AWS Security Group configuration for the new system. I had to open port 7003 in the Security Group, allowing access from my local IP address, in order for the request to be forwarded to the platform.
I suppose I should have thought of this sooner -- VSC spawns a special Chrome browser on my local system with its own private tunnel and such. It appears that that browser instance running on my local machine makes the request against port 7003. The AWS Security Group was blocking that port, and so the request never made it to the server.
I identified the issue by doing the wget from my local machine rather than from the new target EC2 instance. That failed, and then I attempted to connect with telnet. When the latter could not connect, I knew it was a Security Group issue.
The bottom line is that it is sometimes too easy to forget that ALL React code runs in the browser. I know that's obvious. but its implications sometimes are not.

Access SSM Parameter store value in an aws amplify react js application

I have an amplify application built using React JS, I have a scenario for which I am manually storing API keys in my SSM parameter store in my AWS account. However, I want to retrieve/get those values(JSON object) based on a key from my React JS app (client side). So, I have installed the aws-sdk, the AWS JavaScript sdk, and using the below code snipped I am trying to access the ssms parameter store
const AWS = require('aws-sdk');
AWS.config.update({region:'us-east-1'});
const ssm = new AWS.SSM();
const getSecret = async (secretName) => {
console.log(`Getting secret for ${secretName}`);
const params = {
Name: secretName,
WithDecryption: true
};
const result = await ssm.getParameter(params).promise();
return result.Parameter.Value;
};
module.exports = {getSecret};
I am receiving this error on running my application and while accessing the store using the getSecret function.
Unhandled Rejection (CredentialsError): Missing credentials in config,
if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
I believe that amplify configures the environment implicitly but since, the SSM Secrets manager is not supported yet by Amplify hence, I have to use the JS AWS SDK for this purpose. Can anyone help me spot the issue while configuring the service using AWS SDK? Or is there another or a better way to access parameter store from the client side?
Also, after surfing I have found a package named dotenv
Is it okay to store aws credentials in such a way?
Your code to fetch parameter store keys/values shouldn't be at client side considering security implications. It should be done at server-side and functionality can be exposed over endpoint for client-side.
You can read the credentials programmatically something like below:
var AWS = require("aws-sdk");
var credentials = new AWS.SharedIniFileCredentials({profile: 'profile name'});
AWS.config.credentials = credentials;
Refrence:
loading-node-credentials-shared
global-config-object

How to use the SalesForce API?

I'm trying to use an express/node application to make an api call to the salesforce api and return me data according to the records I have with the account.
But it is returning this:
[{"errorCode":"NOT_FOUND","message":"The requested resource does not exist"}]
Currently my code looks like this
const express = require('express')
const app = express();
var request = require('request');
app.get('/',(req,res, next) =>{
request({
url: 'https://nav4.lightning.force.com/services/data"',
}).pipe(res);
});
})
const port = process.env.PORT || 3000; app.listen(3000, ()=>
console.log(`listening on port ${port}`))
I think my URL is wrong and might need authentication also.
You do need to authenticate first to https://login.salesforce.com. I would suggest reading and following the documentation at their documentation. The username password flow is only recommended for testing purposes though, so once you get it working you might want to look into a different oauth flow if you are building a real application depending on your use case.
For consume the Salesforce API below are the Details to notes.
Find which api to consume REST OR SOAP
Needs :
Base URL
Endpoint URL
Consumer Key and secret key
This are the Point To archive
Below are for Your Reference
https://developer.salesforce.com/page/Consuming_Force.com_SOAP_and_REST_Web_Services_from_.NET_Applications
https://trailhead.salesforce.com/content/learn/modules/apex_integration_services

How to send sms messages from a React Native App programmatically ?

I want to be able to sent sms messages though my React Native app programatically in the background.
I know how to sent sms normally in the code, but the app keeps opening the default sms app, and that is not what i want.
The user should not push any buttons to sent the sms, because my goal is to notify a phonenumber every time the user is doing a particularly task in the app.
I have tried looking at Twilio, but they dont provide a api for React Native.
Does anybody know something about how I can do this ?
With the answer from kdenz, I followed a tutorial here: Seeting up a firebase function
This is my code for sending a request to Twilio, when the firebase database value 'visible' is changing.
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const twilio = require('twilio');
const accountSid = functions.config().twilio.sid;
const authToken = functions.config().twilio.token;
console.log(`Twilio account: ${accountSid}`);
const client = new twilio(accountSid, authToken);
const twilioNumber = 'xxx-xxx-xxx';
exports.textStatus = functions.database
.ref('/users/{userId}/data/visible')
.onUpdate(event => {
return admin.database()
.ref(`users/{userId}/data/`)
.once('value')
.then(snapshot => snapshot.val())
.then(user=> {
console.log(user[0]);
const longitude = user.longi;
const latitude = user.lati;
const phoneNumber = user.phone;
const textMessage = {
body: `See user position at Google: http://www.google.com/maps/place/${latitude},${longitude}`,
to: phoneNumber,
from: twilioNumber
}
return client.messages.create(textMessage);
})
.then(message => console.log(message.sid, 'success'))
.catch(err => console.log(err));
});
I think this is only possible with Android, as seen in this deprecated package https://www.npmjs.com/package/react-native-send-sms
For iOS, I don't think so, as seen in How to programmatically send a text message after the user has given permission?
To achieve what you want, you'll need a SMS service like Twilio. Then you can set up a server (Or a cloud function for minimal cost + easy maintainability) which receives API calls from your RN app, and sends the message to the desired recipient. You can then set up some security measures too, to prevent hackers from spamming the API.
Or if you don't care about security (Which I highly don't recommend), you can directly call Twilio send message API within your app, which is dangerous because hackers can easily extract your Twilio authorization token and use it to send messages for themselves.
On android, it is possible to send sms from user's number programmatically without user interaction.
But on IOS, the only way you can send an SMS without user interaction is to use an external provider such as Twilio; but the message will come from your server's number, not from the user.
I have already answered for same kind of question. Check this out
Is there anyway to send sms in background for both Android & IOS?

Resources