How to use dialogs with dispatch service? - javascript

I cannot use beginDialog with the LUIS dispatch. I want to use processHomeAutomation function to begin a new dialog but it gives me an error.
[onTurnError]: Error: DialogContext.beginDialog(): A dialog with an id
of 'TOP_LEVEL_DIALOG' wasn't found.
I imported TOP_LEVEL_DIALOG but still does not work. It only works with MainDialog which is the name of the current class.
const { ConfirmPrompt, DialogSet, DialogTurnStatus, OAuthPrompt, WaterfallDialog } = require('botbuilder-dialogs');
const { LogoutDialog } = require('./logoutDialog');
const { TopLevelDialog, TOP_LEVEL_DIALOG } = require('./topLevelDialog');
const { LuisRecognizer, QnAMaker } = require('botbuilder-ai');
const CONFIRM_PROMPT = 'ConfirmPrompt';
const MAIN_DIALOG = 'MainDialog';
const MAIN_WATERFALL_DIALOG = 'MainWaterfallDialog';
const OAUTH_PROMPT = 'OAuthPrompt';
let loggedIn = true;
class MainDialog extends LogoutDialog {
constructor() {
super(MAIN_DIALOG, process.env.connectionName);
this.addDialog(new TopLevelDialog());
this.addDialog(new OAuthPrompt(OAUTH_PROMPT, {
connectionName: process.env.connectionName,
text: 'Please Sign In',
title: 'Sign In',
timeout: 300000
}));
this.addDialog(new ConfirmPrompt(CONFIRM_PROMPT));
this.addDialog(new WaterfallDialog(MAIN_WATERFALL_DIALOG, [
this.promptStep.bind(this),
this.loginStep.bind(this),
this.displayTokenPhase1.bind(this),
this.displayTokenPhase2.bind(this)
]));
}
/**
* The run method handles the incoming activity (in the form of a DialogContext) and passes it through the dialog system.
* If no dialog is active, it will start the default dialog.
* #param {*} dialogContext
*/
async run(context, accessor) {
console.log(this.id)
if (loggedIn) {
const dialogSet = new DialogSet(accessor);
dialogSet.add(this);
const dialogContext = await dialogSet.createContext(context);
const results = await dialogContext.continueDialog();
const dispatchRecognizer = new LuisRecognizer({
applicationId: process.env.LuisAppId,
endpointKey: process.env.LuisAPIKey,
endpoint: `https://${process.env.LuisAPIHostName}.api.cognitive.microsoft.com`
}, {
includeAllIntents: true,
includeInstanceData: true
}, true);
const qnaMaker = new QnAMaker({
knowledgeBaseId: process.env.QnAKnowledgebaseId,
endpointKey: process.env.QnAAuthKey,
host: process.env.QnAEndpointHostName
});
this.dispatchRecognizer = dispatchRecognizer;
this.qnaMaker = qnaMaker;
const recognizerResult = await dispatchRecognizer.recognize(context);
// Top intent tell us which cognitive service to use.
const intent = LuisRecognizer.topIntent(recognizerResult);
// Next, we call the dispatcher with the top intent.
await this.dispatchToTopIntentAsync(context, intent, recognizerResult, dialogContext, results, dialogSet);
} else {
const dialogSet = new DialogSet(accessor);
dialogSet.add(this);
const dialogContext = await dialogSet.createContext(context);
const results = await dialogContext.continueDialog();
if (results.status === DialogTurnStatus.empty) {
console.log(this.id)
await dialogContext.beginDialog(this.id);
}
}
}
async promptStep(stepContext) {
return await stepContext.beginDialog(OAUTH_PROMPT);
}
async loginStep(stepContext) {
// Get the token from the previous step. Note that we could also have gotten the
// token directly from the prompt itself. There is an example of this in the next method.
const tokenResponse = stepContext.result;
if (tokenResponse) {
loggedIn = true;
await stepContext.context.sendActivity('You are now logged in.');
return await stepContext.prompt(CONFIRM_PROMPT, 'Would you like to view your token?');
}
await stepContext.context.sendActivity('Login was not successful please try again.');
return await stepContext.endDialog();
}
async displayTokenPhase1(stepContext) {
await stepContext.context.sendActivity('Thank you.');
const result = stepContext.result;
if (result) {
return await stepContext.beginDialog(OAUTH_PROMPT);
}
return await stepContext.endDialog();
}
async displayTokenPhase2(stepContext) {
const tokenResponse = stepContext.result;
if (tokenResponse) {
await stepContext.context.sendActivity(`Here is your token ${tokenResponse.token}`);
}
return await stepContext.endDialog();
}
/// QNA STUFF STATS HERE
async dispatchToTopIntentAsync(context, intent, recognizerResult, dialogContext, results) {
switch (intent) {
case 'automation':
await this.processHomeAutomation(context, recognizerResult.luisResult, dialogContext, results);
break;
case 'qna':
await this.processSampleQnA(context);
break;
default:
this.logger.log(`Dispatch unrecognized intent: ${intent}.`);
await context.sendActivity(`Dispatch unrecognized intent: ${intent}.`);
break;
}
}
async processHomeAutomation(context, luisResult, dialogContext, results, dialogSet) {
return await dialogContext.beginDialog(TOP_LEVEL_DIALOG);
}
async processSampleQnA(context) {
this.logger.log('processSampleQnA');
const results = await this.qnaMaker.getAnswers(context);
if (results.length > 0) {
await context.sendActivity(`${results[0].answer}`);
} else {
await context.sendActivity('Sorry, could not find an answer in the Q and A system.');
}
}
}
module.exports.MainDialog = MainDialog;

