Using client in different files - discord.js

Is it possible to use the client/bot constant across different files?
My index.js file has gotten pretty clogged up, so I tried splitting different functions into different files.
I already tried exporting the bot constant from index.js:
// in index.js
module.exports = {
Gbot: bot
}
// in different file
const index = require('../index.js')
const bot = index.Gbot
bot.on('message', message => {
message.channel.send("test")
})
The second file does not do anything, it does not respond with "test"
There is no errors either
Is this not possible or am I doing something wrong?

This is possible, but why do you want to do that? If you are using a Command Handler you define client or bot to use it everywhere. And if not you are running everything in index.js, the file where you defined client or bot.
Edit:
//index.js
module.exports.Gbot = bot;
//other file
const index = require("../index.js");
const bot = index.Gbot;

Related

How to download file from firebase storage and turn it into .stl file with react?

I am trying to download a file I stored on firebase storage and then turn it into an stl file to be later used by ThreeJs.
Currently I am trying to use the following code but it results in a file with 0 size:
const [blobData, setBlobData] = useState([]);
const storageRef = storageReference(
storage,
'/storage/testModel.stl',
)
if (blobData.length < 1) {
getBlob(storageRef).then((data) => {setBlobData(data)});
var testFile = new File([blobData], "testFile.stl");
}
console.log("Outside Loop",testFile);
What the log outside the loop logs is the following:
Is there a better way to do this or can I use this code with changes?
I was using the STLLoader from react three fiber and it turnes out you can give the URL from firebase storage directly to this loader.

Netlify Redirect or Rewrite for Gatsby Wildcard Path

So I've already implemented a wildcard path on my gatsby-node.js file:
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
if (page.path.match(/^\/my-path/)) {
page.matchPath = "/my-path/*"
createPage(page)
}
}
and this works fine when I am running the site locally (in development). i.e., if i provide /my-path/anything123 or /my-path/asdfasdfasdf, both will lead to a rendering of the component I've created in my Gatsby project under pages/my-path.tsx.
Now we come to my problem. When I deploy my site to Netlify, I don't get the same behavior as in development. Can behavior like this be handled with a redirect or rewrite in Netlify? I don't want to lose the content in what comes after /my-path/, as in reality I'm using it to parse an id, i.e. if the URL in the browser is /my-path/123, I want to be able to see that 123 in window.location.href, and parse it with some logic in my-path.tsx.
I hope this is clear. Appreciate anyone who can help or guide me in the right direction!
Of course after writing this all up the answer becomes clear... I tried it, and it works! for the example I was providing, the following redirect would work in your netlify.toml file:
[[redirects]]
from = "/my-path/*"
to = "/my-path"
status = 200
force = true
So it essentially has to match 1:1 with the rules you define in gatsby-node.js.

Call a .json from module.exports

To avoid having to change every emoji from every file whenever I switch an emoji, I decided to place an emojis.json and call the emoji from there.
emojis.json
{
"loading": "<a:loading:847653387343626301>",
"pressf": "<:pressf:862166705911758909>"
}
Exampleping.js
const emoji = require('../emojis.json')
module.exports = {
name: 'ping',
execute(message, args) {
message.channel.send(`${emoji.loading}Pong.`)
}
}
Is this the right way? I'm open to new/better ideas.
Btw it errors: code: 'MODULE_NOT_FOUND',
Well, your approach is correct to a certain extent. Only issue is that you have imported a json file instead of js file and hence it throws an error.
Correct way of achieving this, is having a emojis.js file with your json object exported using module.exports
// emojis.js
module.exports = {
loading: "<a:loading:847653387343626301>",
pressf: "<:pressf:862166705911758909>"
};
// Exampleping.js
const emojis = require('../../emojis.js')
module.exports = {
name: 'ping',
execute(message, args) {
message.channel.send(`${emoji.loading}Pong.`)
}
}
Your code is clean except your import statement is not referring to the emojis.json file. To make it more clear, the script failed to locate the file, which means emojis.json is not located inside the same directory as exampleping.js (require('./emojis.js')).
Based on my experience with Discord bot development, I believe you placed emojis.json in your root directory while exampleping.js is placed inside a directory commonly named "commands". With that being said, all you need is to exist the command directory by adding another . to require().
const emojis = require('../emojis.js');
//instead of ./emojis.json
See HTML File Path

