I got this code that it seems to be working but it does not.
let REMOTE_SSH_HOST = '190.444.01.75:55554'
let REMOTE_SSH_USERNAME = 'olec'
let REMOTE_SSH_PASSWORD = 'm3uW4jkbaEwVChklFszpbm4'
const Client = require('ssh2-sftp-client');
const sshConfig = {
host: process.env.REMOTE_SSH_HOST,
//port: 22,
username: process.env.REMOTE_SSH_USERNAME,
password: process.env.REMOTE_SSH_PASSWORD,
readyTimeout: 99999,
};
let sftp = new Client();
async function Read(directory) {
console.log('Read(' + directory + ')');
const result = await sftp.list(directory);
for(const sub of result) {
if (sub['type'] === 'd') {
await Read(directory + '/ ' + sub['name']);
}
}
}
async function main(directory) {
try{
const myList = await sftp.list(directory);
}catch(err){console.log(err)}//NEVER forget to catch
finally {
console.log('Closing session...');
await sftp.end();
console.log('Session closed.');
}
}
console.log('Application started');
main('/home/user/path').then(r => {
console.log('Application ended.');
});
I get the error message of:
(Use node --trace-warnings ... to show where the warning was created)
(node:16240) 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: 5)
(node:16240) [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 think you might need something like
const sftp = new Client();
await sftp.connect({
host: hostAddress,
username: '...',
privateKey: ...,
});
The issue is you are using environment variables where you have set consts. (also you are setting consts as lets... don't ever use a let where something will never change.
const Client = require('ssh2-sftp-client');
const REMOTE_SSH_HOST = '190.444.01.75'
const REMOTE_SSH_PORT = '55554';
const REMOTE_SSH_USERNAME = 'olec'
const REMOTE_SSH_PASSWORD = 'm3uW4jkbaEwVChklFszpbm4'
const sshConfig = {
host: REMOTE_SSH_HOST,
port: REMOTE_SSH_PORT,
username: REMOTE_SSH_USERNAME,
password: REMOTE_SSH_PASSWORD,
readyTimeout: 99999,
};
Thnx gonna try this and get back to you!
There are a series of errors on your script that are causing the issue. The main one is that you are not handling errors in your async code. You should add a catch chain function to your main call because, even though you are using a try/catch clause inside your main function, it doesn't consider the code that runs inside the finally block.
On the other hand, your code seems to be failing because you are running sftp.list before running sftp.connect.
There are a couple of minor errors that could potentially cause problems in your script:
The address 190.444.01.75 is not a valid IPv4 address.
You should provide default values when reading env variables where they make sense.
You are not really using the Read function yet, but I would suggest you name functions in lower case.
You are declaring the variable of the for-of loop inside the Read function with const. It would be best to use let instead since the engine will update it on each iteration.
Here is a modified example of your script that works:
const Client = require('ssh2-sftp-client')
/**
* Global variables
*/
const SSH_CONFIG = {
host : process.env.REMOTE_SSH_HOST || '190.44.1.75:55554',
port : process.env.REMOTE_SSH_PORT || 22,
username : process.env.REMOTE_SSH_USERNAME || 'olec',
password : process.env.REMOTE_SSH_PASSWORD,
readyTimeout: 99999,
}
const ROOT = process.env.ROOT || '/home/user/path'
/**
* Constructors
*/
const sftp = new Client()
/**
* Main
*/
console.log("Application Started!")
main(ROOT)
.then ((response) => console.log(response))
.catch((err) => console.error(err))
/**
* Functions
*/
async function main(directory) {
let myList
try {
await sftp.connect(SSH_CONFIG)
return await sftp.list(directory)
} catch(err) {
console.error(err)
} finally {
console.log('Closing session...')
await sftp.end()
console.log('Session closed.')
}
}
And here is how you would call it:
env REMOTE_SSH_HOST=10.0.0.10 \
env REMOTE_SSH_USERNAME=conatel \
env REMOTE_SSH_PASSWORD=C0n4t3lC0n4t3l \
env REMOTE_SSH_PORT=22 \
env ROOT=/home/conatel \
node ssh.js
Related
I am trying to export database properties stored in properties file from Javascript module. By the time I read database properties file, Javascript file is already exported and data properties appear undefined wherever I use in other modules.
const Pool = require('pg').Pool;
const fs = require('fs')
const path = require('path');
class DbConfig {
constructor(dbData) {
this.pool = new Pool({
user: dbData['user'],
host: dbData['host'],
database: dbData['database'],
password: dbData['password'],
max: 20,
port: 5432
});
}
}
function getdbconf() {
const dbData = {};
fs.readFile("../../db_properties.txt"), 'utf8', (err, data) => {
if (err) {
console.error(err)
return
}
// dbData = {"user":"postgres", "password": "1234"...};
return dbData;
});
}
let db = new DbConfig(getdbconf());
let dbPool = db.pool;
console.log("dbpool : -> : ",dbPool); // username and password appear undefined
module.exports = { dbPool };
Is there a way to read data before exporting data from Javascript module?
Usually database config or any other sensitive info is read from a .env file using dotenv .
Or
you could also provide env from command line itself like
DB_HOST=127.0.0.1 node index.js
inside your index.js
console.log(process.env.DB_HOST)
Please create a new file (connection-pool.js) and paste this code:
const { Pool } = require('pg');
const poolConnection = new Pool({
user: 'postgresUserName',
host: 'yourHost',
database: 'someNameDataBase',
password: 'postgresUserPassword',
port: 5432,
});
console.log('connectionOptions', poolConnection.options);
module.exports = poolConnection;
For use it, create a new file (demo-connection.js) and paste this code:
const pool = require('./connection-pool');
pool.query('SELECT NOW();', (err, res) => {
if (err) {
// throw err;
console.log('connection error');
return;
}
if (res) {
console.log(res.rows);
pool.end();
}
});
This is an alternative option 🙂
Exporting the result of async calls
To export values which have been obtained asynchronously, export a Promise.
const fs = require('fs/promises'); // `/promise` means no callbacks, Promise returned
const dbDataPromise = fs.readFile('fileToRead')); //`readFile` returns Promise now
module.exports = dbDataPromise;
Importing
When you need to use the value,
const dbDataPromise = require('./dbdata');
async init() {
const dbData = await dbDataPromise;
}
//or without async, using Promise callbacks
init() {
dbDataPromise
.then(dbData => the rest of your code that depends on dbData here);
}
Current code broken
Please note that your current code, as pasted above, is broken:
function getdbconf() {
const dbData = {};
fs.readFile("../../db_properties.txt"), 'utf8', (err, data) => {
//[...] snipped for brevity
return dbData;
});
}
fs.readFile "returns" dbData, but there is nothing to return to, since you are in a callback which you did not call yourself. Function getdbconf returns nothing.
The line that says let db = new DbConfig(getdbconf()); will NOT work. It needs to be inside the callback.
The only way to avoid putting all of your code inside the callback (and "flatten" it) is to use await, or to use readFileSync
Avoiding the issue
Using environment variables
Suhas Nama's suggestion is a good one, and is common practice. Try putting the values you need in environment variables.
Using synchronous readFile
While using synchronous calls does block the event loop, it's ok to do during initialization, before your app is up and running.
This avoids the problem of having everything in a callback or having to export Promises, and is often the best solution.
I am trying to add data to my firestore collection via firebase cloud functions. However, when executing the function the following error appears.
My cloud function code is:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const Firestore = require("#google-cloud/firestore");
const PROJECTID = "[...]";
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true,
});
exports.createNewChat = functions.region("europe-west1")
.https.onRequest((request, response) => {
console.log("!!!!!!");
console.log("THe BodY: " + request);
console.log("THe BodY: " + request.rawBody);
console.log("THe BodY: " + request.body);
try {
const groupName = request.body.groupName;
const members: string[] = request.body.members;
firestore.collection("chats").add({
groupName: groupName,
members: members,
lastMessage: new Date(),
messages: [],
}).then((doc: any) => {
const chatId = doc.id;
members.forEach((member) => {
firestore.collection("myChats/" + member).add({
chatKey: chatId,
});
});
return response.status(200).send(doc);
});
} catch (e) {
functions.logger.log("catch clause " + e);
response.status(500).send(e);
}
});
My postman request looks like this:
Header: Content-Type -> application/json
Body (raw, json):
{
"groupName": "someGroupName",
"members": [
"123321aklslasl"
]
}
The exception which is thrown is:
! Google API requested!
URL: "https://oauth2.googleapis.com/token"
Be careful, this may be a production service.
(node:23224) UnhandledPromiseRejectionWarning: Error: 7 PERMISSION_DENIED: Permission denied on resource project [...].
at Object.callErrorFromStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\call.js:31:26)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client.js:179:52)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client-interceptors.js:336:141)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client-interceptors.js:299:181)
at E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\call-stream.js:145:78
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Caused by: Error
at WriteBatch.commit (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\write-batch.js:414:23)
at DocumentReference.create (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\reference.js:291:14)
at CollectionReference.add (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\reference.js:1967:28)
at E:\Workspaces\cloudFunctions\functions\lib\index.js:39:39
at C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:560:16
at runFunction (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:533:15)
at runHTTPS (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:559:11)
at handler (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:479:23)
at Layer.handle [as handle_request] (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\express\lib\router\route.js:137:13)
(node:23224) 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(). T
o 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: 3)
(node:23224) [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.
In a Cloud Function for Firebase you should use the Admin SDK for Node.js and not the standard JS SDK.
In addition, you need to use Promise.all() to execute in parallel the calls to the asynchronous add() method in the forEach() loop.
So the following set of adaptations should solve your problem:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
exports.createNewChat = functions.region("europe-west1")
.https.onRequest((request, response) => {
const groupName = request.body.groupName;
const members: string[] = request.body.members;
const db = admin.firestore();
db.collection("chats").add({
groupName: groupName,
members: members,
lastMessage: new Date(),
messages: [],
}).then((doc: any) => {
const chatId = doc.id;
const promises = [];
members.forEach((member) => {
promises.push(db.collection("myChats/" + member).add({
chatKey: chatId,
}));
});
return Promise.all(promises);
})
.then(() => {
response.status(200).send(JSON.stringify(doc));
})
.catch(e => {
functions.logger.log("catch clause " + e);
response.status(500).send(JSON.stringify(e));
});
});
Hey I'm startin to learn graphQL by doing the Frontend Masters' course Introduction to GraphQL (repo).
I would start by the context, but I look everywhere and nothing, also I tried to change it but it´s always the SAME output. If someone could help I'll be very, very grateful.
I'm trying to start the server with the next code:
import { ApolloServer } from 'apollo-server'
import { loadTypeSchema } from './utils/schema'
import { authenticate } from './utils/auth'
import { merge } from 'lodash'
import config from './config'
import { connect } from './db'
import product from './types/product/product.resolvers'
import coupon from './types/coupon/coupon.resolvers'
import user from './types/user/user.resolvers'
const types = ['product', 'coupon', 'user']
export const start = async () => {
const rootSchema = `
type Cat {
name: String
}
type _Query {
myCat: Cat
}
schema {
query: _Query
mutation: Mutation
}
`
const schemaTypes = await Promise.all(types.map(loadTypeSchema))
const server = new ApolloServer({
typeDefs: [rootSchema, ...schemaTypes],
resolvers: {
_Query: {
myCat(){
console.log('Hello there')
return {name:'Ivar'}
}
},
async context({ req }) {
const user = await authenticate(req)
return { user }
}
}
}
)
await connect(config.dbUrl)
const {url} = await server.listen({port: config.port})
console.log(`GQL server ready at ${url}`)
}
db file:
import mongoose from 'mongoose'
import options from './config'
export const connect = (url = options.dbUrl, opts = {}) =>
{ return mongoose .connect(url, {
useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
.then(() => console.log('Database Connected'))
.catch(err => console.log(err))
}
The curious thing is that in some moment it worked well, I've made changes, but not important ones.
The console output is this:
...
$ node dist/index.js
(node:17124) UnhandledPromiseRejectionWarning: Error: "context" defined in resolvers, but not in schema (Use `node --trace-warnings ...` to show where the warning was created)
(node:17124) 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:17124) [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.
[nodemon] clean exit - waiting for changes before restart
I'm sure that is a silly bug but it's freaking me out.
The context is part of the configuration object you pass to ApolloServer, not part of its .resolvers object.
const server = new ApolloServer({
typeDefs: [rootSchema, ...schemaTypes],
resolvers: {
_Query: {
myCat(){
console.log('Hello there')
return {name:'Ivar'}
}
},
},
async context({ req }) {
const user = await authenticate(req)
return { user }
},
})
So I am trying to set up an Ethereum flashloan script on the Kovan test network, partly because of the great amount of funds needed to execute it on Mainnet.
I have therefore found all the Kovan addresses of the services used (dydx, kyber, the tokens to be exchanged etc.) and made a new key called ‘kovan’ with those addresses within the ‘addresses’ folder.
I then finally succeeded in deploying the contract on Kovan. And the websocket interaction of getting and displaying the blocks also works.
I expect it to be error-free while waiting for a transaction to go through. But every time it receives a new block, it gives me an error saying:
UnhandledPromiseRejectionWarning: Error: call revert exception (method="decimals()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.1)
This is the whole console log:
λ node run-arbitrage.js
{
kyber: { kyberNetworkProxy: '0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D' },
uniswap: { router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' },
dydx: { solo: '0x4EC3570cADaAEE08Ae384779B0f3A45EF85289DE' },
tokens: {
dai: '0xc4375b7de8af5a38a93548eb8453a498222c4ff2',
usdc: '0xdcfab8057d08634279f8201b55d311c2a67897d2',
weth: '0xd0a1e359811322d97991e03f863a0c30c2cf029c'
}
}
web3-shh package will be deprecated in version 1.3.5 and will no longer be supported.
web3-bzz package will be deprecated in version 1.3.5 and will no longer be supported.
New block received. Block # 24267204
(node:20188) UnhandledPromiseRejectionWarning: Error: call revert exception (method="decimals()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.1)
at Logger.makeError (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\logger\lib\index.js:179:21)
at Logger.throwError (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\logger\lib\index.js:188:20)
at Interface.decodeFunctionResult (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\node_modules\#ethersproject\abi\lib\interface.js:286:23)
at Contract.<anonymous> (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:300:56)
at step (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:46:23)
at Object.next (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:27:53)
at fulfilled (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:18:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:20188) 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:20188) [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.
And this is my run-arbitrage.js file:
require("dotenv").config()
const Web3 = require('web3');
const { ChainId, Token, TokenAmount, Pair } = require('#uniswap/sdk');
const abis = require('./abis');
const { kovan: addresses } = require('./addresses');
console.log(addresses)
const Flashloan = require('./build/contracts/Flashloan.json');
const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.INFURA_KOVAN_URL)
);
const { address: admin } = web3.eth.accounts.wallet.add(process.env.PRIVATE_KEY);
const kyber = new web3.eth.Contract(
abis.kyber.kyberNetworkProxy,
addresses.kyber.kyberNetworkProxy
);
const ONE_WEI = web3.utils.toBN(web3.utils.toWei('1'));
const AMOUNT_DAI_WEI = web3.utils.toBN(web3.utils.toWei('20000'));
const DIRECTION = {
KYBER_TO_UNISWAP: 0,
UNISWAP_TO_KYBER: 1
};
const init = async () => {
const networkId = await web3.eth.net.getId();
const flashloan = new web3.eth.Contract(
Flashloan.abi,
Flashloan.networks[networkId].address
);
let ethPrice;
const updateEthPrice = async () => {
const results = await kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
1
)
.call();
ethPrice = web3.utils.toBN('1').mul(web3.utils.toBN(results.expectedRate)).div(ONE_WEI);
}
await updateEthPrice();
setInterval(updateEthPrice, 15000);
web3.eth.subscribe('newBlockHeaders')
.on('data', async block => {
console.log(`New block received. Block # ${block.number}`);
const [dai, weth] = await Promise.all(
[addresses.tokens.dai, addresses.tokens.weth].map(tokenAddress => (
Token.fetchData(
ChainId.MAINNET,
tokenAddress,
)
)));
const daiWeth = await Pair.fetchData(
dai,
weth,
);
const amountsEth = await Promise.all([
kyber
.methods
.getExpectedRate(
addresses.tokens.dai,
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
AMOUNT_DAI_WEI
)
.call(),
daiWeth.getOutputAmount(new TokenAmount(dai, AMOUNT_DAI_WEI)),
]);
const ethFromKyber = AMOUNT_DAI_WEI.mul(web3.utils.toBN(amountsEth[0].expectedRate)).div(ONE_WEI);
const ethFromUniswap = web3.utils.toBN(amountsEth[1][0].raw.toString());
const amountsDai = await Promise.all([
kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
ethFromUniswap.toString()
)
.call(),
daiWeth.getOutputAmount(new TokenAmount(weth, ethFromKyber.toString())),
]);
const daiFromKyber = ethFromUniswap.mul(web3.utils.toBN(amountsDai[0].expectedRate)).div(ONE_WEI);
const daiFromUniswap = web3.utils.toBN(amountsDai[1][0].raw.toString());
console.log(`Kyber -> Uniswap. Dai input / output: ${web3.utils.fromWei(AMOUNT_DAI_WEI.toString())} / ${web3.utils.fromWei(daiFromUniswap.toString())}`);
console.log(`Uniswap -> Kyber. Dai input / output: ${web3.utils.fromWei(AMOUNT_DAI_WEI.toString())} / ${web3.utils.fromWei(daiFromKyber.toString())}`);
if(daiFromUniswap.gt(AMOUNT_DAI_WEI)) {
const tx = flashloan.methods.initiateFlashloan(
addresses.dydx.solo,
addresses.tokens.dai,
AMOUNT_DAI_WEI,
DIRECTION.KYBER_TO_UNISWAP
);
const [gasPrice, gasCost] = await Promise.all([
web3.eth.getGasPrice(),
tx.estimateGas({from: admin}),
]);
const txCost = web3.utils.toBN(gasCost).mul(web3.utils.toBN(gasPrice)).mul(ethPrice);
const profit = daiFromUniswap.sub(AMOUNT_DAI_WEI).sub(txCost);
if(profit > 0) {
console.log('Arb opportunity found Kyber -> Uniswap!');
console.log(`Expected profit: ${web3.utils.fromWei(profit)} Dai`);
const data = tx.encodeABI();
const txData = {
from: admin,
to: flashloan.options.address,
data,
gas: gasCost,
gasPrice
};
const receipt = await web3.eth.sendTransaction(txData);
console.log(`Transaction hash: ${receipt.transactionHash}`);
}
}
if(daiFromKyber.gt(AMOUNT_DAI_WEI)) {
const tx = flashloan.methods.initiateFlashloan(
addresses.dydx.solo,
addresses.tokens.dai,
AMOUNT_DAI_WEI,
DIRECTION.UNISWAP_TO_KYBER
);
const [gasPrice, gasCost] = await Promise.all([
web3.eth.getGasPrice(),
tx.estimateGas({from: admin}),
]);
const txCost = web3.utils.toBN(gasCost).mul(web3.utils.toBN(gasPrice)).mul(ethPrice);
const profit = daiFromKyber.sub(AMOUNT_DAI_WEI).sub(txCost);
if(profit > 0) {
console.log('Arb opportunity found Uniswap -> Kyber!');
console.log(`Expected profit: ${web3.utils.fromWei(profit)} Dai`);
const data = tx.encodeABI();
const txData = {
from: admin,
to: flashloan.options.address,
data,
gas: gasCost,
gasPrice
};
const receipt = await web3.eth.sendTransaction(txData);
console.log(`Transaction hash: ${receipt.transactionHash}`);
}
}
})
.on('error', error => {
console.log(error);
});
}
init();
My command.js
based on some other bots like HarutoHiroki Bot thst open source on Github and the Nekos.life documentation
const Discord = require('discord.js');
const client = require('nekos.life');
const neko = new client();
module.exports.run = async (bot, message, args) => {
if (message.channel.nsfw === true) {
link = await neko.nsfw.boobs()
console.log(link)
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link)
.setFooter(`Bot by`);
message.channel.send(embed);
}
else {
message.channel.send("This isn't NSFW channel!")
}
};
module.exports.config = {
name: "boobs",
description: "",
usage: "*boobs",
accessableby: "Members",
aliases: []
}
Error:
> node .
(node:25052) ExperimentalWarning: Conditional exports is an experimental feature. This feature could change at any time
Logged in and connected as Bot#1234
{ url: 'https://cdn.nekos.life/boobs/boobs105.gif' }
(node:25052) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.image.url: Could not interpret "{'url': 'https://cdn.nekos.life/boobs/boobs105.gif'}" as string.
at RequestHandler.execute (C:\Users\User\Documents\GitHub\Bot\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:25052) 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:25052) [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.
My Question
how to fix this? (I tried the hole day but didn't got it working need help soon as possible)
I fixed it:
const Discord = require('discord.js');
const client = require('nekos.life');
const neko = new client();
module.exports.run = async (bot, message, args) => {
if (message.channel.nsfw === true) {
link = await neko.nsfw.boobs()
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link.url)
.setFooter(`Bot by`);
message.channel.send(embed);
}
else {
message.channel.send("This isn't NSFW channel!")
}
};
module.exports.config = {
name: "boobs",
description: "",
usage: "*boobs",
accessableby: "Members",
aliases: []
}
It looks like neko.nsfw.boobs() returns an object, not a string. Try this instead:
const { url } = await neko.nsfw.boobs(); // get only the URL, not the whole object
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link.url)
.setFooter(`Bot by`);
message.channel.send(embed);
Here's a code snippet example:
const link = {
url: 'https://cdn.nekos.life/boobs/boobs105.gif'
};
console.log(link); // this will not give the link. it will give the whole object
/* using object destructuring, you can use brackets to capture one
property of an array. in this case, the url.
Object Destructuring - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
*/
const {
url
} = link;
console.log(url); // this will give *only* the link
console.log(link.url); // another method to give only the link