Related

Node function not working, await part is not getting executed in the given function

While hitting API I'm getting function from my services/ElasticSearch.js and for some reason function there is not working after the axios part.
In the below file I've called function elasticService.updateDocument this function has been brought from another file.
'''
class ProductController {
constructor() { }
async saveProduct(req, res) {
console.log('ITs coming here')
let { _id, Product } = req.body;
if (_id) delete req.body._id;
let elasticResult;
try {
if (Product && Product.Category) {
req.body.Category = Product.Category
delete Product.Category
}
if (Product && Product.URL) {
const exists = await ProductService.checkProductByUrl(Product.URL);
_id = exists._id
}
const result = await ProductService.saveProduct(req.body, _id);
if (result) {
if (_id) {
console.log('Here.... UPDATE')
const savedProduct = await ProductModel.createPayload(req.body);
console.log(savedProduct,'saved_product')
let elaticDoc = await this.createElasticDocData(savedProduct);
console.log(elaticDoc.id,'elasticResult')
elaticDoc.id = result._id;
elaticDoc = new Elastic(elaticDoc);
console.log(elaticDoc,'<----------elaticdoc-------------->')
elasticResult = await elasticService.updateDocument(JSON.stringify(elaticDoc), req.body.Category)
console.log(elasticResult,'elasticResult')
}
else {
console.log('Here.... ADD')
const savedProduct = await ProductModel.createPayload(result);
let elaticDoc = await this.createElasticDocData(savedProduct);
elaticDoc.id = result._id;
elaticDoc = new Elastic(elaticDoc);
elasticResult = await elasticService.createDocument(JSON.stringify(elaticDoc), req.body.Category)
}
const response = new Response(1, "Product is saved successfully", "", "", { product: result, elasticResult: elasticResult });
return res.status(200).send(response);
}
const response = new Response(0, "Error in saving Product", 0, "Product not saved", {});
return res.status(200).send(response);
} catch (error) {
const response = new Response(0, "Unexpected Error", 0, error, {});
return res.status(400).send(response);
}
}
'''
This is the elasticappsearch file where above mentioned is coming from and for some reason it's not working after axios.patch part.
'''
const private_key = process.env.elastic_private_key
const search_key = process.env.elastic_search_key
const axios = require("axios")
class ElasticAppSearch {
async updateDocument(body, engine) {
console.log('Its coming in updateDOCS here')
const response = await axios.patch(`${process.env.elastic_url}/${engine}/documents`, body, {
headers: {
Authorization: `Bearer ${private_key}`,
},
});
console.log(response,'<--===-=-=-=-=-=-=-=-=-=-=-=-response')
return response.data
}
'''

