HTML not updating when running my Javascript twitch bot - javascript

const tmi = require('tmi.js');
// Define configuration options
var x = "asdfasdf"
const opts = {
identity: {
username: 'username',
password: 'password'
},
channels: [
"rabeya74"
]
};
// Create a client with our options
const client = new tmi.client(opts);
// Register our event handlers (defined below)
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
// Connect to Twitch:
client.connect();
// Called every time a message comes in
function onMessageHandler(target, context, msg, self) {
if (self) {
return;
} // Ignore messages from the bot
// Remove whitespace from chat message
const commandName = msg.trim();
// If the command is known, let's execute it
if (commandName === '!dice') {
const num = rollDice();
client.say(target, `You rolled a ${num}`);
document.body.innerHTML = x;
console.log(`* Executed ${commandName} command`);
document.body.innerHTML = `You rolled a ${num}`;
window.onload = function() {
document.getElementById("display").innerHTML = "hello";
}
document.getElementById("display").innerHTML = "hello";
} else {
console.log(`* Unknown command ${commandName}`);
}
}
// Function called when the "dice" command is issued
function rollDice() {
const sides = 6;
return Math.floor(Math.random() * sides) + 1;
}
// Called every time the bot connects to Twitch chat
function onConnectedHandler(addr, port) {
console.log(`* Connected to ${addr}:${port}`);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="bot.js"></script>
<div id="display"></div>
</body>
</html>
I'm trying to make a small twitch javascript app that updates the HTML file when I roll a dice. I tried every version of the document.body.innerHTML file but it simply does not want to update. Is it because it's in a function? It seems to just not show anything.

You can't use require() in the browser. This code produces an error because require is undefined. Try adding a <script src="tmi.js"></script> in your <head> element.

Related

rtsp streaming node js ip camera jsmpeg fail

Connected to an ip camera, but it's problem like a picture
when running node app.js "frame= 1970 fps=2.0 q=7.6 size= 22457kB time=00:16:25.00 bitrate= 186.8kbits/s dup=0 drop=3 speed=1.01x"
When executing index.html "name: New WebSocket Connection (1 total)kB time=00:00:43.00 bitrate= 147.0kbits/s speed=1.28x"
but, there are times when the camera does not appear on the canvas, and it is printed like the picture below
app.js
// const onvif = require('node-onvif');
// console.log('Start the discovery process.');
// // Find the ONVIF network cameras.
// // It will take about 3 seconds.
// onvif.startProbe().then((device_info_list) => {
// console.log(device_info_list.length + ' devices were found.');
// // Show the device name and the URL of the end point.
// device_info_list.forEach((info) => {
// console.log('- ' + info.urn);
// console.log(' - ' + info.name);
// console.log(' - ' + info.xaddrs[0]);
// });
// }).catch((error) => {
// console.error(error);
// });
///////////////////////////////////////
// const onvif = require('node-onvif');
// // Create an OnvifDevice object
// let device = new onvif.OnvifDevice({
// xaddr: 'http://192.168.88.4:8081/onvif/device_service',
// user : 'admin',
// pass : 'tmzkdl123$'
// });
// // Initialize the OnvifDevice object
// device.init().then(() => {
// // Get the UDP stream URL
// let url = device.getUdpStreamUrl();
// console.log(url);
// }).catch((error) => {
// console.error(error);
// });
/////////////////////////////////////////
Stream = require('node-rtsp-stream')
stream = new Stream({
name: 'name',
streamUrl: 'rtsp://192.168.88.8:554/0/onvif/profile1/media.smp',
wsPort: 9900,
ffmpegOptions: { // options ffmpeg flags
'-stats': '', // an option with no neccessary value uses a blank string
'-r': 30 // options with required values specify the value after the key
}
})
index.html
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>rtsp</title>
<div><canvas id="video" width="640" height="360"></canvas></div>
<script type="text/javascript" src="jsmpeg.js"></script>
<script type="text/javascript">
var canvas = document.getElementById('video');
var ws = new WebSocket("ws://192.168.88.174:9900");
var player = new jsmpeg(ws, {canvas:canvas, autoplay:true, audio:false, loop:true});
</script>
</head>
<body>
</body>
</html>
image url
enter image description here
I had this problem too but solved that,
you must download jsmpeg.min.js from https://jsmpeg.com/
and replace it with jsmpeg.js file then change this line
<script type="text/javascript" src="jsmpeg.js"></script>
to
<script type="text/javascript" src="jsmpeg.min.js"></script>
after that clear this line
var ws = new WebSocket("ws://192.168.88.174:9900");
and change this line
var player = new jsmpeg(ws, {canvas:canvas, autoplay:true, audio:false, loop:true});
to this:
var player = new JSMpeg.Player("ws://192.168.88.174:9900", {canvas:canvas, autoplay:true, audio:false, loop:true});
your problem must be solved!

How to emit a result from javascript code to all users connected using socket.io

I saw this js code online and i modified the best my knowledge to make it not only visible to current user but all users:
var textarea = $('#textarea');
var typingStatus = document.querySelector('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970
var typingDelayMillis = 2000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
function refreshTypingStatus() {
if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
socket.emit('stat', typingStatus.innerHTML = 'no type');
} else {
socket.emit('stat', typingStatus.innerHTML = 'User typing....');
}
}
function updateLastTypedTime() {
lastTypedTime = new Date();
}
setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylesheet" type="text/css" href="styles2.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input name="textarea" id="textarea" cols="45" rows="5">
<div id="typing_on"></div>
</body>
What i did in front end is add socket.emit to the result as seen above and i did equivalent to that in back-end (server.js)
but it doens't work and show like this:
what i want is for the 'user typing' to appear in both sides (clients)
How can i do that?
To send message from client to server and then sending the message to all clients connected to the websocket:
server.js
io.on('connect', socket => {
let counter = 0;
setInterval(() => {
socket.emit('hello', ++counter);
}, 1000);
});
Index.html
const socket = io();
socket.on('connect', () => {
$events.appendChild(newItem('connect'));
});
socket.on('hello', (counter) => {
$events.appendChild(newItem(`hello - ${counter}`));
});
If you want to send message to all clients except the person who is sending the message, use broadcast instead of emit

websocket works on for index page

I have my website for using jsp. I wanted to use webcsocket to impement chatting. I tried a simple example to test whether it works or not. My code for server end point is given below:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package endpoint;
/**
*
* #author yashs
*/
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class MyServerEndPoint {
#OnMessage
public String echo(String message) {
System.out.println("echo:" + message);
return "Echoing " + message;
}
}
The client side code is given below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login V1</title>
<script type="text/javascript">
function debug(s) {
var d = document.getElementById("debug");
d.innerHTML = d.innerHTML + "<br/>" + s;
}
function sendMessage(msg) {
if (!("WebSocket" in window)) {
debug("Your browser does not support WebSocket.");
return;
}
var uri = "ws://" + document.location.host
+ document.location.pathname + "echo";
var ws = new WebSocket(uri);
ws.onopen = function () {
debug("Connected.");
ws.send("Hello");
};
ws.onmessage = function (evt) {
debug("Received: " + evt.data);
};
ws.onclose = function () {
debug("Connection closed.");
};
}
</script>
</head>
<body>
Send Message
<div id="debug"></div>
</body>
</html>
the name of my project is handiazza
the client side page is the index.html page which is automatically created when you create a new web application in netbeans.
So when ever I run my app using
localhost:8084/handiazza/
then it works fine. But if I copy the same client side code and paste into a new file then it does not work. I saw many examples on google but all the examples have same mechanism of using localhost and the app name

socket.io 404 cant connect with socket.io server

I have webrtc / socket.io / nodejs running on a server, everything works fine when i go to the https://domain.com:8080 to test a video conference.
But i want the script to run in my webserver /public_html/
But i dont know why it is not connecting to the 8080 server.
"socket.io.js GET https://domain.com/socket.io/?EIO=3&transport=polling&t=LPgZs2K 404 (Not Found)"
my server (server.js)
// Load required modules
var https = require("https"); // http server core module
var express = require("express"); // web framework external module
var serveStatic = require('serve-static'); // serve static files
var socketIo = require("socket.io"); // web socket external module
var easyrtc = require("../");
const fs = require('fs'); // EasyRTC external module
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
// Set process name
process.title = "node-easyrtc";
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
// Start Express http server on port 8080
var webServer = https.createServer(options, app).listen(8080);
// Start Socket.io so it attaches itself to Express server
var socketServer = socketIo.listen(webServer, {"log level":1});
easyrtc.setOption("logLevel", "debug");
// Overriding the default easyrtcAuth listener, only so we can directly access its callback
easyrtc.events.on("easyrtcAuth", function(socket, easyrtcid, msg, socketCallback, callback) {
easyrtc.events.defaultListeners.easyrtcAuth(socket, easyrtcid, msg, socketCallback, function(err, connectionObj){
if (err || !msg.msgData || !msg.msgData.credential || !connectionObj) {
callback(err, connectionObj);
return;
}
connectionObj.setField("credential", msg.msgData.credential, {"isShared":false});
console.log("["+easyrtcid+"] Credential saved!", connectionObj.getFieldValueSync("credential"));
callback(err, connectionObj);
});
});
// To test, lets print the credential to the console for every room join!
easyrtc.events.on("roomJoin", function(connectionObj, roomName, roomParameter, callback) {
console.log("["+connectionObj.getEasyrtcid()+"] Credential retrieved!", connectionObj.getFieldValueSync("credential"));
easyrtc.events.defaultListeners.roomJoin(connectionObj, roomName, roomParameter, callback);
});
// Start EasyRTC server
var rtc = easyrtc.listen(app, socketServer, null, function(err, rtcRef) {
console.log("Initiated");
rtcRef.events.on("roomCreate", function(appObj, creatorConnectionObj, roomName, roomOptions, callback) {
console.log("roomCreate fired! Trying to create: " + roomName);
appObj.events.defaultListeners.roomCreate(appObj, creatorConnectionObj, roomName, roomOptions, callback);
});
});
//listen on port 8080
webServer.listen(8080, function () {
console.log('listening on http://localhost:8080');
});
my html file on de WEB server. structure like this https://domain.com/test.html
<!DOCTYPE html>
<html>
<head>
<title>EasyRTC Demo:EasyRTC Demo: Video+Audio HD 720</title>
<link rel="stylesheet" type="text/css" href="/easyrtc/easyrtc.css" />
<script src="js/socket.io.js"></script>
<script type="text/javascript" src="js/easyrtc.js"></script>
<script type="text/javascript" src="js/video.js"></script>
<script>
var selfEasyrtcid = "";
function connect() {
easyrtc.setVideoDims(1280,720);
easyrtc.enableDebug(false);
easyrtc.setRoomOccupantListener(convertListToButtons);
easyrtc.easyApp("easyrtc.videoChatHd", "selfVideo", ["callerVideo"], loginSuccess, loginFailure);
}
function clearConnectList() {
var otherClientDiv = document.getElementById("otherClients");
while (otherClientDiv.hasChildNodes()) {
otherClientDiv.removeChild(otherClientDiv.lastChild);
}
}
function convertListToButtons (roomName, data, isPrimary) {
clearConnectList();
var otherClientDiv = document.getElementById("otherClients");
for(var easyrtcid in data) {
var button = document.createElement("button");
button.onclick = function(easyrtcid) {
return function() {
performCall(easyrtcid);
};
}(easyrtcid);
var label = document.createTextNode(easyrtc.idToName(easyrtcid));
button.appendChild(label);
button.className = "callbutton";
otherClientDiv.appendChild(button);
}
}
function performCall(otherEasyrtcid) {
easyrtc.hangupAll();
var acceptedCB = function(accepted, caller) {
if( !accepted ) {
easyrtc.showError("CALL-REJECTED", "Sorry, your call to " + easyrtc.idToName(caller) + " was rejected");
}
};
var successCB = function() {};
var failureCB = function() {};
easyrtc.call(otherEasyrtcid, successCB, failureCB, acceptedCB);
}
function loginSuccess(easyrtcid) {
selfEasyrtcid = easyrtcid;
document.getElementById("iam").innerHTML = "I am " + easyrtc.cleanId(easyrtcid);
}
function loginFailure(errorCode, message) {
easyrtc.showError(errorCode, message);
}
// Sets calls so they are automatically accepted (this is default behaviour)
easyrtc.setAcceptChecker(function(caller, cb) {
cb(true);
} );
</script>
</head>
<body onload="connect();">
<h1>EasyRTC Demo: Video+Audio HD 720p</h1>
<div id="demoContainer">
<div>
Note: your own image will show up postage stamp sized, while the other party"s video will be shown in high-definition (1280x720). Note: not all webcams are seen by WebRTC as providing high-definition video; the fallback is to use standard definition (640x480).
</div>
<div id="connectControls">
<div id="iam">Not yet connected...</div>
<br />
<strong>Connected users:</strong>
<div id="otherClients"></div>
</div>
<div id="videos">
<div style="position:relative;float:left;" width="1282" height="722">
<video autoplay="autoplay" id="callerVideo"></video>
<video class="easyrtcMirror" autoplay="autoplay" id="selfVideo" muted="true" volume="0" ></video>
</div>
<!-- each caller video needs to be in it"s own div so it"s close button can be positioned correctly -->
</div>
</div>
</body>
</html>
Socket.io.js: http://81.171.38.245/js/socket.io.js

could not open db , $ is not defined, Failed to load jquery

The error is that the db could not be opened and $ not defined, failed to load resources(j query).The code aims at receiving the input field values(date,cal) and storing them into the database using indexedDB
<!DOCTYPE html>
<html manifest="manifest.webapp" lang="en">
<head>
<meta charset="utf-8">
<title>Diab</title>
<link rel="stylesheet" href="diab.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0/jquery.min.js"></script>
<script type="text/javascript" src="diab1.js"></script>
</head>
<body>
<input type="date" id="date">Date</input>
<input type="number" id="cal">Cal</input>
<button id="add" >Add</button>
</body>
</html>
(function()
{ var db;
var openDb=function()
{
var request=indexedDB.open("diabetore");
request.onsuccess = function()
{
console.log("DB created succcessfully");
db = request.result;
console.log("openDB done!!");
};
request.onerror=function(){
alert("could not open db");
};
request.onupgradeneeded = function()
{
console.log("openDB.onupgradeneeded function");
var store = db.createObjectStore("diab", {keyPath: "date"});
var dateIndex = store.createIndex("date", "date",{unique: true});
// Populate with initial data.
store.put({date: "june 1 2013",cal:70});
store.put({date: "june 2 2013",cal:71});
store.put({date: "june 3 2013",cal:72});
store.put({date: "june 8 2013",cal:73});
};
};
function getObjectStore(store_name,mode)
{
var tx=db.transaction(store_name,mode);
return tx.objectStore(store_name);
}
function addItems(date,cal)
{
console.log("addition to db started");
var obj={date:date,cal:cal};
var store=getObjectStore("diab",'readwrite');
var req;
try
{
req=store.add(obj);
}catch(e)
{
if(e.name=='DataCloneError')
alert("This engine doesn't know how to clone");
throw(e);
}
req.onsuccess=function(evt)
{
console.log("****Insertion in DB successful!!****");
};
req.onerror=function(evt)
{
console.log("Could not insert into DB");
};
}
function addEventListners()
{
console.log("addEventListeners called...");
$('#add').click(function(evt){
console.log("add...");
var date=$('#date').val();
var cal=$('#cal').val();
if(!date || !cal)
{
alert("required field missing..");
return;
}
addItems(date,cal);
});
}
openDb();
addEventListners();
})();
Regarding the problem of not being able to see the db created, when you open the database you should pass another parameter with the version of the database, like:
var request=indexedDB.open("diabetore",1);
To see the DB structure on the Resources tab of Chrome Developer Tools, sometimes you must refresh the page.
You will also have a problem with your addEventListners() function since your anonymous function is run before the browser reads the HTML content so the browser doesn't not know about the '#add' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function() {
var db;
var openDb=function() {
You should test the script URL in your browser. Then you'd realize that the script doesn't exist.
You need to change 2.0 to 2.0.0 for example.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Categories

Resources