Network error: Error: connect ETIMEDOUT 149.154.167.220:443 - node.js

I have this code block in server.js file:
const Telegram = require('telegram-node-bot')
const tg = new Telegram.Telegram('***********token**************',{
workers:1
});
const pingController = require('./controllers/ping')
,otherwiseController = require('./controllers/otherwise')
tg.router.when(new Telegram.TextCommand('/ping','pingCommand'), new pingController())
.otherwise(new otherwiseController());
and this code block in ping.js file:
const Telegram = require('telegram-node-bot');
class pingController extends Telegram.TelegramBaseController{
pingHandler($){
$.sendMessage('pong');
}
get routes() {
return{
'pingCommand': 'pingHandler'
};
}
}
module.exports = pingController;
and finally this code block in otherwise file:
const Telegram = require('telegram-node-bot');
class otherwiseController extends Telegram.TelegramBaseController{
handler($){
$.sendMessage('Sorry!!!')
}
}
module.exports = otherwiseController;
when I run node server.js, I just got error like this:
[error]
Network error: Error: connect ETIMEDOUT 149.154.167.220:443
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14) request TelegramApiRequest { _method: 'setWebhook', _params: {
url: '' }, _multipart: undefined }
Also, the telegram is filtered in our country!!!, and I use the Siphon 3 proxy.

its because you have't set your proxy for your terminal/cmd
for Linux:
export http_proxy='http://proxyserveraddress:3128'
export https_proxy='https://proxyserveraddress:3128'
for Wndows:
set HTTP_PROXY=http://proxyserveraddress:3128
set HTTPS_PROXY=https://proxyserveraddress:3128

You can use SOCKS5 proxy with the socks5-https-client lib. Example:
const TelegramBot = require('node-telegram-bot-api')
const Agent = require('socks5-https-client/lib/Agent')
const bot = new TelegramBot(process.env.TELEGRAM_API_TOKEN, {
polling: true,
request: {
agentClass: Agent,
agentOptions: {
socksHost: process.env.PROXY_SOCKS5_HOST,
socksPort: parseInt(process.env.PROXY_SOCKS5_PORT),
// If authorization is needed:
// socksUsername: process.env.PROXY_SOCKS5_USERNAME,
// socksPassword: process.env.PROXY_SOCKS5_PASSWORD
}
}
})
This solution to continue developing bot on your local PC (without proxy you can not start bots from Iran and Russia) and it works.

Related

Failed to connect with RabbitMQ server when sending large amount of messages

I am using Cloudamqp to connect with RabbitMq when I am trying to send 10 messages its publishing data successfully to the queue but when I am trying to send 2,000 messages its showing connection failed error shown below:
Error Error: connect ECONNREFUSED 15.206.75.114:5671
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '15.206.75.114',
port: 5671
}
Error Error: Expected ConnectionOpenOk; got <ConnectionClose channel:0>
at /home/digvijay/test/test-lorien/node_modules/amqplib/lib/connection.js:167:14
at /home/digvijay/test/test-lorien/node_modules/amqplib/lib/connection.js:159:12
at TLSSocket.recv (/home/digvijay/test/test-
lorien/node_modules/amqplib/lib/connection.js:507:12)
I am reading the Excel file using XLSX library and sending those rows to the queue. Below is my code:
const express = require('express');
const XLSX = require("xlsx");
const amqp = require('amqplib/callback_api');
const app = express();
const port = process.env.PORT || 3300;
// Reading our test file
const file = XLSX.readFile('./limit9.xlsx')
app.get('/', (req, res) => {
const sheets = file.SheetNames;
for (let i = 0; i < sheets.length; i++) {
const temp = XLSX.utils.sheet_to_json(
file.Sheets[file.SheetNames[i]])
temp.forEach((res) => {
sendData(res); //Here sending data to the queue
});
}
});
function sendData(res) {
amqp.connect(`amqps://nuogafvveJoldl_RhEyfs7qJzX0BIRep6J8rFIN-0#puffin.rmq2.cloudamqp.com/xxxxxxx`, (err, connection) => {
if (err) {
console.log("Error",err);
}
else {
connection.createChannel((err, channel) => {
if (err) {
throw err;
}
else {
let queu = "review_data";
channel.assertQueue(queu, {
durable: false
});
var json = JSON.stringify(res);
channel.sendToQueue(queu, Buffer.from(json));
}
});
}
});
}
Why is it throwing connection error when I am sending large amount of messages but works fine for sending few messages?

