Getting username from GuildMember - javascript

When I was coding a guildMemberAdd and a guildMemberRemove I ran across an issue... So, I was wondering, how do you obtain the user's username and discriminator from when they join? as when I tried member.username and member.discriminator it logs as undefined and undefined
Code below, nothing was printed to console upon this issue:
exports.run = (client, member) => {
member.guild.channels.find(`name`, `mod-logs`).send({embed: {
"color": 8311585,
"footer": {
"text": "Bot made by: Pawxeric#0858"
},
"author": {
"name": "New Member",
"icon_url": member.avatarURL
},
"fields": [
{"name": `${member.username}#${member.discriminator}`, // logs as undefined#undefined
"value": "Joined"}
]
}});
}
Also, the code is having issues picking up anything that uses the member value. Like avatarURL, username, and discriminator. If there's something I'm missing, please share down below :3c

I think you want to get properties from a user object
<member>.user
User has username, discriminator and avatarurl.
The full object can be found on https://discord.js.org/

Related

Can't query by ID as second parameter with AWS DataStore

I am total noob to AWS, DataStore, and DynamoDB. I can't figure out why this isn't working.
If I attempt query an object related to my users ID from Cognito this seems to work. If I console log I get an array with one User.
let profile = await DataStore.query(User, (u) =>
u.id('eq', user.attributes.sub)
);
// Returns [Model]
console.log('[LOADING USER DATA]', profile);
If I attempt query an object related to my users ID like this. (as recommended by the docs). I get undefined.
let profile = await DataStore.query(User, user.attributes.sub);
// Returns undefined
console.log('[LOADING USER DATA]', profile);
Dynamo Data looks fine to me but am I using the wrong primary key ID field or something?
{
"id": "929e6e62-e3a0-4b84-b050-72c53eebda93",
"_lastChangedAt": 1644433699,
"status": "Active",
"createdAt": "2022-02-09T19:08:18.548Z",
"name": "Test",
"orgs": [
"b6508155-f5cf-49b7-88d6-0e605677c4e4"
],
"_version": 1,
"role": "User",
"updatedAt": "2022-02-09T19:08:18.548Z",
"orgID": "b6508155-f5cf-49b7-88d6-0e605677c4e4",
"title": ""
}
What am I doing wrong?

Discord.js test if a user is offline

I'm working on my bot and I can't get it to respond. I am offline so I'm testing on myself.
Here is my js:
if (member[message.guild.id].id.user.presence.status === "offline") {
client.channel.get(status[message.guild.id]).send("Offline");
}
When it refers to member its a json file and here is its value if this helps
{
"719634604008538192": {
"id": "638368326996983848",
"bot": false,
"username": "丂んムW刀 りの乇丂",
"discriminator": "2435",
"avatar": "afbec0b7cc719ba3d103a60bf72e220e",
"lastMessageChannelID": "719969405034954834",
"flags": 0,
"createdTimestamp": 1572269269466,
"defaultAvatarURL": "https://cdn.discordapp.com/embed/avatars/0.png",
"tag": "丂んムW刀 りの乇丂#2435",
"avatarURL": "https://cdn.discordapp.com/avatars/638368326996983848/afbec0b7cc719ba3d103a60bf72e220e.webp",
"displayAvatarURL":
"https://cdn.discordapp.com/avatars/638368326996983848/afbec0b7cc719ba3d103a60bf72e220e.webp"
}
}
I didn't get any errors but I think it's just the if statement not being true.
First of all, you shouldn’t need to store the members in a JSON file. You can just use the Discord.js API, such as Guild#members.
To test if a user is online, use Presence#status:
const member = /* however you want to get the member */
// To get a member from a guild by ID, use guild.members.cache.get(id)
// To get a guild by ID, use client.guilds.cache.get(id)
if (member.presence.status === 'online') {
// member is online; do something here
}

Dialogflow Fulfilment webhook call failed

