ping and packet loss go up when receiving data from wit.ai - discord

I'm trying to make a discord bot that works with voice commands, (using wit.ai for speech to text) and I have got it working but when it sends or receives data to/from wit.ai the ping goes way up to like 350 ms.
Also the outbound packet loss rate on the voice channel goes up to around 20%, which is annoying, because then you sound robotic and it lags. When you click on debug discord says that my bot is inbound but its not sending anything to the voice channel so why would it be inbound??
The bot sends data to wit.ai every time someone speaks, so it will almost always up at high ping and stuff. If anyone can improve my code (or maybe a different library?) to make it affect the ping and packets(much) then that would be great.
Thanks in advance. Here's the code that runs when someone speaks:
const accessHeaders = function (access_token, others) {
return _.extend(others || {}, {
'Authorization': 'Bearer ' + access_token,
'Accept': 'application/vnd.wit.' + "20170217"
});
};
// Request options
const request_options = {
url: 'https://api.wit.ai/speech',
method: 'POST',
json: true,
headers: accessHeaders('TKOAGFCMGDIRYNZU36XHQDFD32HWXM6O', { 'Content-Type': 'audio/wav' })
};
var wav = require('wav');
var converter = new wav.Writer();
const receiver = member.guild.voiceConnection.createReceiver();
const inputStream = receiver.createPCMStream(member);
inputStream.pipe(converter);
converter.pipe(request(request_options, (error, response, body) => {
receiver.destroy();
if (response && response.statusCode != 200) {
error = "Invalid response received from server: " + response.statusCode;
}
if(error)
return console.log(error);
console.log("you said: " + body._text);
}));

The lag didn't have anything to do with my code. It was on witai's end, and now they've fixed it.

Related

How can I associate an Alexa skill with a catalog?