NestJS and IPFS - no connection on the server instance

I am struggling with binding IPFS node with NestJS instance on the server. All was working fine on the local machine, but on the server, I have a working instance of the IPFS. I know that it works as I can see connected peers and I can see a file uploaded through the server console by https://ipfs.io/ipfs gateway.
The code of the IPFS service is quite simple and it does not produce any errors until I try to upload something.
import { Injectable } from '#nestjs/common';
import { create } from 'ipfs-http-client';
#Injectable()
export class IPFSClientService {
private client = create({
protocol: 'http',
port: 5001
});
public async upload(file: Express.Multer.File): Promise<string> {
const fileToAdd = { path: file.filename, content: file.buffer };
try {
const addedFile = await this.client.add(fileToAdd, { pin: true });
return addedFile.path;
} catch (err) {
console.log('err', err);
}
}
}
Unfortunatelly the error message is enigmatic.
AbortController is not defined
at Client.fetch (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:124:29)
at Client.fetch (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/lib/core.js:141:20)
at Client.post (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:171:17)
at addAll (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add-all.js:22:27)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at Object.last [as default] (/home/xxx_secret/node_modules/it-last/index.js:13:20)
at Object.add (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add.js:18:14)
at IPFSClientService.upload (/home/xxx_secret/src/ipfs/ipfs-client.service.ts:20:25)
I will appreciate any help in this matter as I don't have ideas regarding this issue :/

Error: PollingBlockTracker - encountered an error while attempting to update latest block: Error: ETIMEDOUT

I want to run a code in my terminal. " truffle migrate --network ropsten"
1_initial_migration runs correctly, but I have an error for 2_deploy_conracts.js like this:
D:\Dapp\proje\proje\node_modules\request\request.js:848
var e = new Error('ETIMEDOUT')
^
Error: PollingBlockTracker - encountered an error while attempting to update latest block:
Error: ETIMEDOUT
at Timeout.<anonymous> (D:\Dapp\proje\proje\node_modules\request\request.js:848:19)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
at PollingBlockTracker._performSync (D:\Dapp\proje\proje\node_modules\eth-block-tracker\src\polling.js:51:24)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at runNextTicks (node:internal/process/task_queues:65:3)
at processTimers (node:internal/timers:499:9)
This is my truffle-config.js files:
const path = require("path");
const HDWalletProvider = require('#truffle/hdwallet-provider');
const infuraKey = "08ac778579d74dbaa8d2e3d02e5c0092"
const fs = require('fs');
const mnemonic = fs.readFileSync(".secret").toString().trim();
module.exports = {
contracts_build_directory: path.join(__dirname, "src/contracts"),
networks: {
ropsten: {
provider: () => new HDWalletProvider(mnemonic, `wss://ropsten.infura.io/ws/v3/${infuraKey}`),
network_id: 3, // Ropsten's id
gas: 5500000, // Ropsten has a lower block limit than mainnet
confirmations: 2, // # of confs to wait between deployments. (default: 0)
timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
skipDryRun: false // Skip dry run before migrations? (default: false for public nets )
},
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
}
},
};
What or where is the error? Can you help me please?
As far as I remember if your mnemonics were incorrect, you would get a different error. Most likely your URL is not correct.
Try this:
const webSocketProvider = new Web3.providers.WebsocketProvider(`wss://ropsten.infura.io/ws/v3/${infuraKey}`);
const walletProvider = new HDWalletProvider(mnemonic, webSocketProvider);
If this does not fix it, instead of wss pass https url

Getting getaddrinfo ENOTFOUND when trying to connect to my AWS Neptune with node.js and gremlin

