telegram api signup return PHONE_CODE_INVALID - node.js

my code:
const { Api, TelegramClient } = require("telegram");
const { StringSession } = require("telegram/sessions");
const { Logger } = require("telegram/extensions");
const apiId = 22;
const apiHash = "333333";
const phoneNumber = "9996627328";
const phoneCode = "22222";
const createClient = async (stringSession) => {
const session = new StringSession(stringSession);
const options = { connectionRetries: 5, baseLogger: new Logger("debug") };
const client = new TelegramClient(session, apiId, apiHash, options);
client.session.setDC(2, "149.154.167.40", 443);
await client.connect();
return client;
};
const getLoginCodeCommand = (phoneNumber) => {
const settings = new Api.CodeSettings();
const args = { phoneNumber, apiId, apiHash, settings };
return new Api.auth.SendCode(args);
};
(async () => {
const client = await createClient("");
const response = await client.invoke(getLoginCodeCommand(phoneNumber));
console.log('response:', response);
const { phoneCodeHash } = response;
const result22 = await client.invoke(
new Api.auth.SignUp({
phoneNumber: phoneNumber,
phoneCodeHash: phoneCodeHash,
firstName: "liu",
lastName: "some",
})
);
console.log("RESULT22", result22);
})();
response:
/Users/xizao/work/fm/project/telegram/node_modules/telegram/errors/index.js:28
return new RPCBaseErrors_1.RPCError(rpcError.errorMessage, request, rpcError.errorCode);
^
RPCError: 400: PHONE_CODE_INVALID (caused by auth.SignUp)
at RPCMessageToError (/Users/xizao/work/fm/project/telegram/node_modules/telegram/errors/index.js:28:12)
at MTProtoSender._handleRPCResult (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:517:58)
at MTProtoSender._processMessage (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:442:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async MTProtoSender._recvLoop (/Users/xizao/work/fm/project/telegram/node_modules/telegram/network/MTProtoSender.js:418:17) {
code: 400,
errorMessage: 'PHONE_CODE_INVALID'
}
No matter how you adjust it, the phone code is always invalid
The correct result should be direct registration success.
I haven't been able to find the problem because of what? Please help me to see why?
doc link: https://gram.js.org/tl/auth/SignUp#authsignup

Related

createClickwrap returns 404 Not Found

When I call createClickwrap method, I got 404 error Not Found. If I run this method through Quickstart generated demo project, I don't get this error. However, if I run it through my project I get the error. If I debug the demo app and my app, the functions parameters are the same.
This is the code in my app:
docusign controller:
const docuSignService = require('./docusign_esign_service');
const demoDocumentsPath = path.resolve(__dirname, '../demo_documents');
const { createClickwrap } = require('./createClickWrap');
async getDocusignRecieptService() {
const authResponse = await docuSignService.authenticate();
if (authResponse) {
const docTermsPdf = 'Term_Of_Service.pdf';
const docFile = path.resolve(demoDocumentsPath, docTermsPdf);
const { basePath, accessToken, apiAccountId } = authResponse;
const { clickwrapId } = await createClickwrap({ docFile, basePath, accessToken, accountId: apiAccountId });
const res = await activateClickwrap({ clickwrapId, basePath, accessToken, accountId: apiAccountId });
console.log({ res });
}
}
docuSignService.js
const SCOPES = ['signature', 'impersonation', 'openid', 'click.manage', 'click.send'];
const fs = require('fs');
const docusign = require('docusign-esign');
class DocusingService {
async authenticate() {
const jwtLifeSec = 10 * 60, // requested lifetime for the JWT is 10 min
dsApi = new docusign.ApiClient();
dsApi.setOAuthBasePath(process.env.dsOauthServer.replace('https://', '')); // it should be domain only.
let rsaKey = fs.readFileSync(process.env.privateKeyLocation);
try {
const results = await dsApi.requestJWTUserToken(
process.env.dsJWTClientId,
process.env.impersonatedUserGuid,
SCOPES,
rsaKey,
jwtLifeSec
);
const accessToken = results.body.access_token;
// get user info
const userInfoResults = await dsApi.getUserInfo(accessToken);
// use the default account
let userInfo = userInfoResults.accounts.find((account) => account.isDefault === 'true');
return {
accessToken: results.body.access_token,
apiAccountId: userInfo.accountId,
basePath: `${userInfo.baseUri}/restapi`
};
} catch (e) {
let body = e.response && e.response.body;
// Determine the source of the error
if (body) {
// The user needs to grant consent
if (body.error && body.error === 'consent_required') {
if (this.getConsent()) {
return this.authenticate();
}
} else {
// Consent has been granted. Show status code for DocuSign API error
this._debug_log(`\nAPI problem: Status code ${e.response.status}, message body:
${JSON.stringify(body, null, 4)}\n\n`);
}
}
}
}
getConsent() {
var urlScopes = SCOPES.join('+');
// Construct consent URL
var redirectUri = 'https://developers.docusign.com/platform/auth/consent';
var consentUrl =
`${process.env.dsOauthServer}/oauth/auth?response_type=code&` +
`scope=${urlScopes}&client_id=${process.env.dsJWTClientId}&` +
`redirect_uri=${redirectUri}`;
throw new Error(`Open the following URL in your browser to grant consent to the application: ${consentUrl}`);
}
getArgs(apiAccountId, accessToken, basePath, signerEmail, signerName, id, agreementData, redirect_uri) {
const envelopeArgs = {
signerEmail: signerEmail,
signerName: signerName,
status: 'sent',
signerClientId: id,
dsReturnUrl: redirect_uri,
agreement: agreementData
};
const args = {
accessToken: accessToken,
basePath: basePath,
accountId: apiAccountId,
envelopeArgs: envelopeArgs
};
return args;
}
}
module.exports = new DocusingService();
createClickWrap.js
const createClickwrap = async ({ docFile, clickwrapName = 'clickwrapName', basePath, accessToken, accountId }) => {
// Step 3. Construct the request Body
// Create display settings model
const displaySettings = docusignClick.DisplaySettings.constructFromObject({
consentButtonText: 'I Agree',
displayName: 'Terms of Service',
downloadable: true,
format: 'modal',
hasAccept: true,
mustRead: true,
requireAccept: true,
documentDisplay: 'document'
});
// Create document model
// Read and encode file. Put encoded value to Document entity.
// The reads could raise an exception if the file is not available!
const documentPdfExample = fs.readFileSync(docFile);
const encodedExampleDocument = Buffer.from(documentPdfExample).toString('base64');
const document = docusignClick.Document.constructFromObject({
documentBase64: encodedExampleDocument,
documentName: 'Terms of Service',
fileExtension: 'pdf',
order: 0
});
// Create clickwrapRequest model
const clickwrapRequest = docusignClick.ClickwrapRequest.constructFromObject({
displaySettings,
documents: [document],
name: clickwrapName,
requireReacceptance: true
});
// Step 4. Call the Click API
const dsApiClient = new docusignClick.ApiClient();
dsApiClient.setBasePath(basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + accessToken);
const accountApi = new docusignClick.AccountsApi(dsApiClient);
// Create a clickwrap
let result = null;
try {
result = await accountApi.createClickwrap(accountId, {
clickwrapRequest
});
} catch (e) {
debugger;
console.log(e);
}
debugger;
console.log(`Clickwrap was created. ClickwrapId ${result.clickwrapId}`);
return result;
};
module.exports = { createClickwrap };
Parameters look like this in the demo app and it works:
and these are the parameters in my app:
The first parameter accountId is the same. Why I am getting this issue in my app if function gets the same parameters?
"Error: Not Found
at Request.callback (/Users/and/test/node_modules/docusign-click/node_modules/superagent/lib/node/index.js:696:15)
at IncomingMessage.<anonymous> (/Users/and/test/node_modules/docusign-click/node_modules/superagent/lib/node/index.js:906:18)
at IncomingMessage.emit (node:events:539:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)"
Thanks to pointing out in the comments, when I changed basePath ${userInfo.baseUri}/restapi to ${userInfo.baseUri}/clickapi, it works now.

TypeError: botGuilds.find is not a function

This code is for an express website for my discord bot I need it to catch the mutual guilds but it's giving this error:
TypeError: botGuilds.find is not a function
at C:\Users\não te interessa\Desktop\projetos\bot\backend\utils\utils.js:3:56
at Array.filter (<anonymous>)
at Proxy.methods.<computed> (C:\Users\não te interessa\Desktop\projetos\bot\backend\node_modules\mongoose\lib\types\array\methods\index.js:956:24)
at getMutualGuilds (C:\Users\não te interessa\Desktop\projetos\bot\backend\utils\utils.js:3:28)
at C:\Users\não te interessa\Desktop\projetos\bot\backend\routes\discord.js:11:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)
which uses getMutualGuilds:
const router = require("express").Router()
const { getBotGuilds } = require("../utils/api")
const { getMutualGuilds } = require("../utils/utils")
const User = require('../database/schemas/Users')
router.get('/guilds', async (req, res) => {
const guilds = await getBotGuilds();
const user = await User.findOne({ discordId: req.user.discordId });
if (user) {
const userGuilds = user.get('guilds');
const mutualguilds = await getMutualGuilds(userGuilds, guilds);
res.send(mutualguilds);
}
});
module.exports = router
getMutualGuilds code:
function getMutualGuilds(userGuilds, botGuilds) {
return userGuilds.filter((guild) => botGuilds.find((botGuild) => (botGuild.id === guild.id) && (guild.permissions & 0x20) === 0x20))
}
module.exports = { getMutualGuilds }
code of botGuilds:
const fetch = require("node-fetch")
const TOKEN = "token of my bot";
async function getBotGuilds() {
const response = await fetch('http://discord.com/api/v8/users/#me/guilds', {
method: 'GET',
headers:{
Authorization: `Bot ${TOKEN}`
}
})
return response.json()
}
module.exports = { getBotGuilds }

