So I am trying to create a command that allows a user to enter on or off duty. I am planning to create a panel later displaying who is on or off duty. But I am having trouble updating the value of in the config.json file which corresponds to the staff ID
I am checking the users ID and if it already exists in the config.json file the bot won't write down the ID again
const { Util } = require('discord.js');
const fs = require('fs');
const path = require('path');
module.exports = {
config:{
name:'test'
},
run: async(bot, message, args) => {
const staffMemberID = message.member.id;
function jsonRead(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (err, content) => {
if (err) {
reject(err);
} else {
try {
resolve(JSON.parse(content));
} catch (err) {
reject(err);
}
}
});
});
}
function jsonWrite(filePath, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, JSON.stringify(data), (err) => {
if (err) {
reject(err);
}
resolve(true);
});
});
}
const filePath = path.resolve(`${__dirname}/../storage/config.json`);
if(bot.config.status.find(u => staffMemberID)) {
try {
const config = await jsonRead(filePath);
config.status.push({
value:'On Duty',
});
jsonWrite(filePath, config);
message.channel.send(`Success. ${config.status}`);
} catch (err) {
console.log(err);
}
} else {
try {
const config = await jsonRead(filePath);
config.status.push({
name:staffMember,
value:'On Duty',
});
jsonWrite(filePath, config);
message.channel.send(`Success. ${config.status}`);
} catch (err) {
console.log(err);
}
}
}
}
Related
I want to be able to call "setUser", but it's out of scope for some reason. This is in a MobX store that I've created. I'm sure it's something I'm doing fundamentally wrong, but I don't know what it is. Here's the code:
private setUser = (user: UserType) => {
this.userRegistry.set(user.Username, user);
}
loadUsersFromPoolGroups = () => {
this.loadingInitial = true;
try {
var congitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
const USER_POOL_ID = 'us-east-2_kWOEamV6i';
var params = {
UserPoolId: USER_POOL_ID
}
congitoidentityserviceprovider.listGroups(params, function(err, data) {
if (err) console.log(err, err.stack);
else {
data.Groups.forEach(group => {
var params = {
GroupName: group.GroupName,
UserPoolId: USER_POOL_ID
}
congitoidentityserviceprovider.listUsersInGroup(params, function(err1, data1) {
if (err1) console.log(err1, err1.stack);
else {
data1.Users.forEach((user) => {
this.setUser(user);
})
}
})
})
}
});
} catch (error) {
console.log('error loading users from pool groups', error)
}
}
I'm doing a similar thing in a different store with no issues.
private setSubmittal = (submittal: Submittal) => {
this.submittalRegistry.set(submittal.submittalId, submittal);
}
loadSubmittals = async () => {
this.loadingInitial = true;
try {
const submittals = await agent.Submittals.list();
submittals.data.forEach((submittal: Submittal) => {
this.setSubmittal(submittal);
})
this.setLoadingInitial(false);
} catch (error) {
console.log(error);
this.setLoadingInitial(false);
}
}
I expected to be able to call setUser and it won't let me.
I'm trying to follow run a cypress test with next.js and nock. Based on other examples and following the video, I tried to mock a simple GET request. However, my test fails on the cy.request as it makes an actual call instead of the mock call.
index.js
const nock = require('nock');
const http = require('http');
const next = require('next');
const injectDevServer = require('#cypress/react/plugins/next');
// start the Next.js server when Cypress starts
module.exports = async (on, config) => {
if (process.env.CUSTOM_SERVER == 'false') {
injectDevServer(on, config);
} else {
await startCustomServer(on, config);
}
return config;
};
async function startCustomServer(on, config) {
config.supportFile = false;
const app = next({ dev: true });
const handleNextRequests = app.getRequestHandler();
await app.prepare();
const customServer = new http.Server(async (req, res) => {
return handleNextRequests(req, res);
});
await new Promise((resolve, reject) => {
customServer.listen(3000, (err) => {
if (err) {
return reject(err);
}
console.log('> Ready on http://localhost:3000');
resolve();
});
});
// register handlers for cy.task command
on('task', {
clearNock() {
nock.restore();
nock.cleanAll();
return null;
},
async nock({ hostname, method, path, statusCode, body }) {
nock.activate();
console.log(
'nock will: %s %s%s respond with %d %o',
method,
hostname,
path,
statusCode,
body
);
// add one-time network stub like
method = method.toLowerCase();
nock(hostname)[method](path).reply(statusCode, body);
return null;
},
});
}
my-test.spec.js
describe('my-test', () => {
beforeEach(() => {
cy.task('clearNock');
})
it('execute', () => {
cy.task('nock', {
hostname: 'https://localhost:3000',
method: 'GET',
path: '/myapi/api/layout',
statusCode: 200,
body: {
id: 'NmbFtH69hFd',
status: 200,
success: true
}
})
cy.request(
'https://localhost:3000/myapi/api/layout/'
).as('API'); // <-- Fails here with error
cy.get('API').then((response) => {
assert.exists(response.success);
});
});
});
I dont know much of javaScript and i wanted to make a bot from a youtube tutorial. Now the video said to type this:
(async () => {
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
}
} catch (err) {
if (err) console.error(err);
}
})
Inside the client.once("ready",
So it turned out something like this:
client.once("ready", () => {
console.log("Bot is online.");
const CLIENT_ID = client.user.id;
const rest = new REST({
version: "9"
}).setToken(process.env.TOKEN);
(async () => {
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
}
} catch (err) {
if (err) console.error(err);
}
})
});
Now as you can see it says that if it finds client id it should type on console "Locally" to see if it works. But the terminal is like it ignores the whole async it just says that the bot is online nothing for the commands. What did i do wrong
Instead of defining a separate asynchronous function inside the ready handler function, why not just make the ready handler function itself asynchronous? Here's an example:
client.once("ready", async () => {
console.log("Bot is online.");
const CLIENT_ID = client.user.id;
const rest = new REST({
version: "9"
}).setToken(process.env.TOKEN);
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
} catch (err) {
if (err) console.error(err);
}
});
That should allow the async function to run.
EDIT
Your if statements were slightly incorrect. You are checking if process.env.ENV equals production, and else, you are once again checking if it equals production. I've fixed that in this answer.
nestjs controller.ts
#Patch(':id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
#Body('shippingAddr') addrShipping: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling, addrShipping);
return null;
}
nestjs service.ts
async updateProduct(
addressId: string,
addrBilling: boolean,
addrShipping: boolean,
) {
const updatedProduct = await this.findAddress(addressId);
if (addrBilling) {
updatedProduct.billingAddr = addrBilling;
}
if (addrShipping) {
updatedProduct.shippingAddr = addrShipping;
}
updatedProduct.save();
}
there is no problem here. I can patch in localhost:8000/address/addressid in postman and change billingAddr to true or false.the backend is working properly.
how can i call react with axios?
page.js
const ChangeBillingAddress = async (param,param2) => {
try {
await authService.setBilling(param,param2).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
return....
<Button size='sm' variant={data.billingAddr === true ? ("outline-secondary") : ("info")} onClick={() => ChangeBillingAddress (data._id,data.billingAddr)}>
auth.service.js
const setBilling = async (param,param2) => {
let adressid = `${param}`;
const url = `http://localhost:8001/address/`+ adressid ;
return axios.patch(url,param, param2).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}
I have to make sure the parameters are the billlingddress field and change it to true.
I can't make any changes when react button click
Since patch method is working fine in postman, and server is also working fine, here's a tip for frontend debugging
Hard code url id and replace param with hard coded values too:
const setBilling = async (param,param2) => {
// let adressid = `${param}`;
const url = `http://localhost:8001/address/123`; // hard code a addressid
return axios.patch(url,param, param2).then((response) => { // hard code params too
console.log(response); // see console result
if (response.data.token) {
// localStorage.setItem("user", JSON.stringify(response.data));
}
// return response.data;
})
}
now it worked correctly
#Patch('/:id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling);
return null;
}
const ChangeBillingAddress = async (param) => {
try {
await authService.setBilling(param,true).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
const setBilling= async (param,param2) => {
let id = `${param}`;
const url = `http://localhost:8001/address/`+ id;
return axios.patch(url,{billingAddr: param2}).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}
I am using an opensource react project and getting the following error.
does not provide an export named 'default'
Here is the .js file causing the issue.
import { RevAiStreamingClient, AudioConfig } from 'revai-node-sdk';
module.exports = class StreamingClient {
constructor(accessToken, io) {
console.log('Loading Streaming Client');
this.accessToken = accessToken;
this.io = io;
}
start() {
this.revAiStreamingClient = new RevAiStreamingClient(this.accessToken, new AudioConfig('audio/x-wav'));
this.revAiStreamingClient.on('close', (code, reason) => {
console.log(`Connection closed, ${code}: ${reason}`);
});
this.revAiStreamingClient.on('httpResponse', (code) => {
console.log(`Streaming client received http response with code: ${code}`);
});
this.revAiStreamingClient.on('connectFailed', (error) => {
console.log(`Connection failed with error: ${error}`);
});
this.revAiStreamingClient.on('connect', (connectionMessage) => {
console.log(`Connected with job id: ${connectionMessage.id}`);
this.io.emit('streaming-connected', connectionMessage);
});
this.revStream = this.revAiStreamingClient.start();
this.revStream.on('data', (data) => {
this.io.emit('transcript', data);
});
}
end() {
this.revStream = null;
this.revAiStreamingClient.end();
}
stream(data) {
console.log('streaming data ....');
this.revStream && this.revStream.write(data);
}
};
UPDATE:
Fixed it.
import { RevAiStreamingClient, AudioConfig } from 'revai-node-sdk';
class StreamingClient {
constructor(accessToken, io) {
console.log('Loading Streaming Client');
this.accessToken = accessToken;
this.io = io;
}
start() {
this.revAiStreamingClient = new RevAiStreamingClient(this.accessToken, new AudioConfig('audio/x-wav'));
this.revAiStreamingClient.on('close', (code, reason) => {
console.log(`Connection closed, ${code}: ${reason}`);
});
this.revAiStreamingClient.on('httpResponse', (code) => {
console.log(`Streaming client received http response with code: ${code}`);
});
this.revAiStreamingClient.on('connectFailed', (error) => {
console.log(`Connection failed with error: ${error}`);
});
this.revAiStreamingClient.on('connect', (connectionMessage) => {
console.log(`Connected with job id: ${connectionMessage.id}`);
this.io.emit('streaming-connected', connectionMessage);
});
this.revStream = this.revAiStreamingClient.start();
this.revStream.on('data', (data) => {
this.io.emit('transcript', data);
});
}
end() {
this.revStream = null;
this.revAiStreamingClient.end();
}
stream(data) {
console.log('streaming data ....');
this.revStream && this.revStream.write(data);
}
}
export default StreamingClient;
I need to see more of the error message to understand but best guess is that somewhere in your code it says export default instead of export default insert component name.