I am trying to connect to my Amazon Neptune instance from a API GW. I am using Node.js and Lambda
My YML looks like this
NeptuneDBCluster:
Type: "AWS::Neptune::DBCluster"
Outputs:
NeptuneEndpointAddress:
Description: Neptune DB endpoint address
Value: !GetAtt NeptuneDBCluster.Endpoint
Export:
Name: !Sub ${env:STAGE}-neptune-endpoint-address
My code looks like this
const gremlin = require('gremlin');
const {
NEPTUNE_ENDPOINT
} = process.env;
const { cardinality: { single } } = gremlin.process;
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const Graph = gremlin.structure.Graph;
async function createUserNode(event, context, callback) {
const url = 'wss://" + NEPTUNE_ENDPOINT + ":8182/gremlin';
const dc = new DriverRemoteConnection(url);
const parsedBody = JSON.parse(event.body);
try {
const graph = new Graph();
const g = graph.traversal().withRemote(dc);
const vertex = await g.addV(parsedBody.type)
.property(single, 'name', parsedBody.name)
.property(single, 'username', parsedBody.username)
.property('age', parsedBody.age)
.property('purpose', parsedBody.purpose)
.next();
if (vertex.value) {
return callback(null, {
statusCode: 200,
body: vertex.value
});
}
} catch (error) {
console.error(error);
}
};
I keep getting the folowing error from Cloudwatch (I also tried creating a local js file and it gives the same error)
ERROR Error: getaddrinfo ENOTFOUND my-url
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'my-url'
}
I also tried to write the endpoint without getting it from process.env and I am still facing the same issue. What am i missing?
Alright for anyone being as confused as I am when trying Neptune for first time. You need to create a database instance aswell, I thought the Serverless Framework would do this to me but now I know.

Making POST call outside of the GCP environment to create workload identity

I need to access GCP resources outside of the GCP environment from AWS using a AWS lambda. So, I found this document [accessing GCP resources from AWS][1] which provides a way to access the GCP resources and asks to create a workload identity pool.
I need to create a Workload identity pool in GCP using a REST API call. The REST API call has to run outside of the GCP environment, that is, in this case from the AWS environment. My GCP's IAM user doesn't have privileges to create a workload identity pool (due to org policy reasons). But, I've a service account which has admin privileges to create a workload identity pool and all the required permissions to access the required resources once the pool is created.
I'm a newbie to GCP and figuring out ways of calling a POST REST API call using my service account credentials. Any help is much appreciated.
Edited
Pasting the sample code I've been trying to make the REST call.
const {google} = require('googleapis');
const util = require('util');
const https = require('https');
const aws4 = require('aws4');
const auth = new google.auth.GoogleAuth({
keyFile: 'serviceAccountCreds.json',
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
async function createSignedRequestParams(jsonBodyParams) {
const getAccessToken = await auth.getAccessToken();
console.log(`createSignedRequestParams() - this.credentials:${getAccessToken !== null}`);
// Set up the request params object that we'll sign
const requestParams = {
path: '/v1beta/projects/serviceAccountdev/locations/global/workloadIdentityPools?workloadIdentityPoolId=12345',
method: 'POST',
host: 'iam.googleapis.com',
headers: { 'Content-Type': 'application/json' },
body: jsonBodyParams
};
console.log(`createSignedRequestParams() - (signed) requestParams:${util.inspect(requestParams)}`);
return requestParams;
}
const jsonBodyParams = {
"description": "createWorkloadIdentityPool",
"display-name": "devAccount"
};
async function request(requestParams, jsonBodyParams) {
console.log(`request() requestParams:${util.inspect(requestParams)} jsonBodyParams:${jsonBodyParams}`);
// return new pending promise
return new Promise((resolve, reject) => {
const req = https.request(requestParams);
if (['POST', 'PATCH', 'PUT'].includes(requestParams.method)) {
req.write(jsonBodyParams);
}
req.end();
// Stream handlers for the request
req.on('error', (err) => {
console.log(`request() req.on('error') err:${util.inspect(err)}`);
return reject(err);
});
req.on('response', (res) => {
let dataJson = '';
res.on('data', chunk => {
dataJson += chunk;
});
res.on('end', () => {
const statusCode = res.statusCode;
const statusMessage = res.statusMessage;
const data = JSON.parse(dataJson);
console.log(`request() res.on('end')`, { statusCode, statusMessage, data });
resolve({ statusMessage, statusCode, data });
});
});
});
}
async function postTheRequest(reqParams, jsonBodyParams) {
try {
const response = await request(reqParams, jsonBodyParams);
return response;
} catch (error) {
console.log(error);
}
}
reqParams = createSignedRequestParams(jsonBodyParams);
postTheRequest(reqParams, jsonBodyParams);
output of the above code
[Running] node "c:\Users\av250044\.aws\GCP_Code_examples\registerTheWorkloadIdentifier.js"
request() requestParams:Promise { <pending> } jsonBodyParams:[object Object]
request() req.on('error') err:{ Error: connect ECONNREFUSED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 443 }
{ Error: connect ECONNREFUSED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 443 }
Wondering if I'm passing the PATH and host are correct. Please let me know your thoughts on my code sample.
[1]: https://cloud.google.com/iam/docs/access-resources-aws#iam-workload-pools-add-aws-rest

Resources