discordjs Embed won't show up - discord.js

Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?

Related

Memory heap keeps increasing using ag-grid, angular and websocket

We needed to create a Live Monitor sort of screen that gets the feed through a WebSocket. Angular 11 is used for the UI part. When the page is left on Chrome for a few minutes, the memory heap starts increasing and gradually it increases to a greater extent. After some time, the application will hang and we can't go to another page of the application.
I'm unable to understand the cause of the memory leak, if any.
HTML Code:
<ag-grid-angular #LiveHedgeGrid class="ag-theme-balham" [rowData]="hedgeRowData" [columnDefs]="hedgeColumn" (gridReady)="onLiveHedgeReady($event)" (columnRowGroupChanged)="oncolumnRowGroupChanged($event)" (gridSizeChanged)="onGridSizeChanged($event)"
[enableCellChangeFlash]="true" [rowBuffer]="10" [debounceVerticalScrollbar]="true" [suppressColumnVirtualisation]="true" [groupIncludeTotalFooter]="true" [gridOptions]="gridOptions" [suppressAggFuncInHeader]="true" [groupDefaultExpanded]="groupDefaultExpanded"
[domLayout]="domLayout">
</ag-grid-angular>
TypeScript Code:
websocketCall() {
let socket = new WebSocket(ApiService.webSocketUrl);
socket.onopen = e => {
};
socket.onmessage = e => {
let server_message;
try {
server_message = JSON.parse(e.data);
server_message = JSON.parse(server_message);
if (server_message instanceof Array) {
this.bindTableValues(server_message);
} else {
this.bindTableValues([server_message]);
}
} catch (e) {
this.bindTableValues(server_message);
}
// console.log('socket open');
};
socket.onclose = () => {
//console.log('Web Socket Connection Closed');
};}
async bindTableValues(server_message) {
await server_message.forEach(element => {
this.ricData = {};
let ricPeriod = '';
let itemsToUpdate = [];
let data = {};
let value = 0;
let ricData = this.ricList[element['RIC']];
if (ricData) {
if (ricData['type'] == 'swap') {
value = element['Fields']['NETCHNG_1'];
ricPeriod = ricData['disp_name'];
ricPeriod = ricPeriod.toString().trim().substring(0, ricPeriod.length - 1).toLowerCase();
if (value) {
//const itemsToUpdate: any[] = [];
this.gridApi.forEachNodeAfterFilterAndSort((rowNode) => {
if(!rowNode.group) {
data = rowNode.data;
if(data['Tenor'] == ricPeriod) {
data['LivePnL'] = parseFloat(data['DV01']) * value * 100;
itemsToUpdate.push(data);
}
}
});
// this.gridApi.applyTransaction({ update: itemsToUpdate })!;
// this.gridApi.applyTransactionAsync({ update: itemsToUpdate })!;
this.gridApi.batchUpdateRowData({ update: itemsToUpdate })!;
};
}
};
});}
ngOnDestroy(): void {
try {
//console.log('Destroy ' + this.socket.readyState);
// if (this.socket.readyState === WebSocket.OPEN) {
if (this.socket.readyState === 1) {
this.socket.close();
}
this.getRic.unsubscribe();
this.getTable.unsubscribe();
}
catch (e) {
console.log(e);
}}

Discord.js - How to send YouTube url after searching for a video