How to send data from react editor to server?

I am trying to create an editor to update my backend data but I am stuck at sending data from client to backend
Here is my following front-end code:
import React, { useState } from "react";
import dynamic from "next/dynamic";
import { convertToRaw, EditorState, getDefaultKeyBinding } from "draft-js";
import draftToHtml from "draftjs-to-html";
const Editor = dynamic(
() => import("react-draft-wysiwyg").then((mod) => mod.Editor),
{ ssr: false }
);
const Missions = ({ teamData, editable }) => {
const { title, mission, teamId } = teamData;
const classes = useStyle();
const [missionContent, setMissionContent] = useState(mission);
const [editing, setEditing] = useState(false);
const [editorState, updateEditorState] = useState(EditorState.createEmpty());
const onEditorStateChange = (editData) => {
updateEditorState(editData);
};
const handleSave = async () => {
const selection = editorState.getSelection();
const key = selection.getAnchorKey();
const content = editorState.getCurrentContent();
const block = content.getBlockForKey(key);
const type = block.getType();
if (type !== "unordered-list-item" && type !== "ordered-list-item") {
if (
editorState.getCurrentContent().getPlainText("").trim().length !== 0
) {
const content = editorState?.getCurrentContent();
let html = await draftToHtml(convertToRaw(content));
await updateEditorState(EditorState.createEmpty(""));
setMissionContent(html.trim());
}
}
setEditing(false);
};
return (
<div className="team-mission-editor-container">
<Editor
wrapperClassName={"mission-editor-wapper"}
toolbarClassName={"mission-editor-toolbar"}
editorClassName={"mission-editor-editor"}
editorState={editorState}
onEditorStateChange={onEditorStateChange}
toolbar={{...}}
/>
)
Here is my back-end router:
router.put(
"/team/:teamId",
restrictedRoute,
checkData,
catchErrors(checkTeamPermissions),
catchErrors(updateTeamData)
);
and here is my update function from backend:
exports.updateTeamData = async (req, res) => {
// Get userId
const userId = req.session.passport.user.id;
// Get teamId
const publicTeamId = req.params.teamId;
// Fetch private id for team
const teamId = await getTeamId(publicTeamId);
// The user making the request
const userPublicId = req.session.passport.user.publicId;
// The creator of the team
const creatorPublicId = req.body.creator;
// Check who is making the request
if (userPublicId !== creatorPublicId) {
res.status(401).json("msg: You cant update a team you did not create");
}
// Updates
const payload = {
title: req.body.title,
mission: req.body.mission,
inputs: req.body.inputs,
outputs: req.body.outputs,
duration_in_months: req.body.duration_in_months,
status: req.body.status,
mergedTo: teamId,
};
// Update team data
await models.Team.update(payload, {
where: {
id: teamId,
creatorId: userId,
},
});
res.status(200).json("msg: Updated team successfully");
};
How can I send data fromo my editor to backend and update it?
Thank you so much for helping me

Azure Bot Framework V4 (NodeJS) - LUIS recognizer returns error?

Using Azure Bot Framework and LUIS.ai to recognize user intent. Performing a get request to the endpoint with the text returns the json object I am expecting, however using the built-in Luis Recognizer I receive the following error: 'Cannot read property 'get' of undefined'. From the documentation here: https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-nodejs-tutorial-bf-v4 this appears to be the proper configuration so I am not sure what is going awry. Any ideas?
const { ComponentDialog, DialogSet, DialogTurnStatus, WaterfallDialog, ChoicePrompt, TextPrompt } = require('botbuilder-dialogs');
const { TopLevelDialog, TOP_LEVEL_DIALOG } = require('./topLevelDialog');
const { LuisRecognizer, QnAMaker } = require('botbuilder-ai');
const axios = require('axios');
const MAIN_DIALOG = 'MAIN_DIALOG';
const WATERFALL_DIALOG = 'WATERFALL_DIALOG';
const USER_PROFILE_PROPERTY = 'USER_PROFILE_PROPERTY';
const CHOICE_PROMPT = 'CHOICE_PROMPT';
const TEXT_PROMPT = 'TEXT_PROMPT';
class MainDialog extends ComponentDialog {
constructor(userState) {
super(MAIN_DIALOG);
this.userState = userState;
this.userProfileAccessor = userState.createProperty(USER_PROFILE_PROPERTY);
this.addDialog(new TextPrompt(TEXT_PROMPT));
this.addDialog(new TopLevelDialog());
this.addDialog(new WaterfallDialog(WATERFALL_DIALOG, [
this.initialStep.bind(this),
this.askIfFinishedStep.bind(this),
this.finalStep.bind(this)
]));
this.initialDialogId = WATERFALL_DIALOG;
let luisConfig = {
applicationId: '',
endpointKey: '',
endpoint: '',
};
this.Luis = new LuisRecognizer(
luisConfig,
{
includeAllIntents: true,
log: true,
staging: false
},
true
);
}
async run(turnContext, accessor) {
const dialogSet = new DialogSet(accessor);
dialogSet.add(this);
const dialogContext = await dialogSet.createContext(turnContext);
const results = await dialogContext.continueDialog();
if (results.status === DialogTurnStatus.empty) {
await dialogContext.beginDialog(this.id);
}
}
async initialStep(stepContext) {
let luisAnalysis = await this.Luis.recognize(stepContext);
let queryString = encodeURIComponent(stepContext.context._activity.text);
/*
Ignore this if statement - only in use with the get request
*/
if(luisResponse.data.topScoringIntent.intent === 'TrainingExpiry' && luisResponse.data.topScoringIntent.score > .75)
{
return await stepContext.beginDialog(TOP_LEVEL_DIALOG);
}
else
{
await stepContext.context.sendActivity("I'm sorry, that is not supported at this time or a high enough intent was not acknowledged.");
await stepContext.context.sendActivity("Top intent: " + luisResponse.data.topScoringIntent.intent + " Score: " + luisResponse.data.topScoringIntent.score);
return await stepContext.next();
}
}
async askIfFinishedStep(stepContext) {
const promptOptions = { prompt: 'Is there anything else I can assist you with?' };
return await stepContext.prompt(TEXT_PROMPT, promptOptions);
}
async finalStep(stepContext) {
if(stepContext.context._activity.text.toLowerCase() === 'no')
{
await stepContext.context.sendActivity("Good bye");
return await stepContext.endDialog();
}
else
{
return await stepContext.beginDialog(MAIN_DIALOG);
}
}
}
module.exports.MainDialog = MainDialog;
module.exports.MAIN_DIALOG = MAIN_DIALOG;
Note: The issue was in my parameter being passed to the recognizer, as #billoverton pointed out. The solution is to pass stepContext.context.
Looking at luisRecognizer.js from the botbuilder-ai module, the error is because the recognizer is expecting a turnContext (with turnState property) and you are sending a stepContext. turnState doesn't exist on stepContext, thus the get property is failing and causing your error. If you send stepContext.context instead, that will fix the issue, i.e. let luisAnalysis = await this.Luis.recognize(stepContext.context);

how to fix octokit.authenticate() is deprecated

I am starting the ginit module but getting the error like this:
=> octokit.authenticate() is deprecated. Use "auth" constructor
option instead.
How can I fix it?
my code
module.exports = {
getInstance: () => {
return octokit;
},
setGithubCredentials : async () => {
const credentials = await inquirer.askGithubCredentials();
octokit.authenticate(
_.extend(
{
type: 'basic',
},
credentials
)
);
},
}
Maybe you code from this article: https://www.sitepoint.com/javascript-command-line-interface-cli-node-js/
And my solution is below
const Octokit = require("#octokit/rest");
const Configstore = require("configstore");
const pkg = require("../package.json");
const _ = require("lodash");
const CLI = require("clui");
const Spinner = CLI.Spinner;
const chalk = require("chalk");
const inquirer = require("./inquirer");
const conf = new Configstore(pkg.name);
module.exports = {
getInstance: () => {
return global.octokit;
},
getStoredGithubToken: () => {
return conf.get("github.token");
},
setGithubCredentials: async () => {
const credentials = await inquirer.askGithubCredentials();
const result = _.extend(
{
type: "basic"
},
credentials
);
global.octokit = Octokit({
auth: result
});
},
registerNewToken: async () => {
const status = new Spinner("Authenticating you, please wait...");
status.start();
try {
const response = await global.octokit.oauthAuthorizations.createAuthorization({
scopes: ["user", "public_repo", "repo", "repo:status"],
note: "ginits, the command-line tool for initalizing Git repos"
});
const token = response.data.token;
if (token) {
conf.set("github.token", token);
return token;
} else {
throw new Error(
"Missing Token",
"GitHub token was not found in the response"
);
}
} catch (err) {
throw err;
} finally {
status.stop();
}
}
};
Try something like:
const Octokit = require('#octokit/rest');
module.export = {
getInstance({username, password}) {
return Octokit({
auth: {
username,
password,
},
});
}
}
The PR introducing the auth property shows some other examples of specifying credentials.

Resources