How can I make the bot work? - javascript

I am trying to send messages to a bot based on Microsoft bot framework.
Here is my code.
const builder = require("botbuilder");
\\I have id and password, did not show them here
const config = {
appId: "**********************",
appPassword: "********************"
};
const connector = new builder.ChatConnector(config);
const bot = new builder.UniversalBot(connector);
// respond to bot messages
app.post("/bot", () => console.log('being called') ,connector.listen());
// define bot dialog routes
bot.dialog("/", session => {
console.log('++++++++++++++>', session.message.text)
});
It is printing the "being called ", but not printing "++++++++++++++>".
I got no error message.
How can I check the problem and fix this?
Note: this is not emulator, i ma trying this within an app locally.

Whilst there appears to be missing code (e.g. app isn't defined), I'm going to presume you're using Express and that side of things is fine. Your root dialog will not be triggered until it has an input from the user.
Take this super simple ConsoleConnector example:
const builder = require('botbuilder')
let connector = new builder.ConsoleConnector().listen()
let bot = new builder.UniversalBot(connector)
bot.dialog('/', (session) => {
console.log('Testing')
})
Paste that into a file and run it. You'll notice that you won't get any error messages, but you won't see the console log either. Now type anything in and press return. This will trigger the root dialog and the console.log will fire.
If you want to send a proactive message when the conversation starts, check out the 'Greet a user' example in the Bot Framework documentation.
Edit:
Additional Echo Bot example using Express:
const express = require('express')
const builder = require('botbuilder')
const app = express()
const port = 8080
const connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
})
const bot = new builder.UniversalBot(connector)
bot.dialog('/', (session) => {
console.log('Testing')
session.send(session.message.text)
})
app.post('/api/messages', connector.listen())
app.listen(port)
I realise you're not using the Emulator at this point, but for the sake of testing, point it at localhost:8080/api/messages and type something. You'll see the console.log message appear and the message you entered will be echoed back to you.

Related

Unable to use Datastore emulator with Nodejs application

I am trying to use datastore emulator with my nodejs application
Initially I have followed the instructions given in here
Then in my node application :-
var config = {
projectId : "scio1-ts-datastore"
}
const datastore = require("#google-cloud/datastore")
const db = new datastore.Datastore(config)
const setdata = async () => {
await db.save(({
key : db.key('orders') ,
data : {
orderId : 1 ,
orderType : "Hazardous"
}
}))
}
const getdata = async () => {
const query = db.createQuery('orders')
const [orders] = await db.runQuery(query)
console.log(orders)
}
setdata()
getdata()
After this I had to run gcloud auth application-default login which I think is not needed to run as I am using datastore Emulator .
But even after this I am unable to run the app
Following error pops up :-
Not sure if this is the same issue, but for me a problem was that nodejs client did not "listen" to the environmental variables I set up (as part of the instructions you linked) and I had to initialize the datastore with endpoint explicitly given:
this.datastore = new Datastore({
apiEndpoint: "0.0.0.0:8081"
});
or whichever port the emulator says it's listening on.
Also make sure that the ~/.config/gcloud directory contains the application_default_credentials.json - unsure if emulator really needs it, but it worked for me after these steps.
Edit: if you are running the app through webstorm or such, it's good to note that environmental variables are loaded when you start it. So if it's already running when you set the variables, restart it!

How to send dm as bot after voted top.gg discord.js?

const Discord = require(discord.js);
const client = new Discord.Client();
const Topgg = require ("#top-gg/sdk");
So i dont know about next code
Sorry im to early for studying in javascript
In here im using discord.js V12
You're not yet requiring Discord properly. It should be require("discord.js"); otherwise you're trying to require a non-existent variable.
Upon scrolling through the Top.gg API Docs it looks like you can use the webhook class to get when a user votes.
const Discord = require("discord.js");
const Client = new Discord.Client();
// top.gg example
const Topgg = require("#top-gg/sdk");
// Webhook options can be found here if you wish to include them, currently the only one is an error callback: https://topgg.js.org/interfaces/webhookoptions
// You'll have to set up a webhook on top.gg in your bot's settings
const TopWebhook = new Topgg.Webhook("authorization");
const express = require("express");
const app = express();
app.listen(process.env.PORT || 8080);
// This example assumes you're using express
app.post("/webhook", async TopWebhook.listener(vote) => {
let user = vote.user; // the User ID
// get the user from their user id, then send a DM
});
Hopefully this helps note that this is untested so may require some tweaking, but definitely read the documentation.

code to console log members joining isnt working in discord.js