So basically, my idea for a new command for my discord bot is a "link searcher", which will be a searching command that sends the url of the video that is chosen by the user. Something like in the image attached.
What I already have made is a searching command with embed, but im not quite sure how to send the video url that gets chosen via reaction. Any ideas/solutions?
I have found a solution after some tries, so here's the final code.
//////CONFIG LOAD///////////
////////////////////////////
const ytsr = require("youtube-sr")
const { Client, Collection, MessageEmbed } = require("discord.js");
const { attentionembed } = require("../util/attentionembed"); //attentionembed is an embed i pre-made for errors/attention cases for when the user gets one
const { approveemoji, denyemoji, PREFIX, } = require(`../config.json`); //my config contains the definitions for "yes" and "no" emojis, together with the bot token
////////////////////////////
//////COMMAND BEGIN/////////
////////////////////////////
module.exports = {
name: "linkfor",
aliases: ["searchlink","findlink","link","lf"], //optional
cooldown: 3, //optional
async execute(message, args, client) {
//if its not in a guild return
if (!message.guild) return;
//react with approve emoji
message.react(approveemoji).catch(console.error);
//if the argslength is null return error
if (!args.length)
return attentionembed(message, `Usage: ${message.client.prefix}${module.exports.name} <Video Name>`)
//if there is already a search return error
if (message.channel.activeCollector)
return attentionembed(message, "There is a search active!");
//define search
const search = args.join(" ");
//define a temporary Loading Embed
let temEmbed = new MessageEmbed()
.setAuthor("Searching...", "put a gif link here if you want")
.setColor("#F0EAD6")
//define the Result Embed
let resultsEmbed = new MessageEmbed()
.setTitle("Results for ")
.setDescription(`\`${search}\``)
.setColor("#F0EAD6")
.setAuthor("Search results:", "put a gif link here if you want")
.setFooter("Respond with the right number", "put a gif link here if you want")
//try to find top 9 results
try {
//find them
const results = await ytsr.search(search, { limit: 9 });
//map them and sort them and add a Field to the ResultEmbed
results.map((video, index) => resultsEmbed.addField(video.url, `${index + 1}. ${video.title}`));
//send the temporary embed aka Loading... embed
const resultsMessage = await message.channel.send(temEmbed)
//react with 9 Numbers
await resultsMessage.react("1️⃣");
await resultsMessage.react("2️⃣");
await resultsMessage.react("3️⃣");
await resultsMessage.react("4️⃣");
await resultsMessage.react("5️⃣");
await resultsMessage.react("6️⃣");
await resultsMessage.react("7️⃣");
await resultsMessage.react("8️⃣");
await resultsMessage.react("9️⃣");
//edit the resultmessage to the resultembed (you can also try deleting and sending the new one, if you need to)
await resultsMessage.edit(resultsEmbed)
//set the collector to true
message.channel.activeCollector = true;
//wait for a response
let response;
await resultsMessage.awaitReactions((reaction, user) => user.id == message.author.id,
{ max: 1, time: 60000, errors: ['time'], }).then(collected => {
//if its one of the emoji set them to 1 / 2 / 3 / 4 / ...
if (collected.first().emoji.name == "1️⃣") { return response = 1; }
if (collected.first().emoji.name == "2️⃣") { return response = 2; }
if (collected.first().emoji.name == "3️⃣") { return response = 3; }
if (collected.first().emoji.name == "4️⃣") { return response = 4; }
if (collected.first().emoji.name == "5️⃣") { return response = 5; }
if (collected.first().emoji.name == "6️⃣") { return response = 6; }
if (collected.first().emoji.name == "7️⃣") { return response = 7; }
if (collected.first().emoji.name == "8️⃣") { return response = 8; }
if (collected.first().emoji.name == "9️⃣") { return response = 9; }
//otherwise set it to error
else {
response = "error";
}
});
//if response is error return error
if (response === "error") {
//send error message
attentionembed(message, "Please use the right emoji symbol.");
//try to delete the message
return resultsMessage.delete().catch(console.error);
}
//get the response link
const URL = resultsEmbed.fields[parseInt(response) - 1].name;
//set collector to false aka off
message.channel.activeCollector = false;
//send the collected url
message.channel.send(URL);
//delete the search embed (optional, for better displaying)
resultsMessage.delete().catch(console.error);
//catch any errors while searching
} catch (error) {
//log them
console.error(error);
//set collector false, just incase its still true
message.channel.activeCollector = false;
}
}
};

Command deprecated [duplicate]

