Whenever i ping my bot it shows the API latency as NaNms - javascript

Whenever I ping my discord.js bot it shows the API latency as NaNms
This is the output
This is the code
module.exports = {
name: 'ping',
description: 'Pings the bot!',
usage: '​',
execute(message) {
const pingEmbed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('Pong!')
.setThumbnail('https://i.gifer.com/fyMe.gif')
.addFields(
{ name: 'Latency - ', value: `${Date.now() - message.createdTimestamp}ms`, inline: true },
{ name: 'API Latency', value: `${Math.round(client.ws.ping)}ms`, inline: true },
)
.setTimestamp();
message.channel.send(pingEmbed);
},
};

You didnt pass the client as here it's undefined
Either pass the client or use message.client.ws.ping
That's the solution unless the code sample you gave is no full one.

i had this issue too, the problem is that you're adding the client.ws.ping part in the embed instead of the command.
The embed wont have:
client.on('messageCreate', (message) => {}
which is why it gives out "NaNms"
so instead of a separate embed i just made the embed within the command and it works fine, here (but depending on how different the way you set your bot up, it might not work) :
message.channel.send({embeds:[{
title:'Pong!',
description:`API Latency: ${client.ws.ping}`
}]
});

Related

Discord.js: TypeError: Cannot read properties of null (reading 'status')

So I have a command that outputs user information. Though most fields have no problems, the Status field is rather buggy for me.
This is the code for the command:
import { Command } from '#sapphire/framework';
import { MessageEmbed } from 'discord.js';
export class UserInfoCommand extends Command {
constructor(context, options) {
super(context, {
...options,
name: 'userinfo',
description: 'Retrives user information.',
aliases: ['user'],
});
}
async messageRun(message, args) {
const userInfo = await args.pick('member').catch(() => message.member);
const roleMap = userInfo.roles.cache.mapValues(roles => roles.name);
const roleArray = Array.from(roleMap.values());
const userEmbed = new MessageEmbed()
.setTitle(`Information about ${userInfo.displayName}#${userInfo.user.discriminator}`)
.setColor(0xC63D85)
.setThumbnail(userInfo.displayAvatarURL())
.addField('ID', `${userInfo.id}`, true)
.addField('Status', `${userInfo.presence.status}`, true)
.addField('Account Created:', `${userInfo.user.createdAt}`)
.addField('Joined on:', `${userInfo.joinedAt}`)
.addField('Server Nickname:', `${userInfo.displayName}`)
.addField('Server Roles:', `${roleArray.join(', ')}`);
return message.channel.send({ embeds: [userEmbed] });
}
}
When executing the command with me (or a user offline since the bot was started), it throws TypeError: Cannot read properties of null (reading 'status'). When I go online and then offline once again, the command works and outputs offline as my status.
I do have the proper intents enabled.
const client = new SapphireClient({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MEMBERS', 'GUILD_PRESENCES'],
disableMentionPrefix: true,
typing: true,
presence: {
activities: [
{
name: 'Captain\'s commands!',
type: 'LISTENING',
},
],
},
});
I've tried to use an if statement where if userInfo.presence.status is null then it should throw offline instead but that didn't work out. How can I make this work out properly?
Make sure you have the PRESENCE INTENT option enabled in the applications bot settings
This setting is required to get presence updates
Replaced the line with:
.addField('Status', `${userInfo.presence? userInfo.presence.status : "offline"}`, true) // if presence is truthy, output the string, else, the user is offline
A simple null check that worked. Probably my previous method was wrong.

Getting bot to react to it's own message

How would I make the bot react to it's own message? I know it's probably a simple enough thing but I can't find an answer. Thanks in advance.
module.exports = {
name: "ping",
description: "Basic ping command",
execute(message) {
message.channel.send("Pong.");
message.react("🏓");
},
};
Edit: I forgot to say in here that this is Discord.JS, not python
You have the right idea but you add the reaction to the wrong message. To react to the message the bot has send, you can use the Promise returned by TextChannel.send(). Take a look at the example code below and give it a try:
module.exports = {
name: "ping",
description: "Basic ping command",
execute(message) {
message.channel.send("Pong.").then((botMessage) => {
botMessage.react("🏓");
});
},
};
see this article
the code should be
bot.add_reaction(msg, "🏓")

Set Activity/Presence Command for Discord.js-Commando

So I have this command that sets the bot's "Playing" status:
const commando = require('discord.js-commando');
const { RichEmbed } = require('discord.js');
class sets extends commando.Command {
constructor(client) {
super(client, {
name: 'setgame',
group: 'owner',
memberName: 'setgame',
description: 'Sets the Bots\' activity',
examples: ['Playing __on many servers!__'],
args: [
{
key: "game",
prompt: "What do you want to set my game as?",
type: "string"
}
]
});
}
async run(message, { game } ) {
if (message.author.id !== "442918106378010635"){
message.channel.send("That's for TheRSC only!");
}
else {
this.client.bot.setActivity(game)
const embed = new RichEmbed()
.setColor(0x00AE86)
.setDescription("Game set!");
message.channel.send({embed});;
}
}
}
module.exports = sets;;
I ran into a few bugs before and managed to fix them, but this one stumps me. No matter how I code it, I keep getting: TypeError: Cannot read property 'setActivity' of undefined
I've tried a few things, having text be defined in run, putting args.game into .setActivity() and it keeps spitting out that error. I tried the splitting the args method but that didn't work either. Any ideas? (As a side note, I'd also like to turn this into a .setPresence command if possible.)
Note: I am a beginner at coding, so I may be doing something that the average coder wouldn't.
Try changing
client.bot.setActivity(game)
to
client.user.setActivity(game)
You can take a look at this example provided by the official documentation on setActivity() if you need more help, or if my solution doesn't work.
client.user.setActivity('YouTube', { type: 'WATCHING' })
.then(presence => console.log(`Activity set to ${presence.game ? presence.game.name : 'none'}`))
.catch(console.error);
EDIT: I still think it has something to do with the .bot part because the only reference on the documentation of .bot was a boolean of whether or not a user was a bot.

Getting values from my web chat call in my website using backchannel

I'm trying to integrate the backchannel and getting the values.
https://github.com/Microsoft/BotFramework-WebChat/tree/master/samples/15.d.backchannel-send-welcome-event
I also tried this. Get URL Referer and Origin header from Microsoft Bot Framework
I also tried deserializing the values still not able to get the data.
how can i get the language values?
here's my sample code:
var userinfo = {
id: 'user-id',
name: 'user name',
locale: 'es'
};
var botConnection = new BotChat.DirectLine({
token: 'mytoken',
user: userinfo,
locale: 'es'
});
BotChat.App({
botConnection : botConnection,
user: userinfo,
bot: { id: 'bot-id', name: 'bot name' },
}, document.getElementById('botDiv'));
botConnection
.postActivity({
from: userinfo,
name: 'ConversationUpdate',
type: 'event',
value: '',
})
.subscribe(function (id) {
console.log('"trigger ConversationUpdate" sent');
});
The purpose of this I want to pass the locale to my bot from my website.
just like in the emulator.
Thanks!
I would recommend adding the locale to the back channel event's channel data. That way on the bot side you can simply access the locale in the incoming activity without having to deserialize any JSON objects when you receive the event. Note, you can also use text or value in place of channelData. See the code snippets below.
BotChat Back Channel Event
// Send back channel event
botConnection.postActivity({
from: userinfo,
name: 'setLocale',
type: 'event',
channelData: "es"
}).subscribe(id => console.log(id));
Bot - C#
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext.Activity.Type == ActivityTypes.Message)
{
...
} else if (turnContext.Activity.Type == "event") {
// Check for `setLocale` events
if (turnContext.Activity.Name == "setLocale") {
await turnContext.SendActivityAsync($"Your locale is set to {turnContext.Activity.ChannelData}");
}
}
else
{
await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");
}
}
Hope this helps!