How would I set a manual gas limit in web3? To get the smart contract to execute?

I'm having a problem executing my smart contract. From the error code, I figured it is must be a gas limit problem, although I don't know where I would place the code in order for it to execute properly. Any suggestions?
Solidity code:
pragma solidity ^0.8.0;
import 'hardhat/console.sol';
contract WavePort {
//TrackWaves
uint totalWaves; //State Variable, Permanetly Stored In Contract Storage
constructor() {
console.log("Yo, I am I contract");
}
//Function Increments Waves On The Blockchain/ Immutable Never Decreasing
function wave() public {
totalWaves += 1;
console.log("%s has waved!", msg.sender);
}
//Function Returns Us the The Total Waves To Be Viewed
function getTotalWaves()public view returns(uint256) {
console.log("We have %d total waves", totalWaves);
return totalWaves;
}
}
JavaScript code:
const App = () => {
const [currentAccount, setCurrentAccount] = useState("")
const contractAddress = "contractAddress"
const contractABI = abi.abi
const checkIfWalletConnected = async () => {
let web3
try {
const {ethereum} = window;
if(!ethereum) {
window.alert("Make sure you have metamask !");
return;
}else {
web3 = new Web3(window.ethereum)
console.log("We have the ethereum object", ethereum)}
const accounts = await ethereum.request({method: 'eth_accounts'})
if(accounts.length !== 0) {
const account = accounts[0]
console.log("Found an Authorized account:", account, );
setCurrentAccount(account)
} else {
window.alert("NO authorized account found")
}
const EthBalance = await web3.eth.getBalance(accounts[0])
console.log(EthBalance)
}catch(err) {console.log(err)}
}
const connectWallet = async () => {
try {
const {ethereum} = window;
if(!ethereum) {alert("Get Metamask extenstion")
return
} else {
const accounts = await ethereum.request({method: 'eth_accounts'})
console.log("Connected", accounts[0])
window.alert("Wallet is Connected")
setCurrentAccount(accounts[0])
const ethBlance = await Web3.eth.getBalance(currentAccount)
console.log(ethBlance)
}
}catch(err) {
console.log(err)
}
}
const wave = async () => {
try {
const {ethereum} = window;
if(ethereum) {
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const wavePortalContract = new ethers.Contract(contractAddress, contractABI, signer);
let count = await wavePortalContract.getTotalWaves( );
const waveTxn = await wavePortalContract.wave({gas:10000000 }, {gasPrice:80000000000});
console.log("Mining....", waveTxn.hash)
await waveTxn.wait( );
console.log("Mined-- ", waveTxn.hash)
count = await await wavePortalContract.getTotalWaves( );
console.log("Retrieved total wave count.. ", count.toNumber())
}else {
console.log("Eth Object doesn't exist!")
}
} catch(err) {console.log(`${err} hello world`) }
}
useEffect(() => {
checkIfWalletConnected();
}, [])
The error code I get:
Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"code":-32000,"message":"execution reverted"}, method="call", transaction={"from":"0xD49a9a33F180D1e35A30F0ae2Dbfe5716a740Ebc","to":"0x5FbDB2315678afecb367f032d93F642f64180aa3","data":"0x9a2cdc08","accessList":null}, code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.5.1)
While calling a contract Abi method, you can pass an object of additional gas-related params in the second argument (or first if you don't have any arguments in your method).
So calling of wave function should looks like following:
const waveTxn = await wavePortalContract.wave({gasLimit:30000});
Check all additional params in the below documentation.
https://docs.ethers.io/v5/api/contract/contract/#contract-functionsSend

Is this Transaction valid?

I am wondering if this transaction is even valid and actually ensuring quantity is being the most up to date.
async function deductQuantity(orders: [Order]) : Promise<boolean> {
try {
let document = await admin.firestore().collection("MenuItems")
orders.forEach(async (order)=> {
let itemDoc = (await document.where(`item.catalogType`, "==", order.catalogType).where(`item.id`, "==", order.item.id))
let get = await itemDoc.get()
get.forEach(async a=> {
const pp = document.doc(a.id)
await admin.firestore().runTransaction(async (t)=> {
const mostRecentDoc = await t.get(pp)
const data = await mostRecentDoc.data()
if (data == undefined){
return
}
const newQuantity = data.item.quantity - order.quantity
await t.update(pp, {[`item.quantity`] : newQuantity})
})
})
})
return true
} catch (error) {
console.log("dum: " + error)
return false
}
}
the part where I do let get = await itemDoc.get(), and get.ForEach, is kind of unnecessary because I know, that it will only return one document that matches the query field, but I need to forEach it in order to get the child component\s. Anyways, is it a valid transaction?

Cosmos DB query with JavaScript API v2 query for 1 doc

I have an async call chain that looks like this:
getConnections()
.then(() => addOneNewDoc())
.then(() => fetchOneDoc());
The addNewDoc() works fine and inserts a document. I then use the query capabilities of the API to query for the document in fetchOneDoc().
The call to fetch doc always returns undefined, but I can go see the document in the portal db browser. I've tried sleeping between the calls in case the doc just didn't make it in before the query, but that didn't work either.
const query = `select * from items i where i.id = '${docId}'`;
const {result: doc} = await connection.container.items.query(query);
if (!doc) {
console.log('GOT NO DOCS BACK');
return;
}
I have validated the query works fine in the portal.
Please refer to my sample code:
const cosmos = require('#azure/cosmos');
const CosmosClient = cosmos.CosmosClient;
const endpoint = "https://***.documents.azure.com:443/"; // Add your endpoint
const masterKey = "***"; // Add the masterkey of the endpoint
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const databaseId = "db";
const containerId = "coll";
async function run() {
await insertItem();
}
async function insertItem(continuationToken) {
const { container, database } = await init();
const documentDefinition = { content: 'Hello World!' };
const { body } = await container.items.create(documentDefinition);
console.log('Created item with content: ', body.id);
return await queryItems1(body.id);
}
async function queryItems1(idParam) {
const { container, database } = await init();
const querySpec = {
query: "SELECT r.id,r._ts FROM root r where r.id = '"+ idParam +"'"
};
const queryIterator = await container.items.query(querySpec,null);
if (queryIterator.hasMoreResults()) {
const { result: results, headers } = await queryIterator.executeNext();
console.log(results)
}
}
async function init() {
const { database } = await client.databases.createIfNotExists({ id: databaseId });
const { container } = await database.containers.createIfNotExists({ id: containerId });
return { database, container };
}
run().catch(err => {
console.error(err);
});

async await inside function not working properly?

I have this function, that i need to define an async function inside it:
_refetchConnection = (page) => { // query for cursor page
const refetchVariables = async (fragmentVariables) => {
let pageCursor;
if(page !== 1) {
const getAfterCursorQueryText = `
query($count: Int!, $cursor:String) {# filename+Query
viewer {
publicTodos (first: $count, after: $cursor) {
edges {
cursor
node {
id
}
}
pageInfo { # for pagination
hasPreviousPage
startCursor
hasNextPage
endCursor
}
}
}
}`;
let cursor = fragmentVariables.cursor;
let count = 5;
const getAfterCursorQuery = { text: getAfterCursorQueryText };
const result = await this.props.relay.environment._network.fetch(getAfterCursorQuery, {cursor, count});
pageCursor = result.data.viewer.publicTodos.pageInfo.endCursor;
} else if (page === 1) {
pageCursor = null;
}
return {
cursor: pageCursor,
count:5
}
}
this.props.relay.refetch(refetchVariables, null);
};
but there's no returned value on refetchVariables, it only had when I do not use async but i need to perform await for this code, and I need access on fragmentVariables:
const result = await this.props.relay.environment._network.fetch(getAfterCursorQuery, {cursor, count});
maybe making refetchVariables not an async works? but I have no idea how to code it. help? btw this is the value returned on async refetchVariables:
ƒ refetchVariables(_x2) {
return _ref3.apply(this, arguments);
}

Categories

Resources