This question already has an answer here:
Discord.js v12 code breaks when upgrading to v13
(1 answer)
Closed 1 year ago.
So basically I had this blackjack command that worked fine with v12 discord.js but as soon as I updated to discord v13. Bugs starting to appear like:
node:5932) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use node --trace-deprecation ... to show where the warning was created)
(Only error showing up)
So I made some research and figured out that what happens to embed, but this command does not content an embed.. I came here to ask help. I would appreciate it :)
Blackjack.js
const { stripIndents } = require('common-tags');
const { shuffle, verify } = require('../../functions');
const db = require('quick.db');
const suits = ['♣', '♥', '♦', '♠'];
const faces = ['Jack', 'Queen', 'King'];
const hitWords = ['hit', 'hit me'];
const standWords = ['stand'];
module.exports = {
config: {
name: 'blackjack',
aliases: ['bj'],
category: 'games',
usage: '[deck] <bet>',
description: 'Play A Game Of Blackjack!',
accessableby: 'everyone'
},
run: async (bot, message, args, ops) => {
if (!args[0]) return message.channel.send('**Please Enter Your Deck Amount!**')
let deckCount = parseInt(args[0])
if (isNaN(args[0])) return message.channel.send('**Please Enter A Number!**')
if (deckCount <= 0 || deckCount >= 9) return message.channel.send("**Please Enter A Number Between 1 - 8!**")
let user = message.author;
let bal = db.fetch(`money_${user.id}`)
if (!bal === null) bal = 0;
if (!args[1]) return message.channel.send("**Please Enter Your Bet!**")
let amount = parseInt(args[1])
if (isNaN(args[1])) return message.channel.send("**Please Enter A Number**")
if (amount > 10000) return message.channel.send("**Cannot Place Bet More Than \`10000\`**")
if (bal < amount) return message.channel.send("**You Are Betting More Than You Have!**")
const current = ops.games.get(message.channel.id);
if (current) return message.channel.send(`**Please Wait Until The Current Game Of \`${current.name}\` Is Finished!**`);
try {
ops.games.set(message.channel.id, { name: 'blackjack', data: generateDeck(deckCount) });
const dealerHand = [];
draw(message.channel, dealerHand);
draw(message.channel, dealerHand);
const playerHand = [];
draw(message.channel, playerHand);
draw(message.channel, playerHand);
const dealerInitialTotal = calculate(dealerHand);
const playerInitialTotal = calculate(playerHand);
if (dealerInitialTotal === 21 && playerInitialTotal === 21) {
ops.games.delete(message.channel.id);
return message.channel.send('**Both Of You Just Hit Blackjack!**');
} else if (dealerInitialTotal === 21) {
ops.games.delete(message.channel.id);
db.subtract(`money_${user.id}`, amount);
return message.channel.send(`**The Dealer Hit Blackjack Right Away!\nNew Balance - **\` ${bal - amount}\``);
} else if (playerInitialTotal === 21) {
ops.games.delete(message.channel.id);
db.add(`money_${user.id}`, amount)
return message.channel.send(`**You Hit Blackjack Right Away!\nNew Balance -**\`${bal + amount}\``);
}
let playerTurn = true;
let win = false;
let reason;
while (!win) {
if (playerTurn) {
await message.channel.send(stripIndents`
**First Dealer Card -** ${dealerHand[0].display}
**You [${calculate(playerHand)}] -**
**${playerHand.map(card => card.display).join('\n')}**
\`[Hit / Stand]\`
`);
const hit = await verify(message.channel, message.author, { extraYes: hitWords, extraNo: standWords });
if (hit) {
const card = draw(message.channel, playerHand);
const total = calculate(playerHand);
if (total > 21) {
reason = `You Drew ${card.display}, Total Of ${total}! Bust`;
break;
} else if (total === 21) {
reason = `You Drew ${card.display} And Hit 21!`;
win = true;
}
} else {
const dealerTotal = calculate(dealerHand);
await message.channel.send(`**Second Dealer Card Is ${dealerHand[1].display}, Total Of ${dealerTotal}!**`);
playerTurn = false;
}
} else {
const inital = calculate(dealerHand);
let card;
if (inital < 17) card = draw(message.channel, dealerHand);
const total = calculate(dealerHand);
if (total > 21) {
reason = `Dealer Drew ${card.display}, Total Of ${total}! Dealer Bust`;
win = true;
} else if (total >= 17) {
const playerTotal = calculate(playerHand);
if (total === playerTotal) {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}${playerTotal}-${total}`;
break;
} else if (total > playerTotal) {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}${playerTotal}-\`${total}\``;
break;
} else {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}\`${playerTotal}\`-${total}`;
win = true;
}
} else {
await message.channel.send(`**Dealer Drew ${card.display}, Total Of ${total}!**`);
}
}
}
db.add(`games_${user.id}`, 1)
ops.games.delete(message.channel.id);
if (win) {
db.add(`money_${user.id}`, amount);
return message.channel.send(`**${reason}, You Won ${amount}!**`);
} else {
db.subtract(`money_${user.id}`, amount);
return message.channel.send(`**${reason}, You Lost ${amount}!**`);
}
} catch (err) {
ops.games.delete(message.channel.id);
throw err;
}
function generateDeck(deckCount) {
const deck = [];
for (let i = 0; i < deckCount; i++) {
for (const suit of suits) {
deck.push({
value: 11,
display: `${suit} Ace!`
});
for (let j = 2; j <= 10; j++) {
deck.push({
value: j,
display: `${suit} ${j}`
});
}
for (const face of faces) {
deck.push({
value: 10,
display: `${suit} ${face}`
});
}
}
}
return shuffle(deck);
}
function draw(channel, hand) {
const deck = ops.games.get(channel.id).data;
const card = deck[0];
deck.shift();
hand.push(card);
return card;
}
function calculate(hand) {
return hand.sort((a, b) => a.value - b.value).reduce((a, b) => {
let { value } = b;
if (value === 11 && a + value > 21) value = 1;
return a + value;
}, 0);
}
}
};
Event Handler:
const { readdirSync } = require("fs")
module.exports = (bot) => {
const load = dirs => {
const events = readdirSync(`./events/${dirs}/`).filter(d => d.endsWith('.js'));
for (let file of events) {
const evt = require(`../events/${dirs}/${file}`);
let eName = file.split('.')[0];
bot.on(eName, evt.bind(null, bot));
};
};
["client", "guild"].forEach(x => load(x));
};
message is an event. you have an event handler, which fires, when a message event is triggered by a user. (they send a message).
What this error is saying is that the message event is deprecated. messageCreate (or messageUpdate) are the new events, and your event handlers need to use that syntax to address the message events (accordingly to creation or update).