I have been half following a tutorial, half working it out on my own how to code a discord bot in discord.js. I am up to the point where i want to add a welcome message, and after doing the same thing as the person making the tutorial the code isn't console logging a joining member to the server. Here is the code that i have done, and in the tutorial the code would send a welcome message to the selected channel and console log the member.
there is no error message
module.exports = client => {
const channelId = '790887807127650304' // welcome channel
client.on('guildMemberAdd', member => {
console.log(member)
const message = `welcome <#${member.id} to the server!`
const channel = member.guild.channels.cache.get(channelID)
channel.send(message)
})
}
also, for reference, here is the tutorial i have been following;
video
Make sure the gateway intents are enabled in your dev portal for your bot, it's in the bot tab (the same page where you copy the bot's token). This is a change made after the tutorial you linked.
If you want to know why this is required, read this
Also there are a few errors in your code. You typed channelID two different ways and you didnt put '>' after <#${member.id}.
Here it is fixed.
module.exports = client => {
const channelID = '790887807127650304' // welcome channel
client.on('guildMemberAdd', member => {
console.log(member)
const message = `welcome <#${member.id}> to the server!`
const channel = member.guild.channels.cache.get(channelID)
channel.send(message)
})
}

How to get different user in firebase auth

I am working on an app, and part of the functionality of the app is an admin being able to sign in and reset other users' passwords. How do I get a user other than the one currently signed in?
resetForm.addEventListener('submit', (e) => {
e.preventDefault();
let newPass = resetForm['reset-password'].value;
let firebaseUser = auth.user(docId);
console.log(firebaseUser);
});
I understand that that code won't actually reset any password, I just wrote that to see if I could get a user other than the one already signed in. I ran it, but instead of seeing the User UID in the console I saw this:
Uncaught TypeError: auth.user is not a function
Edit:
I have created a cloud function. Here is the code of my index.js file:
var functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("/removed-for-privacy.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://troop-30-elections-web-app.firebaseio.com"
});
exports.resetPassword = functions.https.onCall((docId,newPass) => {
console.log("step 2");
admin.auth().updateUser(docId, {
password: newPass,
}).then(() => {
const modal = document.querySelector('#modal-reset');
M.Modal.getInstance(modal).close();
resetForm.reset();
});
});
Here is the code that runs when the button is pressed:
resetForm.addEventListener('submit', (e) => {
console.log("Step 1");
e.preventDefault();
let newPass = resetForm['reset-password'].value;
const resetPasswordFunction = firebase.functions().httpsCallable('resetPassword');
resetPasswordFunction(docId,newPass);
console.log("Step 1.5");
});
When I open the console, there are no error messages. I see step 1 and step 1.5. Nothing else.
There is no way to identify an application administrator in Firebase Authentication. You will have to build your own infrastructure for this.
Typically this means:
In a trusted environment (like a server you control, or Cloud Function) you use the Admin SDK to change their password.
You then wrap that code into a custom API, that you expose to your application.
You call the API from your application, passing along the ID token of the signed in user.
In the API you verify the ID token, and make sure the caller is authorized for the operation.
You are completely on your own here though, as you can't use Firebase's built in password reset mechanism. That is only available to the signed-in user on the client, to prevent it being abused to spam users.

Cannot read property 'firstName' of undefined at admin.firestore.collection.doc.get.then.doc

I created this Firebase Functions(onCreate user trigger) to return the new user data and create a realtime notification.
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const createNotification = (notification => {
return admin.firestore().collection('notifications')
.add(notification)
.then(doc => console.log('notification added', doc))
})
exports.userJoined = functions.auth.user().onCreate(user => {
return admin.firestore().collection('users').doc(user.uid).get().then(doc => {
const newUser = doc.data()
const notification = {
content: 'Joined the app',
user: `${newUser.firstName} ${newUser.lastName}`,
time: admin.firestore.FieldValue.serverTimestamp()
}
return createNotification(notification)
})
})
The first time I use firebase deploy and create a new user, the trigger works perfectly. But the second and the subsequent attempts the Firebase Function logs returns me the following error:
TypeError: Cannot read property 'firstName' of undefined
at admin.firestore.collection.doc.get.then.doc (/user_code/index.js:28:29)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Given that you key them on the uid, you'll only be able to create it after the user is created. I'm going to assume you do this from the client-side app, right after creating the user.
After you deploy the functions, the next time you run them you're going to have a so-called cold-start, where Cloud Functions spins up a new container for running the new code. This can take some time, and apparently that time is long enough for your client-side app to create the document for the new user.
Repeated calls often won't need to start a new container, in which case your Cloud Function for functions.auth.user().onCreate gets triggered before the client-side app has written the user's document.
I recommend turning the function that sends a notification into an HTTPS triggered Cloud Function, and then explicitly calling it from the client-side app after creating the document.

Categories