I am new to dialogflow fulfillment and I am trying to retrieve news from news API based on user questions. I followed documentation provided by news API, but I am not able to catch any responses from the search results, when I run the function in console it is not errors. I changed the code and it looks like now it is reaching to the newsapi endpoint but it is not fetching any results. I am utilizing https://newsapi.org/docs/client-libraries/node-js to make a request to search everything about the topic. when I diagnoise the function it says " Webhook call failed. Error: UNAVAILABLE. "
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const http = require('http');
const host = 'newsapi.org';
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('63756dc5caca424fb3d0343406295021');
process.env.DEBUG = 'dialogflow:debug';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((req, res) =>
{
// Get the city
let search = req.body.queryResult.parameters['search'];// search is a required param
// Call the weather API
callNewsApi(search).then((response) => {
res.json({ 'fulfillmentText': response }); // Return the results of the news API to Dialogflow
}).catch((xx) => {
console.error(xx);
res.json({ 'fulfillmentText': `I don't know the news but I hope it's good!` });
});
});
function callNewsApi(search)
{
console.log(search);
newsapi.v2.everything
(
{
q: 'search',
langauge: 'en',
sortBy: 'relevancy',
source: 'cbc-news',
domains: 'cbc.ca',
from: '2019-12-31',
to: '2020-12-12',
page: 2
}
).then (response => {console.log(response);
{
let articles = response['data']['articles'][0];
// Create response
let responce = `Current news in the $search with following title is ${articles['titile']} which says that
${articles['description']}`;
// Resolve the promise with the output text
console.log(output);
}
});
}
Also here is RAW API response
{
"responseId": "a871b8d2-16f2-4873-a5d1-b907a07adb9a-b4ef8d5f",
"queryResult": {
"queryText": "what is the latest news about toronto",
"parameters": {
"search": [
"toronto"
]
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
""
]
}
}
],
"intent": {
"name": "projects/misty-ktsarh/agent/intents/b52c5774-e5b7-494a-8f4c-f783ebae558b",
"displayName": "misty.news"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 543
},
"languageCode": "en"
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
},
"outputAudio": "UklGRlQqAABXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAAZGF0YTAqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... (The content is truncated. Click `COPY` for the original JSON.)",
"outputAudioConfig": {
"audioEncoding": "OUTPUT_AUDIO_ENCODING_LINEAR_16",
"synthesizeSpeechConfig": {
"speakingRate": 1,
"voice": {}
}
}
}
And Here is fulfillment request:
{
"responseId": "a871b8d2-16f2-4873-a5d1-b907a07adb9a-b4ef8d5f",
"queryResult": {
"queryText": "what is the latest news about toronto",
"parameters": {
"search": [
"toronto"
]
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
""
]
}
}
],
"intent": {
"name": "projects/misty-ktsarh/agent/intents/b52c5774-e5b7-494a-8f4c-f783ebae558b",
"displayName": "misty.news"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 543
},
"languageCode": "en"
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
},
"outputAudio": "UklGRlQqAABXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAAZGF0YTAqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... (The content is truncated. Click `COPY` for the original JSON.)",
"outputAudioConfig": {
"audioEncoding": "OUTPUT_AUDIO_ENCODING_LINEAR_16",
"synthesizeSpeechConfig": {
"speakingRate": 1,
"voice": {}
}
}
}
Also here is the screenshot from the firebase console.
Can anyone guide me what is that I am missing in here?
The key is the first three lines in the error message:
Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'newsapi'
It is saying that the newsapi module couldn't be loaded and that the most likely cause of this is that you didn't list this as a dependency in your package.json file.
If you are using the Dialogflow Inline Editor, you need to select the package.json tab and add a line in the dependencies section.
Update
It isn't clear exactly when/where you're getting the "UNAVAILABLE" error, but one likely cause if you're using Dialogflow's Inline Editor is that it is using the Firebase "Spark" pricing plan, which has limitations on network calls outside Google's network.
You can upgrade to the Blaze plan, which does require a credit card on file, but does include the Spark plan's free tier, so you shouldn't incur any costs during light usage. This will allow for network calls.
Update based on TypeError: Cannot read property '0' of undefined
This indicates that either a property (or possibly an index of a property) is trying to reference against something that is undefined.
It isn't clear which line, exactly, this may be, but these lines all are suspicious:
let response = JSON.parse(body);
let source = response['data']['source'][0];
let id = response['data']['id'][0];
let name = response['data']['name'][0];
let author = response['author'][0];
let title = response['title'][0];
let description = response['description'][0];
since they are all referencing a property. I would check to see exactly what comes back and gets stored in response. For example, could it be that there is no "data" or "author" field in what is sent back?
Looking at https://newsapi.org/docs/endpoints/everything, it looks like none of these are fields, but that there is an articles property sent back which contains an array of articles. You may wish to index off that and get the attributes you want.
Update
It looks like that, although you are loading the parameter into a variable with this line
// Get the city and date from the request
let search = req.body.queryResult.parameters['search'];// city is a required param
You don't actually use the search variable anywhere. Instead, you seem to be passing a literal string "search" to your function with this line
callNewsApi('search').then((output) => {
which does a search for the word "search", I guess.
You indicated that "it goes to the catch portion", which indicates that something went wrong in the call. You don't show any logging in the catch portion, and it may be useful to log the exception that is thrown, so you know why it is going to the catch portion. Something like
}).catch((xx) => {
console.error(xx);
res.json({ 'fulfillmentText': `I don't know the news but I hope it's good!` });
});
is normal, but since it looks like you're logging it in the .on('error') portion, showing that error might be useful.
The name of the intent and the variable I was using to make the call had a difference in Casing, I guess calls are case sensitive just be aware of that

