Telegram - 401 AUTH_KEY_UNREGISTERED - node.js

I am trying to get the Telegram API working by saving the StringSession in a database and then using it to access the channels on my telegram app.
But with the following codes, I am facing the issue around 401 - Unregistered Auth Key.
Is there anyway to verify that the Auth key is registered? Or is there anything wrong with the codes?
Any pointers will be greatly appreciated.
const apiId = result.apiId;
const apiHash = result.apiHash;
const _stringSession = new telegramStringSession.StringSession(result.stringSession);
const client = new telegramClient.TelegramClient(_stringSession, apiId, apiHash, {
connectionRetries: 3,
});
await client.connect();
const dialogs = await client.getDialogs(new iterDialogs(this, {
limit: 100
}));

Related

Unable to retrieve auth string from auth endpoint - received status: 500

I using react native and backend is node.I trying implement pusher in my app.
Object {
"error": "Unable to retrieve auth string from auth endpoint - received status: 0 from http://10.0.27.124:8070/pusher/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/authenticating_users",
"status": 0,
"type": "AuthError",
}
Here is my react native code :
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
console.log(pusher)
const presenceChannel = pusher.subscribe('presence-channel');
Here is my node js code :
exports.authPusher = function (req, res) {
const socketId = req.body.socket_id;
const channel = req.body.channel_name;
console.log(req.body);
const presenceData = {
user_id: 'unique_user_id',
user_info: { name: 'Mr Channels', twitter_id: '#pusher' },
};
const auth = pusher.authenticate(socketId, channel, presenceData);
res.send(auth);
};
Thank you for answering.
I think you just forgot to use quote marks around authEndpoint parameter. Pusher is trying to call http instead of http://10.0.27.124:8070/pusher/auth.
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
If you open network tab on the web-developers toolbar of your browser, you must be able to see the actual request and debug it from there.

Express GET request not working after adding authentication

I'm stuck on this very simple problem and I don't know what I am doing wrong. I'm creating a simple RESTAPI with users and authentication. This is the GET request that I'm trying to run:
router.get('/users/me',auth ,async(req,res)=>{
console.log(req.user)
console.log('Entered the get request')
res.send(getUserData(req.user)) })
Basically, at the end of the authentication, I save the user fetched from the database into req.user object and then I send it to the client using res.send(req.user). As you can see in the code below:
const auth = async(req,res,next)=>{
try{
const token = req.header('Authorization').replace('Bearer ','')
const decoded = jwt.verify(token,'secretkey')
const db = req.app.locals.database
const user = await db.collection('users').findOne({
_id: decoded.id,
'tokens.token':token
})
console.log(user)
if(!user){
throw new Error()
}
req.user = user
next()
}catch(e){
res.status(401).send('Please Authenticate')
}}
The problem is that this authentication function is working perfectly fine. I have used it on other routes as well. But in this GET request, the authentication function runs (I identified this using many console logs) and fetches the data correctly. But it doesn't enter the get request once the middleware(auth function) has completed the call.
From POSTMAN, when I send GET requests, I get a 404 error and I have no idea why. I have literally spent hours trying to make sense of this. Please help me out if you know what might be the problem.
EDIT: So I was able to run the get request by moving the request above the following request that I also have in the same file:
router.get('/users/:id',auth ,async(req,res)=>{
const id = req.params.id
const db = req.app.locals.database
try{
const result = await db.collection('users').findOne({_id: id})
const userData = getUserData(result)
res.status(200).send(userData)
}catch(e){
res.status(404).send()
}
})
But now this request doesn't work. I cant figure out what positioning has to do with requests functionality. Can anyone please explain?

PERMISSION_DENIED: IAM permission 'dialogflow.sessions.detectIntent' Node js

