I had a friend set up an MQTT to trigger by Gmail emails with certain words, which I want to use to set a script (via userscript in Chrome) in motion with that trigger from the MQTT.
He set up the MQTT part but when he tried integrating it into the script we want it to activate, 'require' was not the proper command (the error states 'eslint: no-undef - 'require' is not defined.'). Here's the relevant piece of code:
(function() {
console.log(`Script started`);
var mqtt = require('mqtt')
const client = mqtt.connect('mqtt://broker.hivemq.com');
console.log(`Script connected`);
textToSpeech("Starting");
client.on('connect', function () {
client.subscribe('thescriptthing/newemail', function (err) {
if (!err) {
console.log('Subscribed to topic');
}
});
});
Any tips, anyone?
From mqtt.js documentation:
The only protocol supported in browsers is MQTT over WebSockets, so you must use
ws://
orwss://
protocols.
Besides that, you need to specify the correct port; from mqtt-dashboard.com:
- Host: broker.hivemq.com
- TCP Port: 1883
- Websocket Port: 8000
- TLS TCP Port: 8883
- TLS Websocket Port: 8884
*You also need to use the path /mqtt
=> wss://broker.hivemq.com:8884/mqtt
Here's an example script:
// ==UserScript==
// @name mqtt
// @namespace http://tampermonkey.net/
// @version 0.1
// @description mqtt.js test
// @author You
// @match https://stackoverflow.com/*
// @require https://unpkg.com/mqtt@5.10.1/dist/mqtt.min.js
// @grant none
// ==/UserScript==
/* globals mqtt */
const client = mqtt.connect("wss://broker.hivemq.com:8884/mqtt");
client.on("connect", () => {
client.subscribe("thescriptthing/newemail", (err) => {
if (!err) {
console.log('Subscribed to topic');
}
});
});
client.on("message", (topic, message) => {
console.log(message.toString());
});