Google Pay - ERROR: Request Failed - Unexpected developer error, please try again later

When I try to pay(on TEST environment) with Google Pay on a real device I get a the error in the title.
I have tried changing 'gateway' into a string like the google docs show it but so far nothing.
const DETAILS = {
id: 'COMPANY',
displayItems: [
{
label: 'Phone Bill',
amount: { currency: 'USD', value: compTotal }
}
],
total: {
label: 'COMPANY',
amount: { currency: 'USD', value: compTotal }
}
};
// GOOGLE PAY
const METHOD_DATA = [{
supportedMethods: ['android-pay'],
data: {
supportedNetworks: ['visa', 'mastercard', 'amex'],
currencyCode: 'USD',
environment: 'TEST', // defaults to production
paymentMethodTokenizationParameters: {
tokenizationType: 'GATEWAY_TOKEN',
parameters: {
gateway: 'braintree',
'braintree:tokenizationKey': 'sandbox_XXXXXXXXXXX'
}
}
}
}];
const paymentRequest = new PaymentRequest(METHOD_DATA, DETAILS);
paymentRequest.show()
.then(paymentResponse => {
const { getPaymentToken } = paymentResponse.details;
return getPaymentToken()
.then(paymentToken => {
const { ephemeralPublicKey, encryptedMessage, tag } = paymentToken.details;
return fetch('...', {
method: 'POST',
body: {
ephemeralPublicKey,
encryptedMessage,
tag
}
})
.then(res => res.json())
.then(paymentResponse.complete('success'), handleConfirm())
.catch(paymentResponse.complete('fail'), alert(1));
});
});
};
Expected result would be the payment going through.
To learn more about this error, follow these steps:
1- Make sure Android Debug Bridge (adb) is installed on your computer..
Make sure USB debugging is enabled on your device. For more information, see Debug Your App.
2- Connect your phone to the computer with a USB cable.
3- Run the following command in a terminal or command prompt on your computer:
adb -d logcat -s WalletMerchantError
Turns out I was not able to do this with React-Native because 'React Native Payments' did not fully support Google Pay which in turn did not fully support Braintree & didn't support Payeezy at all.
I had to resort to native code(Java) and then link React-Native to that native module. It was pretty simple.
I used this demo on Github to guide me through it. I was using Braintree as the payment processor but looks like I will be switching to Payeezy.
I was getting the error in the title because like I said Google Pay wasn't supported fully by 'React-Native-Payments' which in turn didn't support Braintree and when the error was accuring because I was only giving this info -
parameters: {
gateway: 'braintree',
'braintree:tokenizationKey': 'sandbox_TOKEN-HERE'
}
But looks like I needed to use this(In the Java Module) -
.put("gateway", "braintree")
.put("braintree:apiVersion", "v1")
.put("braintree:sdkVersion", "BETA")
.put("braintree:clientKey", "sandbox_TOKEN-HERE")
.put("braintree:merchantId", "TOKEN-HERE"));
I have the some error because of mismatch type of price object.
I put the float value in totalPrice.
After update
data class TransactionInfo(
#SerializedName("totalPrice") val price: String,
#SerializedName("totalPriceStatus") val priceStatus: String,
#SerializedName("currencyCode") val currency: String
)
This is works fine on ENVIRONMENT_TEST case.
Use https://google.com/pay under supportedMethods to leverage Google Pay through Payment Request API.
Check these couple of examples for further reference: official docs, sample from the Chrome team.

Categories