I have created a webhook for WhatsApp Chatbot using NodeJS following this online article: https://dev.to/newtonmunene_yg/creating-a-whatsapp-chatbot-using-node-js-dialogflow-and-twilio-31km
The webhook is linked to Twilio Sandbox for WhatsApp.
I have also provided the DialogFlow Admin API permission to service account on Google Cloud Platform.
When I send a new message from WhatsApp, it's received on Twilio and the webhook is triggered, but I am getting the following error on the console on my local machine.
"Error: 7 PERMISSION_DENIED: IAM permission 'dialogflow.sessions.detectIntent' on 'projects/xxxx-xxx-xxxx/agent' denied."
I am using Ngrok to tunnel the localhost build to the web and using that URL as the webhook URL in Twilio.
We have a client demo for this feature, so any quick help is appreciated. I am placing my dialog flow code and controller code below
dialogflow.ts
const dialogflow = require("dialogflow");
const credentials = require("../../credential-new.json");
const sessionClient = new dialogflow.SessionsClient({
credentials: credentials
});
const projectId: string = process.env.DIALOGFLOW_PROJECT_ID!;
export const runQuery = (query: string, number: string) => {
return new Promise(async (resolve, reject) => {
try {
// A unique identifier for the given session
//const sessionId = uuid.v4();
const sessionId = number;
// Create a new session
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: query,
// The language used by the client (en-US)
languageCode: "en-US"
}
}
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
resolve(result);
} catch (error) {
reject(error);
}
});
};
This issue got resolved by creating a new account on DialogFlow and providing new API key.
I think the problem is with the service account. Make sure you use the same email which is registered with Dialogflow and GCP and then create a service account and also make sure the service account email is present in the credential-new.json file is the same service account which has the Dialog Flow Admin Role and also check you have given the valid path to access credential-new.json file in the code.
You can safely do this by going to the settings menu on Dialogflow and then clicking on the project id, it will take you to the correct place.
Also, there may be a possibility that you forget to enable the Dialogflow API from the API section on GCP.

Discord rest API: Kick members from guild

I'm trying to use the Discord Rest API and the "unirest" module with node.js to kick members from my server:
const unirest = require('unirest');
const guildId = "xyz";
const botSecret = "xyz";
const memberId = "xyz"
var request = 'https://discord.com/api/v8//guilds/' + guildId + '/members/' + memberId;
unirest.delete(request).send({"botToken": botSecret}).then((response) => {
console.log(response.body);
}).catch(error =>{
console.log(error);
})
However, I get a 401: Unauthorized response. The bot I'm using has the administrator role, so it is allowed to kick members from the guild.
I think that I'm making some mistakes in the request.
A 401 indicates you have not properly sent your authentication credentials.
If we look at the documentation for Discord Authentication we can see that they expect the bot token in the Authorization header instead of in the request like you have done.
We aren't using basic auth so we need to write the header manually.
unirest.delete(request)
.header('Authorization', 'Bot ' + botSecret)
...

Unable to handle multiple fulfillment responses

I am using the dialogflow enterprise edition bot,the issue is about receiving responses from rest api(node.js sdk).Recently we have shifted from dialogflow standard edition to Enterprise edition. We have referred and used the following code in this link
https://www.npmjs.com/package/dialogflow
We have created our own cloud function using rest Api which takes the user answer as the request and send the fulfillment text(questions in that particular intent) as the response to the user.When multiple request calls happen the the cloud function is not showing proper response which means
When user(Android/IOS) "A" started answering the bot then the cloud function triggering gets started and it send the questions as the response to the user but when the multiple users started answering the bot, due to multiple calls for the cloud function, the questions which are displayed to the one user are not going to be displayed to the other user say "B". Please help us in handling the multiple calls for node.js sdk
https://i.stack.imgur.com/BVAci.png
This is the view of an intent in dialogflow.
https://i.stack.imgur.com/aRAr6.png ,
https://i.stack.imgur.com/oMp0d.png
https://i.stack.imgur.com/T7Jo7.png
https://i.stack.imgur.com/7U3Rb.png
https://i.stack.imgur.com/EwWSo.png
Above five screenshots represent the first time when the user triggers
the cloud function, and the 1st question is displayed. When we answer the
first question and submit the answer, next question is not displayed.(I am
getting the empty response).
https://i.stack.imgur.com/rLI2I.png ,
https://i.stack.imgur.com/T5wZL.png
These screenshots represent the empty response after first question is answered.
const functions = require('firebase-functions');
const dialogflow = require('dialogflow');
const Firestore = require('#google-cloud/firestore');
const firestore = new Firestore();
admin.initializeApp();
var db = admin.firestore();
const {WebhookClient} = require('dialogflow-fulfillment');
exports.fulfillmenttext = functions.https.onRequest((req,res) =>{
runSample();
async function runSample() {
const projectId = 'bodha-192606';
const sessionId = uuid.v4();
const answer = req.body.Text;
console.log("Text said by the user",answer);
const languageCode = 'en-US';
const credentials = {
client_email: 'xxxx ',
Private_key:'xxxx ',
};
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient({
projectId,
credentials,
});
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: answer,
languageCode,
},
},
};
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
let action = result.action;
console.log("action is"+action);
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
res.status(200).send({"question":result.fulfillmentText});
} else {
console.log(` No intent matched.`);
res.status(400).send("No Intent matched");
}
}
});
It looks like you are using the same session ID for all of your clients. I'm not certain, but I can certainly understand that if Dialogflow gets two requests for the same session at the same time, that it can mix up the replies.
You should be generating a new session for each of your clients - possibly by putting something into an HTTP session (aha!) cookie when they first connect and continuing to use that during the session.

Resources