I am trying to associate my Alexa skill with a catalog that I created by hitting the https://api.amazon.com/v0/catalogs endpoint with an Auth token that I had generated through a LWA profile.
This worked, and I created a catalog like so:
{
associatedSkillIds: [],
createdDate: '2022-01-22T20:50:37.318Z',
id: 'amzn1.ask-catalog.cat.[REDACTED]',
lastUpdatedDate: '2022-01-22T20:50:37.318Z',
title: 'TestCatalog',
type: 'AMAZON.AudioRecording',
usage: 'AlexaTest.Catalog.AudioRecording'
}
However, the next step, associating my Alexa skill with the Catalog is always returning 401 https://developer.amazon.com/en-US/docs/alexa/smapi/catalog-content-upload.html#associate-catalog-with-skill
This is my function to attempt to associate the skill with the catalog:
async associateSkillWithCatalog() {
console.log(`Associating skill...`);
const accessToken = await this.getRefreshToken(); // makes post to https://api.amazon.com/auth/o2/token
console.log(this.alexaEndpoint + this.skillAssoc(cat.id, skillId));
const response = await axios.put(
"https://api.amazonalexa.com/v0/skills/amzn1.ask.skill.[REDACTED]/catalogs/amzn1.ask-catalog.cat.[REDACTED]",
{
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${accessToken}`
}
}
);
return response.data;
}
Always receiving back this Error: Request failed with status code 401\n at createError.
Why would I be receiving 401 Error here, despite other requests against this API not failing?
Thanks!

How to perform a post request with axios on React and pass your data as FormData?

There's this API:http://zssn-backend-example.herokuapp.com/api/, detailed here: http://zssn-backend-example.herokuapp.com/swagger-api/index.html#!/people/Api_People_index . I am trying to do a POST request on this endpoint "/people/{person_id}/properties/trade_item.json"(Make a trade transaction between survivors). On the Website for testing I filled the fields with the following data and got 204 response:
person_id:34e183a6-965e-4a61-8db5-5df9103f4d4b
consumer[name]: Person4
consumer[pick]: AK47:1;Campbell Soup:1
consumer[payment]: First Aid Pouch:2
I investigated a Little and got
this information
didn't understand the "PROPERTY[KEY]:VALUE" representation
When I try to the Request with this code, with the same values(by the way, the database of this API is cleared each 24 hours, so those value might not work, even if you do it in the right way):
this is My code:
async function handleTrade(e){
e.preventDefault();
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
await api.post(
"/people/" + match.params.id + "/properties/trade_item.json",
{
person_id:match.params.id,
name: survivorRef.current,
pick: survivorItemsToPick,
payment: userItemsToPay,
},
config
);
And this is what I get:
Request:
request-description
Response:
response-description
How Can i make this request in the right way in order to get the same result as the first Image ?
You can use FormData to send the request, I made an example:
const data = new FormData();
data.append("customer[name]", "Person4");
data.append("customer[pick]", "AK47:1");
await api.post("/people/" + match.params.id + "/properties/trade_item.json", data, config)

How to post a message in an existing DM as a Slack Bot

My understanding of the chat.postMessage method of the Slack Web API is that you can, as a bot with a bot token, post messaged to public channels. However, if you want to post to DMs - you would need to request a user token and then post on behalf of the user
However, I've used a few apps that are able to post into DMs as an app (and therefore, I assume, are using a bot token). To me this is ideal, so you're not bugging every person in the Slack workspace to get their user token
Can anyone tell me how this is done?
For reference, here is the code I use to post a message as a bot. It does not work for DMs or for private channels the bot has not been invited to. Would love to fix that. Thanks
function getQueryString(data = {}) {
return Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
function postMessageInSlack(bot_token, channelID, userID, message, send_blocks, endpoint) {
const options = {
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
};
const data = {
token: bot_token,
channel: channelID,
text: `${message} from <#${userID}>`,
blocks: JSON.stringify(send_blocks),
}
delete axios.defaults.headers.common["Content-Type"];
axios.post(endpoint,
data, {
options,
transformRequest: getQueryString}
)
.then(res => console.log("result is ", res))
.catch(err => console.log("the error is ", err))
}
You need to open a new conversation with the user, that's if there was none open. To so this you need the conversations.open method. This will return a response that contains the conversation id. You can now use the conversation id in place of the channel id in your chat.postMessage method.

How to send image to server with Blob type using Axios in React Native?

I try to select a picture from the gallery, and I got data like below:
{
"exif":null,
"localIdentifier":"9F983DBA-EC35-42B8-8773-B597CF782EDD/L0/001",
"filename":"IMG_0003.JPG",
"width":500,
"modificationDate":null,
"mime":"image/jpeg",
"sourceURL":"file:///Users/vichit/Library/Developer/CoreSimulator/Devices/3BBFABAC-2171-49AA-8B2B-8C2764949258/data/Media/DCIM/100APPLE/IMG_0003.JPG",
"height":500,
"creationDate":"1344451932"
}
For this time, I want to send this picture to the server with Blob type using Axios.
I don't know how to convert this picture to a Blob type.
It's simple:
async function uploadToServer(sourceUrl) {
// first get our hands on the local file
const localFile = await fetch(sourceUrl);
// then create a blob out of it (only works with RN 0.54 and above)
const fileBlob = await localFile.blob();
// then send this blob to filestack
const serverRes = await fetch('https://www.yourAwesomeServer.com/api/send/file', { // Your POST endpoint
method: 'POST',
headers: {
'Content-Type': fileBlob && fileBlob.type,
},
body: fileBlob, // This is your file object
});
const serverJsonResponse = await serverRes.json();
// yay, let's print the result
console.log(`Server said: ${JSON.stringify(serverJsonResponse)}`);
}
And run like uploadToServer("file:///Users/vichit/Library/Developer/CoreSimulator/Devices/3BBFABAC-2171-49AA-8B2B-8C2764949258/data/Media/DCIM/100APPLE/IMG_0003.JPG")
It took me forever to figure it out, but it makes sense now.
I hope that helps someone!

How can I get the JWT token after authenticating?

I have a Rest spring-boot API that when a user authenticates the api returns the token jwt, I noticed in the browser that the token appears in the Response Header> Authentication and in the tests with the Postman it shows in the Body.
How can I get this token to store in the Local Storage browser by Reactjs?
My code that makes the requests looks like this:
import { ACCESS_TOKEN, API_BASE_URL } from '../constants';
export function request (options) {
const headers = {
'Content-Type': 'application/json',
}
if (localStorage.getItem(ACCESS_TOKEN)) {
headers.append('Authorzation', 'Bearer ' + localStorage.getItem(ACCESS_TOKEN))
}
return fetch(API_BASE_URL+options.url, {
method: options.method,
headers: headers,
body: options.body
})
.then(function(response){
// Falta pegar o token e gravar na local estorage
if (!response.ok) {
return Promise.reject(json);
}
return json;
});
};
// Save data to the current local store
localStorage.setItem("username", "John");
// Access some stored data
alert( "username = " + localStorage.getItem("username"));
The first argument of setitem is the key
My account got blocked by some down votes questions, the funny thing is I have to re-edit them, even though I already have the accepted answer.I do not understand what's the point to do this.I am so frustrated by this stackoverflow system.
Now, I basically can do nothing but keep editing my questions, and they have all been answered. This is ridiculous !!!

Resources