I'm trying to create a meme command with my bot that uses Jimp to add text onto an image the user sends with the command. It works, but whenever something doesn't go to plan (e.g. someone not sending the image, someone not sending the text that needs to be applied to the image, etc.) it gets an error and crashes my bot. Here's my code:
case "meme":
const [topText, bottomText] = args.slice(1).join(" ").split(",");
msg.channel.startTyping();
if (!args[1]) msg.channel.send("You need to give the text you want to apply to the image!");
Jimp.read(msg.attachments.first(), (err, lenna) => {
Jimp.loadFont(Jimp.FONT_SANS_128_WHITE).then(font => {
if (err) console.log(err);
lenna
.resize(1280, 1080)
.quality(100) // set quality
.print(font, 75, 20, {
text: topText,
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE
}, 1100)
.print(font, 75, 900, {
text: bottomText,
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE
}, 1100)
.write("./tmp/" + msg.author.id + ".jpg"); // save
});
});
for (i = 0; i < (1); i++) {
setTimeout(function () {
msg.channel.send({
files: ["./tmp/" + msg.author.id + ".jpg"]
})
msg.channel.stopTyping();
for (i = 0; i < (1); i++) {
setTimeout(function () {
fs.unlinkSync("./tmp/" + msg.author.id + ".jpg")
}, 3 * 1000)
}
}, 3 * 1000)
}
break;
Error:
(node:32440) UnhandledPromiseRejectionWarning: Error: No matching constructor overloading was found. Please see the docs for how to call the Jimp constructor.
at Jimp.throwError (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\utils\dist\index.js:35:13)
at new Jimp (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\core\dist\index.js:502:85)
at _construct (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#babel\runtime\helpers\construct.js:19:21)
at C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\core\dist\index.js:1016:32
at new Promise (<anonymous>)
at Function.Jimp.read (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\core\dist\index.js:1015:10)
at Client.<anonymous> (C:\Users\lqshkiwi\Desktop\Discord Bot\index.js:53:18)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
(node:32440) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:32440) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:32440) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat 'C:\Users\lqshkiwi\Desktop\Discord Bot\tmp\652940695585292299.jpg'
(node:32440) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
internal/fs/utils.js:230
throw err;
^
Error: ENOENT: no such file or directory, unlink './tmp/652940695585292299.jpg'
at Object.unlinkSync (fs.js:1053:3)
at Timeout._onTimeout (C:\Users\lqshkiwi\Desktop\Discord Bot\index.js:80:32)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
errno: -4058,
syscall: 'unlink',
code: 'ENOENT',
path: './tmp/652940695585292299.jpg'
}
Without know what specific error you're trying to handle against, the best way is to wrap your entire section of code in a try/catch. In the catch portion, you can console.warn the error and hopefully use the logs to debug this with more details.
You forgot to add a return statement to exit the logic if the user didn't follow the proper commands. When the user didn't provide the argument, I'm guessing msg.attachments.first() returns undefined which is why Jimp errors.
if (!args[1]) {
return msg.channel.send("You need to give the text you want to apply to the image!");
}
try { // it's good to have a try catch when dealing with asynchronous code
Jimp.read(msg.attachments.first(), (err, lenna) => {
...
Related
I am facing a very strange issue. As soon as I updated my node to node 16 from 14 my tests stopped working and I get a complain like this:
Error:
at /src/api/v1/datastore/SearchesDatastore.ts:109:25
at processTicksAndRejections (node:internal/process/task_queues:96:5)
And my code the line it shows is:
public async isRemovalNeeded() {
try {
this._logger.debug({message: `Checking if any design doc removal needed.`});
const designDocsName = getDesignDocLists(this.designDocsPath);
const allDesignDocs = await this._db.list({
include_docs: true,
startkey: "_design/",
endkey: "_design0"
});
const toBeRemoved = allDesignDocs.rows.
filter((row: any) => !designDocsName.includes(row.id.replace("_design/", "")));
return toBeRemoved.length > 0;
} catch (e) {
this._logger.warn({ message: "Failed to retrieve list of documents." });
this._logger.debug({ message: `Error: ${e}` });
throw new Error(errors.ERROR_GETTING_DB_LIST.message);
}
}
just to test I ran the same thing with node 14 and it passed with this warning
(node:22352) UnhandledPromiseRejectionWarning: Error:
at src/api/v1/datastore/SearchesDatastore.ts:128:19
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:22352) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 43)
(node:22352) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
so I am thinking it is because of node16 being strict for unhandled promises but in my code I Cannot see any unhandled promise so I am confused
any help is appreciated
Also this is how I call it :
try {
this._loggingService.debug({message: `Checking to see if current pod is a leader`});
const isLeader: any = await this._consensusService.isLeader();
this._loggingService.debug({message: `current Pod checked for leading and isLeader is: ${isLeader}`});
const isRemovalNeeded = await this._searchesDatastore.isRemovalNeeded();
this._loggingService.debug({message: `check occurred to make sure if design doc removal needed and isRemovalNeeded is: ${isRemovalNeeded}`});
const isUpdateNeeded = await this._searchesDatastore.isUpdateNeeded();
this._loggingService.debug({message: `check occurred to make sure if design doc update needed and isUpdateNeeded is: ${isUpdateNeeded}`});
if (!isRemovalNeeded && !isUpdateNeeded) {
shouldWait = false;
this._loggingService.info({ message: "All documents are up to date" });
} else if (isLeader) {
isRemovalNeeded && await this._searchesDatastore.cleanRemovedDesignDocs();
isUpdateNeeded && await this._searchesDatastore.syncAllDesignDocs();
shouldWait = false;
} else {
this._loggingService.info({ message: "Design docs are not synced but this pod is not a leader. We need to wait for leader pod to take do the house keeping first." });
}
if (!shouldWait) {
this._loggingService.debug({message: `datastorewatcher is done and we are proceeding to the next step...`});
this.watcherFailureCount= 1;
resolve(true);
break;
} else {
this._loggingService.debug({message: `datastorewatcher is not done. We will try again after ${config.databaseWatcher.interval}.`})
await this.sleep(config.databaseWatcher.interval);
}
} catch (e) {
this.watcherFailureCount++;
if(this.watcherFailureCount> config.databaseWatcher.toleranceLevel){
this._loggingService.warn({message: "App crashed and pod will die soon"})
reject(e);
break;
}
const nextIntervalToRun: number= config.databaseWatcher.interval * this.watcherFailureCount;
this._loggingService.warn({ message: `DataStoreWatcher failed but still failure is less than tolerance threshold: ${config.databaseWatcher.toleranceLevel}. Watcher will run again in ${nextIntervalToRun}. ${e}` });
await this.sleep(nextIntervalToRun);
}
I was going through the flashloan course and I was having trouble with section 13 Pull Kyber Prices.
I am getting this error
(node:43614) UnhandledPromiseRejectionWarning: Error: This contract object doesn't have address set yet, please set an address first
Here is my full code:
require('dotenv').config();
const Web3 = require('web3');
const abis = require('./abis');
const { mainnet: addresses } = require('./addresses');
const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.INFURA_URL)
);
const kyber = new web3.eth.Contract(
abis.kyber.kyberNetworkProxy,
addresses.kyber.kyberNetworProxy
);
const AMOUNT_ETH = 100;
const RECENT_ETH_PRICE = 2400;
const AMOUNT_ETH_WEI = web3.utils.toWei(AMOUNT_ETH.toString());
const AMOUNT_DAI_WEI = web3.utils.toWei((AMOUNT_ETH * RECENT_ETH_PRICE).toString());
web3.eth.subscribe('newBlockHeaders')
.on('data', async block => {
console.log('New Block Recieved # ' + block.number);
const kyberResult = await Promise.all([
kyber
.methods
.getExpectedRate(
addresses.tokens.dai,
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
AMOUNT_DAI_WEI
)
.call(),
kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
AMOUNT_ETH_WEI
)
.call()
]);
console.log(kyberResults);
})
.on('error', error => {
console.log(error);
});
The error that I am getting is this:
(node:43614) UnhandledPromiseRejectionWarning: Error: This contract object doesn't have address set yet, please set an address first.
at Object.ContractNoAddressDefinedError (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-helpers/lib/errors.js:122:16)
at Object._processExecuteArguments (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-eth-contract/lib/index.js:728:22)
at Object._executeMethod (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-eth-contract/lib/index.js:744:68)
at Subscription.<anonymous> (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/run-arbitrage.js:34:18)
at Subscription.emit (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/eventemitter3/index.js:181:35)
at /Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-subscriptions/lib/subscription.js:242:35
at Array.forEach (<anonymous>)
at Object.callback (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-subscriptions/lib/subscription.js:234:28)
at WebsocketProvider.data (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-requestmanager/lib/index.js:99:73)
at WebsocketProvider.emit (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/eventemitter3/index.js:181:35)
at /Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-providers-ws/lib/index.js:104:19
at Array.forEach (<anonymous>)
at WebsocketProvider._onMessage (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-providers-ws/lib/index.js:102:69)
at W3CWebSocket._dispatchEvent [as dispatchEvent] (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/yaeti/lib/EventTarget.js:115:12)
at W3CWebSocket.onMessage (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/websocket/lib/W3CWebSocket.js:234:14)
at WebSocketConnection.<anonymous> (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/websocket/lib/W3CWebSocket.js:205:19)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:43614) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:43614) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I believe that the problem is lines 31 and 38 after the method ".getExpectedRate" I am just not sure what to switch those addresses that he provided out with.
cant get the hrefs from my web element using .getAttribute("href"). I can get it to work on single variable but not when its looping through my array.
const {Builder, By, Key, until} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to webscraper.io
await driver.get('https://webscraper.io/test-sites');
// Scrape links
let links = await driver.findElements(By.xpath('//*[#class="row test-site"]/div/h2/a'))
// loop through links and print
console.log('\nFound ' + links.length + ' Links total.\n')
for (let index = 0; index < links.length; index++) {
console.log(links[index].getAttribute("href"));
}
}
finally{
driver.quit();
}
})();
I get the following error:
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
(node:81217) UnhandledPromiseRejectionWarning: Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:54431
at ClientRequest.<anonymous> (/Users/eric/Dropbox/Javascript/node_modules/selenium-webdriver/http/index.js:262:15)
at ClientRequest.emit (events.js:315:20)
at Socket.socketErrorListener (_http_client.js:469:9)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:81217) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
added await to the console.log line and it worked.
console.log(await links[index].getAttribute("href"));
I have a script where you need to answer to the bot with yes (da in the script) or no (nu in the script) and when I run the script on discord it tells me that filter is not a function. I have to mention that I am a beginner.
The script is this:
module.exports = {
name: 'moneda',
description: 'mai usor de luat o decizie',
execute(message, args){
let decizii = [
"Fata",
"Spate",
]
let decizie = decizii[Math.floor(Math.random() * (decizii.length))]
message.reply(`Ti-a picat ${decizie}`);
let decizii1 = [
"Fata",
"Spate",
]
let decizie1 = decizii1[Math.floor(Math.random() * (decizii1.length))]
message.channel.send('Mai vrei sa incerci odata?').then(async (start) => {
message.channel.awaitMessage(filter, { maxMatches: 1, time: 60000, errors: ['time']}).then(async (collected) => {
if(collected.first().content === 'da') {message.channel.send(decizie1)} else if (collected.first().content === 'nu') {return}
})
})
}
}
The error is this:
(node:8340) UnhandledPromiseRejectionWarning: ReferenceError: filter is not defined
at C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\moneda.js:18:42
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8340) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block, or by rejecting a promise which
was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the
CLI flag `--unhandled-rejections=strict` (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:8340) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,
promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
filter is not defined, means that you have to create a filter.
This is an example filter, for your problem:
let filter = m => m.author.id === message.author.id;
I am trying to build some code but I get those two errors:
(node:12909) UnhandledPromiseRejectionWarning: NoSuchSessionError: Tried to run command without establishing a connection
at Object.throwDecodedError (/home/matthew/node_modules/selenium-webdriver/lib/error.js:550:15)
at parseHttpResponse (/home/matthew/node_modules/selenium-webdriver/lib/http.js:563:13)
at Executor.execute (/home/matthew/node_modules/selenium-webdriver/lib/http.js:489:26)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:12909) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12909) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:12909) UnhandledPromiseRejectionWarning: NoSuchSessionError: Tried to run command without establishing a connection
at Object.throwDecodedError (/home/matthew/node_modules/selenium-webdriver/lib/error.js:550:15)
at parseHttpResponse (/home/matthew/node_modules/selenium-webdriver/lib/http.js:563:13)
at Executor.execute (/home/matthew/node_modules/selenium-webdriver/lib/http.js:489:26)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:12909) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
function review_balance() {
if (balance_amount > 0) {
console.log("This address has " + balance_amount + "Bitcoin");
}
else {
console.log("0 Bitcoins!");
}
}
async function searching() {
console.log("Waiting for address to be scanned on the Bitcoin blockchain...");
const result = await review_balance();
console.log(result);
}
searching();
driver.close();
This is the part of the program that is the most important and contains the problem. Can anyone give me any advice? I would be really thankful.
Solution using Promise:
let check_balance = new Promise((resolve, reject) => {
driver.get("https://explorer.bitcoin.com/btc/address/" + address);
let balance_amount = driver.findElement(webdriver.By.className("amount")).getText();
if (balance_amount > 0) {
resolve('This wallet has ' + balance_amount + ' Bitcoins.');
}
else {
reject('0 Bitcoins!');
}})check_balance.then((message) => {
console.log(message);}).catch((message) => {
console.log(message);}) setTimeout(function () {
driver.quit();}, 8000);