Discord.js interaction calculate latency - discord.js

I just started building a Discord bot and I'm trying to get a client-side API latency from the moment when client use the bot's command until they receive a response. In other words, from client to server and server to client. Is that possible?
const axios = require('axios');
module.exports = {
data: new SlashCommandBuilder()
.setName('bored')
.setDescription('Send a random things to do'),
async execute(interaction) {
const url = 'http://www.example.com';
let response;
try {
response = await axios.get(url);
console.log(response.data);
} catch (err) {
console.error(err);
}
const embed = new MessageEmbed()
.setDescription(response.data.activity)
await interaction.reply({embeds: [embed]});
}
}

To get the API latency you can use:
const ping = client.ws.ping;
To get the Bot latency you need to calculate the difference in time between the timestamp of the interaction and the current time.
const botLatency = Date.now() - interaction.createdTimestamp;

Related

Channel Rename Logs Discord.js v12

client.on("channelDelete", async function(channel) {
const loggg = client.channels.cache.get("channel.id");
const logs = await channel.guild.fetchAuditLogs({ limit: 1, type: 'CHANNEL_DELETE' });
const log = logs.entries.first();
if (!log) return;
loggg.send(`channelDeleted: ${channel} ${log.executor.tag} ${channel.type}`);
});
Can someone help me to convert it to channel rename logs with old and new channel and executor

How to send properly a message in twilio conversation with react?

I have a nextjs project and I want to replace the twilio programmable chat with twilio conversations.
I did the following steps:
I did one API which creates or gets (if it is already created) the conversation and returns to the client the conversation unique name and the token
Once I have the conversation unique name and the token I want to send client side one message.
To do so I did the following function:
import { Client, State } from '#twilio/conversations';
import toast from 'react-hot-toast';
const sendMessageToConversation = async (
token: string,
room: string,
message: string
) => {
const client = new Client(token);
client.on('stateChanged', async (state: State) => {
if (state === 'initialized') {
try {
const conversation = await client.getConversationByUniqueName(room);
await conversation.join();
if (message && String(message).trim()) {
await conversation.sendMessage(message);
}
} catch {
toast.error('Unable to create conversation, please reload this page');
}
}
});
};
the problem seems to be const conversation = await client.getConversationByUniqueName(room); which gives the following error:
What do you think I did wrong?
Also is it a better idea to build an API to send messages in this way? I would avoid this because of the possible overhead of the server
UPDATE
I tried to send a message through API. It works and it returns what I expect. For more detail I will put also the code I have on backend side which generates the tokens and the conversations.
I generate tokens for client side with:
import Twilio from 'twilio';
import { config } from '../config';
const client = require('twilio')(
config.TWILIO_ACCOUNT_SID,
config.TIWLIO_AUTH_TOKEN
);
const AccessToken = Twilio.jwt.AccessToken;
const ChatGrant = AccessToken.ChatGrant;
const SyncGrant = AccessToken.SyncGrant;
export const tokenGenerator = (identity: string) => {
const token = new AccessToken(
config.TWILIO_ACCOUNT_SID,
config.TWILIO_API_KEY,
config.TWILIO_API_SECRET
);
token.identity = identity || 'unknown';
if (config.TWILIO_CHAT_SERVICE_SID) {
const chatGrant = new ChatGrant({
serviceSid: config.TWILIO_CHAT_SERVICE_SID,
pushCredentialSid: config.TWILIO_FCM_CREDENTIAL_SID,
});
token.addGrant(chatGrant);
}
if (config.TWILIO_SYNC_SERVICE_SID) {
const syncGrant = new SyncGrant({
serviceSid: config.TWILIO_SYNC_SERVICE_SID || 'default',
});
token.addGrant(syncGrant);
}
return {
identity: token.identity,
token: token.toJwt(),
};
};
I create conversations with:
const client = require('twilio')(
config.TWILIO_ACCOUNT_SID,
config.TIWLIO_AUTH_TOKEN
);
export const createTwilioConversation = async (
partecipantsProfiles: Partial<User>[],
identity: string
) => {
const friendlyName: string = partecipantsProfiles
.map((el) => `${el.first_name} ${el.last_name}`)
.join(' - ');
const conversation = (await client.conversations.conversations.create({
friendlyName,
uniqueName: uuidv4(),
})) as TwilioConversationResponse;
await client.conversations
.conversations(conversation.sid)
.participants.create({ identity });
return conversation;
};
The flow I do in order to send messages is:
If I want to send a message I create a conversation by calling an API, executes the functions above and returns the room unique name and the token. I also store into my DB the room unique name, participants and other infos. I do this only for the first message. If a user has already chatted with another user, then I don't create a conversation anymore, but I return the unique name stored + token generated and I get/send the message client side
I have also tried to send a message through API and it works. I can't figure out why I still can't get the conversation by unique name client side. Maybe I should generate the token differently?
This is the method that sends messages server side:
export const sendMessage = async (
conversationSid: string,
author: string,
body: string
) => {
return await client.conversations
.conversations(conversationSid)
.messages.create({ author, body });
};
Your issue is that you are not using the default Conversations service, but you are not scoping your API calls on the server side to the service you need.
So in pages/api/utils/conversations you need to add .services(config.TWILIO_CHAT_SERVICE_SID) into all your API calls. See below:
export const createTwilioConversation = async (
chatTo: string,
myIdentity: string
) => {
const uniqueName = uuidv4();
const conversation = (await client.conversations
.services(config.TWILIO_CHAT_SERVICE_SID)
.conversations.create({
friendlyName: `Chat created by ${myIdentity}`,
uniqueName,
})) as TwilioConversationResponse;
await client.conversations
.services(config.TWILIO_CHAT_SERVICE_SID)
.conversations(conversation.sid)
.participants.create({ identity: chatTo });
await client.conversations
.services(config.TWILIO_CHAT_SERVICE_SID)
.conversations(conversation.sid)
.participants.create({ identity: myIdentity });
return conversation;
};
export const sendMessage = async (
conversationSid: string,
author: string,
body: string
) => {
return await client.conversations
.services(config.TWILIO_CHAT_SERVICE_SID)
.conversations(conversationSid)
.messages.create({ author, body });
};
Once you've done that, you need to one other thing. Because you add your participant to the conversation using the REST API, you don't need to join the conversation in the front-end. So you can remove the line
await conversation.join();
from src/twilio/index.ts.
One last thing, you can get better error messages in the front-end if you log out error.body rather than just error or error.message.
try {
const conversation = await client.getConversationByUniqueName(room);
if (message && String(message).trim()) {
await conversation.sendMessage(message);
}
} catch (error) {
console.log("error", error);
console.log("error body", error.body);
toast.error("Unable to create conversation, please reload this page");
}
Twilio have an official blog for Build a Chat App with Twilio Programmable Chat and React.js, please check it out once,
Here is the link - https://www.twilio.com/blog/build-a-chat-app-with-twilio-programmable-chat-and-react

