I can't seem to figure out what the problem is. I'm trying to use EvaporateJS to upload files to S3, I'm also using React. Here is what my code looks like:
Blockquote
useEffect(() => {
Evaporate.create({
aws_key: AWS_ACCESS_KEY,
bucket: S3_BUCKET,
awsRegion: 'us-west-1', // s3 region
signerUrl: '/api/videos/signv4_auth',
awsSignatureVersion: '4',
computeContentMd5: true,
cloudfront: true,
cryptoMd5Method: (data) => {
return AWS.util.crypto.md5(data, 'base64');
},
cryptoHexEncodedHash256: (data) => {
return AWS.util.crypto.sha256(data, 'hex');
}
}).then(evaporate => {
console.log(evaporate);
// evaporate.add(); // showing as not a function
});
}, []);
But I get an error message: evaporate.add is not a function. When I inspect the evaporate variable that's being passed with then, it doesn't contain the add function, nor some of the other functions mentioned in documentation. Not sure why it's not working, any help would be highly appreciated.
Console output of evaporate
Error Message
Related
I am creating a project where I need to take a user input - pass it through a function and return the new value to the user - seems simple enough. I am new to async functions and have read everything I possibly can, and can't works out if there's a more fundamental issue I am missing. I will show the basic code, and then what I wish to achieve. I believe the issue, is that I am returning back the status of the function rather than the value, but just can't work it out.
Basic Code:
ipcMain.on('gpt3', (event, args) => {
async function gpt3(args) {
generateResponse('james', 'hello world'); // Takes a user's name & input and recieves a response from a python file.
event.reply('textRecieve', 'hello world'); // Sends 'Hello World' to the user (ipcRenderer 'textRecieve')
}
gpt3(args);
})
async function generateResponse(name, text) {
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
let content = "";
try {
testshell.on('message', function (message) {
console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
return message; // attempting to return the 'Message' from the python file
});
} catch (error) {
console.log("You've f*cked it somewhere my friend");
console.log(error);
}
}
Python Script:
import sys
name = sys.argv[1]
text = sys.argv[2]
print(f'Python File: {name} Text: {text}')
sys.stdout.flush()
Returns: (as expected)
> Executing task: npm run start <
> electron-quick-start#1.0.0 start
> electron .
Python File: james Text: hello world
What I'd Like it to do:
ipcMain.on('gpt3', (event, args) => {
async function gpt3(args) {
message = generateResponse('james', 'hello world'); // Takes a user's name & input and recieves a response from a python file, retunring the message to the 'message' variable.
console.log(message);
event.reply('textRecieve', 'message would send here'); // Sends the 'Message' to the user (ipcRenderer 'textRecieve')
}
gpt3(args);
})
async function generateResponse(name, text) {
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
let content = ""
try {
testshell.on('message', function (message) {
console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
return message; // attempting to return the 'Message' from the python file
});
} catch (error) {
console.log("You've f*cked it somewhere my friend")
console.log(error)
}
return content; // content needs to be message instead due to async nature it returns empty string
}
Returns:
> Executing task: npm run start <
> electron-quick-start#1.0.0 start
> electron .
Promise { '' }
Python File: james Text: hello world
TLDR; I would like to take the 'message' generated through 'generateResponse()' and pass it through to my 'event.reply()'. Instead, I am receiving what I believe to be the status of the Promise. Any help would be greatly appreciated. Thanks
You should resolve the promise first.
ipcMain.on('gpt3', (event, args) => {
async function gpt3(args) {
const message = await generateResponse('james', 'hello world');
console.log(message);
event.reply('textRecieve', 'message would send here'); // Sends the 'Message' to the user (ipcRenderer 'textRecieve')
}
gpt3(args);
})
async function generateResponse(name, text) {
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
let content = ""
try {
testshell.on('message', function (message) {
console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
content = message;
});
} catch (error) {
console.log("You've f*cked it somewhere my friend")
console.log(error)
}
return content; // content needs to be message instead due to async nature it returns empty string
}
Okay, so there were a few problems here... but the main was node.js 'non-ability' to pass variables around when 'asynchronous'. with node.js being new to me, I can't lie and say I was confused. Hopefully, the following link to a great workaround/method and my working code will be able to help someone:
https://stackoverflow.com/a/23667087/10246221
Code:
ipcMain - nested within app.whenReady().
ipcMain.on('gpt3', (event, input) => {
gpt3Async(event, input, function(result) {
event.reply('textRecieve', result);
console.log('gpt3Async: '+ result);
})
})
Code:
Generic 'nested' Function - free-floating around 'main.js' or 'index.js'.
function gpt3Async(event, input, callback) {
console.log('input: ' + input)
let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: ['elliott' ,input]});
testshell.on('message', function (message) {
callback(message);
});
}
Code: Python Script 'text_echo.py' - in my case within a 'python' subdirectory.
import sys
name = sys.argv[1]
text = sys.argv[2]
print(f'Python File: {name} Text: {text}')
#sys.stdout.flush()
sys.stdout.flush()
For anyone working on a project where you need input and output for python scripts, this will help you out. also make sure you turn on the following:
webPreferences: {
//preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
sandbox: false,
},
BUT!, please be aware of the security implications this will have on your code, More info is available here: https://stackoverflow.com/a/57507392 & https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content & much more so do some reading if this is an important project...
Okay, An explainer, or at least something that blew my mind as a beginner... . The way I finally understood it was through the example link:
https://stackoverflow.com/a/23667087/10246221
for some reason, it hadn't clicked with me that functions could be nested within functions like this, all in one line. For someone who is used to JS or node.js this may seem fundamental, but seeing as this is a first-time project to me, and maybe others - if still using python code. Hopefully, this may help!
ipcMain.on('gpt3', (event, input) => { gpt3Async(event, input, function(result) { event.reply('textRecieve', result); console.log('gpt3Async: '+ result);})})
I've finished writing my first Cypress test. Everything is good except I'm struggling to post the result data to a website. Because I want to send the result data and also if any errors occurs the result screenshot to our coworker telegram group.
For the last two days I've tried everything and couldn't find any solution.
I've tried those in my test script (cypress/integration/test.js);
Cypress.on('test:after:run', (test, runnable) => {
console.log('test,runnable', test, runnable)
const details = {
projectKey: Cypress.env('zephyr-project-key'),
testName: test.invocationDetails.relativeFile,
status: test.status,
error: runnable.err.message,
retries: runnable.retries.length,
duration: test.wallClockDuration,
startTime: test.wallClockStartedAt
}
cy.request('POST', 'http://mywebsite.com/notify.php', { body: details })
fetch('http://mywebsite.com/notify.php')
})
Also this didn't work (cypress/plugins/index.js);
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on('after:run', (results) => {
if (results) {
// results will be undefined in interactive mode
console.log(results.totalPassed, 'out of', results.totalTests, 'passed')
fetch('http://mywebsite.com/notify.php');
}
})
}
Edit: This is day 3 and I still couldn't solve this. What I've seen from Cypress help page is that cy.task() calls do not fire in 'test:after:run' event block;
https://github.com/cypress-io/cypress/issues/4823
I've seen some telegram groups who can do what I'm trying to do. All I need is to be able to get the results and post it to my website.
The third parameter to cy.request() is body, you don't have to wrap it.
Cypress.on('test:after:run', (test, runnable) => {
const details = {
projectKey: Cypress.env('zephyr-project-key'),
testName: test.invocationDetails.relativeFile,
status: test.status,
error: runnable.err?.message, // need err?.message if there is no error
retries: runnable.retries.length,
duration: test.wallClockDuration,
startTime: test.wallClockStartedAt
}
cy.request('POST', 'http://mywebsite.com/notify.php', details) // don't wrap details
.then(res => expect(res.status).to.eq(201)) // confirm result
})
I want to use the chrome proxy API. I have this code in my background script but it will not work
const proxyData = []
const fetchProxyData = () => {
axios({
method: "GET",
baseURL: "https://api.getproxylist.com/proxy",
params: {
protocol: "http",
allowsPost: 1,
allowsHttps: 1,
anonimity: "high anonymity"
}
}).then( (response) => {
console.log(response.data)
proxyData.push(response.data)
})
}
fetchProxyData();
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
host: proxyData.ip,
port: proxyData.port
}
}
}
chrome.proxy.settings.set({
value: config,
scope: "regular"
}, () => {
console.log(`proxy configured with data: ${proxyData}`)
})
I get this error in background page console: background.js:55 Uncaught TypeError: Invalid invocation
I've tried with the example provided with the proxy api documentation and the error will not occur. Maybe it's caused by the config object? To set the proxy as you can see in the code, I'm using an ajax call, maybe is this the problem?
is there any fix?
I have also faced the same problem when I find the solution, it was silly mistake.
I had passed string value to port.
Please make sure you are passing integer value to port
Close. Couple things.
One, you need to fetch your data before calling Chrome's proxy API. And two, your getting the properties for your config from the proxyData array, not the JSON object from your axios call.
You need to do something like this:
const proxyData = [];
const fetchProxyData = () => {
axios({
method: "GET",
baseURL: "https://api.getproxylist.com/proxy",
params: {
protocol: "http",
allowsPost: 1,
allowsHttps: 1,
anonimity: "high anonymity"
}
}).then((response) => {
const {data} = response;
proxyData.push(data);
const config = {
mode: "fixed_servers",
rules: {
singleProxy: {
host: data.ip,
port: data.port
}
}
};
chrome.proxy.settings.set({
value: config,
scope: "regular"
}, () => {
console.log(`proxy configured with data: ${data}`)
});
})
};
fetchProxyData();
What's happening with your code...The properties host and port in singleProxy (in config) are being assigned undefined because those properties don't exist in the array proxyData. They exist in the object returned from your axios call (above, data).
The undefined keys caused Chrome to throw an Invalid Invocation error.
For anyone else getting the Invalid Invocation issue, it seems to me the problem usually lies within the config your passing into Chrome. In particular the types of each key.
In my case, I was passing in the port as a string when it needed to be a number.
I have a csv file in storage(firebase-admin), and In my cloud function tried to create a readable stream in it
my code is something like this.
const customErrObject = {any: false, messag: []};
storageFile.createReadStream().pipe(fastCsv({headers: false,})
.on("data", async data => {
try {
// retrieve a user here from `firestore`
console.log('user.empty', user.empty);
// more codes
// retrieve kyc data
console.log('kyc.empty', kyc.empty);
// create notification
} catch (e) {
customErrObject.any = true;
customErrObject.message.push(e);
}
}
.on("end", () => {
console.log('customErrObject on end', customErrObject);
if(customerErrObject.any) //return 400 with error messages
else // return 200
})
now during runtime i would expect it to follow like this
user.empty false
kyc.empty false
customerErrObject on end, object log here....
but to my surprise this showed in the logs
user.empty false
customerErrorObject on end, object log here...
kyc.empty false
it really confused me as to why it didn't follow my expected sequence.
any help would be great!
I might just be missing something simple, but I've never had this error before and I don't think I edited it enough to cause this problem since it was last functional. The code block below keeps giving me this error at the top of the file:
(node:17592) UnhandledPromiseRejectionWarning: TypeError: client.catch is not a function
I have specified client = new Discord.Client();
The other issue I am having is that I am trying to get the role that is being made by the bot to be the name of the two players/users (challenger vs target format) after the target has accepted the challenge posed by the challenger. It just makes a role named "new role" instead. Any help with either of these problems?
if (message.channel.id === '541736552582086656') return challenged.send("Do you accept the challenge? Please reply with 'accept' or 'deny'.")
.then((newmsg) => {
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 150000,
errors: ['time'],
}).then((collected) => {
// Grabs the first (and only) message from the collection.
const reply = collected.first();
if (reply.content === 'accept'){
reply.channel.send(`You have ***accepted *** the challenge from ${challenger}. Please wait while your battlefield is made...`);
message.author.send(`${target} has accepted your challenge! Please wait while the channel is made for your brawl...`)
var server = message.guild;
var permsName = `${target} vs ${challenger}`;
var name = `${target} vs ${challenger}`;
message.guild.createRole({
data: {
name: permsName,
hoist: true,
color: "#00fffa",
permissions: [] }
}).then(role => {
target.addRole(data, permsName)
challenger.addRole(role, permsName)
// client.catch error occurring below
.catch(error => client.catch(error))
}).catch(error => client.catch(error)).then(
server.createChannel(name, "text")).then(
(channel) => {
channel.setParent("542070913177485323")
})
} else if (reply.content === 'deny') {
reply.channel.send("You have ***denied *** the challenge.")
} else {
reply.channel.send("Your response wasn't valid.");
}
})
})
}
module.exports.help = {
name: "challenge"
}
I have tried looking up the problem and I don't see anything that has helped so far with either issue. They might be related since the catch is after the add role part? Thanks in advance for the help!
Curious if there's a template you copied for this bot? The Discord.Client object does not have any catch method, so calling client.catch() is not going to work.
To clarify, this is fine:
challenger.addRole(role, permsName)
.catch(error => /* do something with this error */);
What can you do with the error? You could print it to console, I suppose:
challenger.addRole(role, permsName)
.catch(error => console.error(error));
But you can't call client.catch(error), because that's not a real method - you can check out the docs for the Client object here.
Regarding the role name, you just have a small error: you don't want to wrap your options object in { data: }, your options object is the data. Just pass them in directly, like so:
message.guild.createRole({
name: permsName,
hoist: true,
color: "#00fffa",
permissions: []
}).then(role => {
Hope that helps!