What's the prefix for mute

Problems with my bot. Can't get mute to work. Help? Can't find any prefix and don't know where to add it or how to format it. I linked most of code below. Anti-spam and kick/ban works. New to coding to any help would be nice. Tips how set a general prefix for all code foward? Role is named mute and bot has all premissons it shall need to kick
const fs = require('fs');
module.exports = class mute {
constructor(){
this.name = 'mute',
this.alias = ['tempmute'],
this.usage = 'mute';
}
run(bot, message, args){
let member = message.mentions.members.first();
var command = args[0];
var mentioned = args[1];
var days = parseInt(args[3]);
var hours = parseInt(args[4]);
var seconds = parseInt(args[5]);
if (message.member.hasPermission('MANAGE_ROLES')) {
let muterole = message.guild.roles.find(role => role.name === "Muted");
if (!message.guild) {
if (message.guild.id === '505872328538718233') {
let memberrole = message.guild.roles.find("name", "Member");
member.removeRole(memberrole);
}}
let usermsg = new Discord.RichEmbed();
usermsg.setTitle('You have been Muted.');
usermsg.setColor('76b3fc');
usermsg.setFooter('Please do not attempt to bypass');
usermsg.addField('Muted by:',
`<#${message.author.id}>`);
let mutedmsg = new Discord.RichEmbed();
mutedmsg.setTitle('User has been Muted Successfully');
mutedmsg.setColor('76b3fc');
mutedmsg.setDescription(`User muted: ${mentioned}\nMuted by: <#${message.author.id}>\nReason: ${input}`);
mutedmsg.setFooter('This mute has been logged.');
if (message.content === `${command}`) {
return message.channel.send('You did not provide a member to mute.');
}
if (message.content === `${command} ${mentioned}`) {
return message.channel.send('Please input a reason for the mute.');
}
if (message.guild.roles.find(role => role.name)) {
message.member.addRole(muterole);
if (message.content.includes (`${days}d`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${hours} Seconds`);
}, `${args[2]} * 86400`);
}
if (message.content.includes (`${hours}h`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${hours} Seconds`);
}, `${args[3]} * 3600`);
}
if (message.content.includes (`${seconds}s`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${seconds} Seconds`);
}, `${args[4]} * 1000`);
}
if (message.content === `${command} ${mentioned} ${input}`) {
message.member.addRole(muterole);
usermsg.addField('Muted for',
`${input}`);
usermsg.addField('Punishment Time:',
'Permenant');
message.channel.send(mutedmsg);
}
if (message.member.id === `${message.author.id}`) {
return;
}
if (message.author.id === `${mentioned}`) {
return message.member.send(usermsg);
}
message.channel.send(mutedmsg);
console.log('===========================');
console.log(`Member Muted: ${mentioned}`);
console.log(`Muted by: ${message.author.tag}`);
console.log(`Reason: ${input}`);
console.log('===========================');
} else {
message.channel.send('You do not have a `Muted` Role, This command won\'t work.');
}
} else {
message.reply('You do not have permission to do this.');
}
let jsonlogs = JSON.parse(fs.writeFileSync("./storages/mutelogs.json"));
if (!jsonlogs[message.guild.id]){
jsonlogs[message.guild.id] = {
mutedby: `${message.author.tag}`,
user: `${mentioned}`,
reason: `${input}`,
days: `${days}`,
hours: `${hours}`,
seconds: `${seconds}`,
};
}
}
};
You seem to have a lot, and I mean A LOT of outdated methods from Discord.js v11.
I'd highly recommend installing the newest version of DJS and reading all of the v12 changes that can be found here:
https://github.com/discordjs/discord.js/releases/tag/12.0.0
Some examples:
Discord.RichEmbed() no longer exists -> Use Discord.MessageEmbed()
.addRole() no longer exists -> Use message.member.roles.add()
.removeRole() no longer exists -> Use message.member.roles.remove()

Uncaught SyntaxError: Identifier 'socket' has already been declared in client file

I've created a React app where I'm using socket.io to connect to the Google Cloud Platform. When I run the client and the server I get following error in the client file:
Uncaught SyntaxError: Identifier 'socket' has already been declared
But I'm not quite sure why since the socket is a constant that is not defined as a global constant. Probably that's not the reason why is failing.
The following is the code of the client.js and the structure of the project:
//connection to socket
const io = require('socket.io-client');
const socket = io.connect('http://localhost:1337');
// ================= visibilitychange =================
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || hidden === undefined) {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);
}
//================= CONFIG =================
// Stream Audio
let bufferSize = 2048,
AudioContext,
context,
processor,
input,
globalStream;
//vars
let audioElement = document.querySelector('audio'),
finalWord = false,
resultText = document.getElementById('ResultText'),
removeLastWord = true,
streamStreaming = false;
//audioStream constraints
const constraints = {
audio: true,
video: false
};
//================= RECORDING =================
function initRecording() {
socket.emit('startGoogleCloudStream', ''); //init socket Google Speech Connection
streamStreaming = true;
AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
processor = context.createScriptProcessor(bufferSize, 1, 1);
processor.connect(context.destination);
context.resume();
var handleSuccess = function (stream) {
globalStream = stream;
input = context.createMediaStreamSource(stream);
input.connect(processor);
processor.onaudioprocess = function (e) {
microphoneProcess(e);
};
};
navigator.mediaDevices.getUserMedia(constraints)
.then(handleSuccess);
}
function microphoneProcess(e) {
var left = e.inputBuffer.getChannelData(0);
var left16 = convertFloat32ToInt16(left);
socket.emit('binaryData', left16);
}
//================= INTERFACE =================
var startButton = document.getElementById("startRecButton");
if(startButton) {
startButton.addEventListener("click", startRecording);
}
var endButton = document.getElementById("stopRecButton");
if(endButton){
endButton.addEventListener("click", stopRecording)
endButton.disabled = true;
}
function startRecording() {
startButton.disabled = true;
endButton.disabled = false;
initRecording();
}
function stopRecording() {
// waited for FinalWord
startButton.disabled = true;
endButton.disabled = true;
streamStreaming = false;
socket.emit('endGoogleCloudStream', '');
let track = globalStream.getTracks()[0];
track.stop();
input.disconnect(processor);
processor.disconnect(context.destination);
context.close().then(function () {
input = null;
processor = null;
context = null;
AudioContext = null;
startButton.disabled = false;
});
}
//================= SOCKET IO =================
socket.on('connect', function (data) {
console.log('client connected');
socket.emit('join', 'Server Connected to Client');
});
socket.on('endmessages', function (data) {
console.log(data);
resultText.appendChild(document.createTextNode(data));
});
socket.on('speechData', function (data) {
// console.log(data.results[0].alternatives[0].transcript);
// console.log(data.results[0]);
var dataFinal = undefined || data.results[0].isFinal;
if (dataFinal === false) {
// console.log(resultText.lastElementChild);
if (removeLastWord) { resultText.lastElementChild.remove(); }
removeLastWord = true;
//add empty span
let empty = document.createElement('span');
resultText.appendChild(empty);
let edit = data.results[0].alternatives[0].transcript;
resultText.lastElementChild.appendChild(document.createTextNode(edit));
resultText.lastElementChild.appendChild(document.createTextNode('\u00A0'));
} else if (dataFinal === true) {
resultText.lastElementChild.remove();
//add empty span
let empty = document.createElement('span');
var br = document.createElement("br");
resultText.appendChild(empty);
let edit = data.results[0].alternatives[0].transcript;
resultText.lastElementChild.appendChild(document.createTextNode(edit));
resultText.lastElementChild.appendChild(document.createTextNode('\u00A0'));
resultText.appendChild(br);
console.log("Google Speech sent 'final' Sentence.");
finalWord = true;
removeLastWord = false;
}
});
socket.on('end', function (data) {
console.log(data);
});
function handleVisibilityChange() {
if (document[hidden]) {
console.log('handleVisibilityChange:hidden');
if (streamStreaming) {
console.log("end");
socket.emit('leave', 'onbeforeunload stop');
stopRecording();
}
} else {
console.log('handleVisibilityChange:show');
startButton.disabled = false;
endButton.disabled = true;
}
}
//================= SANTAS HELPERS =================
// sampleRateHertz 16000 //saved sound is awefull
function convertFloat32ToInt16(buffer) {
let l = buffer.length;
let buf = new Int16Array(l / 3);
while (l--) {
if (l % 3 == 0) {
buf[l / 3] = buffer[l] * 0xFFFF;
}
}
return buf.buffer
}
This is the architecture of the project:
publicFolder
assetsFolder
cssFolder
fontsFolder
jsFolder
client.1.js
client.js
socket.io.js
socket.io.js.map
index.html
serverFolder
app.js //this is server
src
components
App.js //the wrapper component
ComponentA.js
ComponentB.js
App.css
index.js
resgisterServiceWorker.js
.babelrc
webpack.config.js
I think I've fixed, just by changing the connection to the socket from this:
//connection to socket
const io = require('socket.io-client');
const socket = io.connect('http://localhost:1337');
to this
//connection to socket
const socket = io('http://localhost:1337');

Resources