How to connect API in reactjs

I and my team are working in Reactjs and I'm completely new to this my part is Connect to API and I follow many resources on the internet, and I don't know that am I on the right track here the code that I did, can someone tell me what I am doing wrong? This part is on the client I want to connect API to the server.I've recieved error:Unexpected reserved word 'await'
useEffect(()=>{
try {
const requestUrl = 'http://localhost:3000/';
const response = await fetch(requestUrl);
const requestJSON = await response.json();
console.log({responseJSON});
const {data} = responseJSON;
setPostEvent(data)
} catch (error) {
console.log('Failed to fetch post list: ',error.message);
}
fetchPostEvent()
},[events])
useEffect(()=>{
localStorage.setItem('events',JSON.stringify(events));
},[events]) ```
You are to use await key word, in an async function. This is how you would make your function async:
useEffect(async()=>{
try {
const requestUrl = 'http://localhost:3000/';
const response = await fetch(requestUrl);
const requestJSON = await response.json();
console.log({responseJSON});
const {data} = responseJSON;
setPostEvent(data)
} catch (error) {
console.log('Failed to fetch post list: ',error.message);
}
fetchPostEvent()
},[events])

My discord bot isn't working after 13.0.0

I am trying out discord.js version 13.1.0 and I am following discord's guide on how to setup a bot. I have followed all the steps. When I have the bot running, and I send a message or a command into the server, nothing gets printed to the console. Any ideas?
My code:
const { Client, Intents } = require("discord.js");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once("ready", () => {
console.log("Ready!");
});
client.on("interactionCreate", (interaction) => {
console.log(interaction);
});
client.login(process.env.TOKEN);
From the Discord Developer Portal:
An Interaction is the message that your application receives when a user uses an application command or a message component.
By an application command is meant a special type of command, that you have to register against the Discord API. To learn more about application commands, read this.
From the discord.js docs main page, how to register an application (slash) command:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
However if you are looking for a way to reply to (or just capture) a normal message sent in a TextChannel, you are probably looking for the messageCreate event.
client.on("messageCreate", (message) => {
console.log(message);
});
Also note that to receive messageCreate event, you need GUILD_MESSAGES intent.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

ReactNative: AsyncStorage not working properly

Hello I am trying to impliment a login and the most of the logic is inside action creator but for some react my code doesn't execute after
await AsyncStorage.setItem('adminFlag', adminFlag);
await AsyncStorage.setItem('token', token);`
the console.log(data) is working before this statement...I have no idea why this is happening
export const verifyPassword = (
adminFlag,
password,
navigate
) => async dispatch => {
loadingStatus(dispatch, true);
try {
const { data } = await axios.post(
"myurl with response success--lajja--token",
{
admin: adminFlag,
job: "verifyPassword",
password
}
);
if (data.includes("--lajja--")) {
//spliting the token and the response
const destructuredData = data.trim().split("--lajja--");
const response = destructuredData[0];
const token = destructuredData[1];
console.log(data);
await AsyncStorage.setItem("adminFlag", adminFlag);
await AsyncStorage.setItem("token", token);
navigate();
loadingStatus(dispatch, false);
}
loadingStatus(dispatch, false);
} catch (e) {
console.log(e);
loadingStatus(dispatch, false);
}
};
the lines after console.log(data) are not working...
The problem happened to me as well as to some people on this issue. This seems to happen on Android devices (only during debug) that are running some background activities as specified here and here. The pull request provided by #github/jsdario to fix that issue seems to have not passed the CI though. I guess for now we have to debug... Without the debugger attached.

Resources