Authentication to serve static files on Next.js?

So, I looked for a few authentication options for Next.js that wouldn't require any work on the server side of things. My goal was to block users from entering the website without a password.
I've set up a few tests with NextAuth (after a few other tries) and apparently I can block pages with sessions and cookies, but after a few hours of research I still can't find how I would go about blocking assets (e.g. /image.png from the /public folder) from non-authenticated requests.
Is that even possible without a custom server? Am I missing some core understanding here?
Thanks in advance.
I did stumble upon this problem too. It took my dumbass a while but i figured it out in the end.
As you said - for auth you can just use whatever. Such as NextAuth.
And for file serving: I setup new api endpoint and used NodeJS magic of getting the file and serving it in pipe. It's pretty similar to what you would do in Express. Don't forget to setup proper head info in your response.
Here is little snippet to demonstrate (typescript version):
import { NextApiRequest, NextApiResponse } from 'next'
import {stat} from "fs/promises"
import {createReadStream, existsSync} from "fs"
import path from "path"
import mime from "mime"
//basic nextjs api
export default async function getFile (req: NextApiRequest, res: NextApiResponse) {
// Dont forget to auth first!1!!!
// for this i created folder in root folder (at same level as normal nextjs "public" folder) and the "somefile.png" is in it
const someFilePath = path.resolve('./private/somefile.png');
// if file is not located in specified folder then stop and end with 404
if (! existsSync(someFilePath)) return res.status(404);
// Create read stream from path and now its ready to serve to client
const file = createReadStream(path.resolve('./private/somefile.png'))
// set cache so its proper cached. not necessary
// 'private' part means that it should be cached by an invidual(= is intended for single user) and not by single cache. More about in https://stackoverflow.com/questions/12908766/what-is-cache-control-private#answer-49637255
res.setHeader('Cache-Control', `private, max-age=5000`);
// set size header so browser knows how large the file really is
// im using native fs/promise#stat here since theres nothing special about it. no need to be using external pckages
const stats = await stat(someFilePath);
res.setHeader('Content-Length', stats.size);
// set mime type. in case a browser cant really determine what file its gettin
// you can get mime type by lot if varieties of methods but this working so yay
const mimetype = mime.getType(someFilePath);
res.setHeader('Content-type', mimetype);
// Pipe it to the client - with "res" that has been given
file.pipe(res);
}
Cheers

How to create and update a text file using React.js?

I am trying to save a variable's data into a text file and update the file every time the variable changes. I found solutions in Node.js and vanilla JavaScript but I cannot find a particular solution in React.js.
Actually I am trying to store Facebook Long Live Access Token in to a text file and would like to use it in the future and when I try importing 'fs' and implementing createFile and appendFile methods I get an error saying Method doesn't exist.
Please help me out. Here is the code below
window.FB.getLoginStatus((resp) => {
if (resp.status === 'connected') {
const accessToken = resp.authResponse.accessToken;
try {
axios.get(`https://graph.facebook.com/oauth/access_token?client_id=CLIENT_id&client_secret=CLIENT_SECRET&grant_type=fb_exchange_token&fb_exchange_token=${accessToken}`)
.then((response) => {
console.log("Long Live Access Token " + response.data.access_token + " expires in " + response.data.expires_in);
let longLiveAccessToken = response.data.access_token;
let expiresIn = response.data.expires_in;
})
.catch((error) => {
console.log(error);
});
}
catch (e) {
console.log(e.description);
}
}
});
React is a frontend library. It's supposed to be executed in the browser, which for security reasons does not have access to the file system. You can make React render in the server, but the example code you're showing is clearly frontend code, it uses the window object. It doesn't even include anything React-related at first sight: it mainly consists of an Ajax call to Facebook made via Axios library.
So your remaining options are basically these:
Create a text file and let the user download it.
Save the file content in local storage for later access from the same browser.
Save the contents in online storage (which could also be localhost).
Can you precise if any of these methods would fit your needs, so I can explain it further with sample code if needed?

Resources