How to validate $set 'keys' with MongoDB?

I've got a rather specific case: Using mongoose/mongo and user objects
I want to find and update user in one call.
DB.collection('users').findOneAndUpdate({localId: id} ,{ "$set": { "name": "lla", "usnme": "As"} } ,callback);
Note that 'username' is spelled wrong. Yet mongo updated the first field(name) and does not give any error about the second.
How can I validate the keys I pass in $set without making more than one query?
What MongoDB suggests here is called schema validation:
In your specific case you could run the following command to make sure that no additional ("incorrect") fields can be added by anyone:
db.runCommand({ "collMod": "users", "validator": {
$jsonSchema: {
additionalProperties: false,
properties: {
"_id": {
bsonType: "objectId"
},
"name": {
bsonType: "string"
},
"username": {
bsonType: "string"
}
}
}
}})
Beyond that I cannot really think of any solution since MongoDB is a document database which by default is schemaless and hence won't stop you from creating the fields you tell it to create...

Publish and Subscribe do not work correctly

Publish and Subscribe did not work. Please find the solution as an answer down below.
Initial question:
I am trying to publish the facebook first_name which is automatically retrieved when logging in with the accounts facebook package in Meteor (stored in the user collection under services.facebook). I have autopublish and insecure removed.
What I have tried so far looks like this:
Server side
Meteor.publish("facebook_name", function() {
return Meteor.users.find({_id: this.userId},
{fields: {'services.facebook.first_name' : true} });
});
Client side
Meteor.subscribe('facebook_name');
What I am using in my template to display it is this
<div class="Name"><p>{{currentUser.services.facebook.first_name}}</p></div>
Before removing autopublish the name showed up in the template.
Found the solution to my problem:
When setting up your meteor project in your client/main.js it will show import './main.html'; if you are working with routing and templates and not the main.html template this will prevent publish and subscribe to work correctly.
When user is logged in via facebook oauth API and the authentication was implemented using meteor accounts-facebook, then all needed data is stored in current user object ( Meteor.user() ).
So, the schema of user in your case looks similar to this:
{
"_id": "Ap85ac4r6Xe3paeAh",
"createdAt": "2015-12-10T22:29:46.854Z",
"services": {
"facebook": {
"accessToken": "XXX",
"expiresAt": 1454970581716,
"id": "XXX",
"email": "ada#lovelace.com",
"name": "Ada Lovelace",
"first_name": "Ada",
"last_name": "Lovelace",
"link": "https://www.facebook.com/app_scoped_user_id/XXX/",
"gender": "female",
"locale": "en_US",
"age_range": {
"min": 21
}
},
"resume": {
"loginTokens": [
{
"when": "2015-12-10T22:29:46.858Z",
"hashedToken": "XXX"
}
]
}
},
"profile": {
"name": "Sashko Stubailo"
}
}
Thus, if you want to retrieve a name of a user, all you need to do is to publish current user to a client and then get username from user object.
// server
Meteor.publish("userData", function () {
return Meteor.users.find({_id: this.userId});
});
// client
Meteor.subscribe("userData");
Template.templateName.helpers({
// this function returns username
Username : function(){
// if user is logged in using facebook; otherwise user is logged in using password
if (Meteor.user().profile.name)
return Meteor.user().profile.name;
else
return Meteor.user().username;
}
Now you can display a name of a user in your view: {{Username}}
Here is more info...

Categories

Resources