After connecting and wiring the Shelly2.5 with my shutter, trying to connect it with Siri.
Decided to do this with Scriptable app and then connect Siri commands to it, so it will run.
Currently have an issue to send the request from the Scriptable app as the code is written below, when i tried to fire it from Postman it works.
// # open shutter
let url = "https://domain.shelly.cloud";
let suffix ="/device/relay/roller/control/";
let auth_key = "AAAABBBBCCCDDDEEEEFFFFFF____EXAMPLE_TOKEN___AAAABBBBCCCDDDEEEEFFFFFF";
let channel = 0;
let turn = "on";
let direction = "open";
let id = "C45bbe75f1bd";
let body = {
"auth_key":auth_key,
"id": id,
"direction":direction
};
// console.log(body);
let req = new Request(url + suffix);
// console.log(url+suffix);
req.method = "POST";
req.body = body;
req.headers = { "Content-Type":"application/x-www-form-urlencoded" };
// req.body = JSON.stringify(body)
let json = await req.loadJSON()
console.log(json);
the current response:
2021-09-13 11:20:46: {"isok":false,"errors":{"invalid_header":"Unauthorized! Wrong authorization header provided!","invalid_token":"The login information is invalid! Please login again!"}}
please notice that i change the real token and the real sub domain for shelly cloud.
It will be grate if someone know how to fix this, Thanks
looks like the Shelly expect form-encoded body. Try this
let form = Object.keys(body).map( k => `${k}=${encodeURIComponent(body[k])}`).join('&')
req.body = form
Related
Every time one of my button is clicked, I trigger a call to the adviceslip API to get an advice data. I expect the payload to vary. But the exact same data is returned after each call.
I've tried to call getAdvice function as a callback but it didn't work.
Am I missing something?
'use strict'
const title = document.querySelector('.advice-title')
const desc = document.querySelector('.advice-text')
const btn = document.querySelector('.btn')
const getAdvice = async () =>{
try{
const response = await fetch('https://api.adviceslip.com/advice');
if (!response.ok){
throw new Error('Api connection problem')
}
const responseJson = await response.json();
const data = responseJson.slip;
const id = `ADVICE #${data.id}`;
const advice = `"${data.advice}"`;
title.textContent = id;
desc.textContent = advice;
}
catch (e) {
console.error(e)
}
}
btn.addEventListener('click', () => {
getAdvice()
})
There appears to be an issue with caching where multiple requests closely spaced in time from a web page will cause the same result to come back. If I add a uniquely changing value to the URL to defeat caching like this:
const response = await fetch('https://api.adviceslip.com/advice?t=' + Math.random());
Then, I get a unique response every time.
I experimented with sending various headers to disable caching instead of the t=xxx hack, but those headers trigger a CORs error and the fetch() does not succeed because custom headers like this don't pass the test for a "simple" CORS request and thus require pre-flight which the target site does not support. So, the ?t=xxx where xxx is different on each request seems to do the trick.
I found this and it worked for me. Add
const response = await fetch("https://api.adviceslip.com/advice", { cache: "no-cache" });
So watch a tutorial on internet i created a Google App Script(GAS) for getting History id. using previous history ids i created a script which gives message id and thread id for every incoming requests and posts it on my API in function postReq(). Now when i try to use these ids in python gmail api they show error that they dont exist. I tried to get ids for certain messages and found out they are different from those given from GAS. Is this something api does or i can fix this anyway? Thanks
function doPost(e) {
let message = JSON.parse(e.postData.getDataAsString()).message
let data = Utilities.newBlob(Utilities.base64Decode(message.data)).getDataAsString();
let sheet = SpreadsheetApp.openById('...')
let doc = DocumentApp.openById('...').getBody()
let para = doc.getParagraphs()[0]
let prevId = sheet.getDataRange().getValues()[0][0];
data = JSON.parse(data)
let historyId = parseInt(data.historyId)
let history = Gmail.Users.History.list("nyxgodxd#gmail.com",{"startHistoryId": `${prevId}` }).history
let threadId = history[0].messages[0].threadId
let msgId = history[0].messages[0].id
let msg = Gmail.Users.Messages.get(userId = 'me', id = `${msgId}`).snippet
let res = {historyId,threadId, msgId,msg}
para.appendText(`\n${JSON.stringify(res)}\n`)
postReq(res)
sheet.getDataRange().setValues([[`${historyId}`]])
return 200;
}
I am currently trying to implement SendGrid Email Activity into my application. Whenever an event fires I am able to access the info I need. When trying to look at the message corresponding to the message_id I receive the error: NOT FOUND.
I am wondering if there is a solution for this or has it not yet been created on SendGrid and how would I go about accessing the message information based on an engagement or delivery event?
Thanks
const env = require('dotenv').config();
const client = require('#sendgrid/client');
client.setApiKey(process.env.SENDGRID_API_KEY);
const eventStatus = info.event;
const customerAccountNumber = info.customerAccountNumber;
const recipient = info.email;
const messageId = info.sg_message_id;
console.log("message ID:", messageId);
try {
const request = {};
request.method = 'GET';
request.url = '/v3/messages/' + messageId;
client.request(request)
.then(([response, body]) => {
console.log(response.statusCode);
if(response.statusCode == 200) {
const messageInfo = response.body;
const sender = messageInfo.from_email;
const subject = messageInfo.subject;
console.log(eventStatus, customerAccountNumber, sender, recipient, messageId, subject);
}
else {
console.dir("Here");
}
});
}
catch(e){
console.log(e);
}
return("Test");
I believe you're getting a HTTP 404 because the URL you're putting together is wrong. Given messageId = 'foobar123', the following code
request.url = '/v3/messages/' + messageId;
will produce the request URL "/v3/messages/foobar123".
Taking a quick peek at the docs, the URL should be something more like "/v3/messages?limit=10&query={your_query}", with options for {your_query} described here.
I'm assuming you're trying to make a query such as msg_id="filter0307p1las1-16816-5A023E36-1.0". You need to pass this as URL parameter query. You'll also need to URL encode it, since it contains = and " characters. Putting all of this together, I'd try something like:
const query = `msg_id="${messageId}"`;
const request = {};
request.method = 'GET';
request.url = `/v3/messages?query=${encodeURIComponent(query)}`;
client.request(request).then(...)
H Apologies,
This is going to be an incredibly beginner question - I have been trying to figure this out on my own this afternoon. I am only beginning coding in js for the first time today.
I am trying to create a script that will monitor Mixer's constellation server, receive a response when a stream goes live. (I have this bit working fine and when the streamer goes online it send a true message, when the streamer goes offline i get false).
const Carina = require('carina').Carina;
const ws = require('ws');
Carina.WebSocket = ws;
const channelId = xxxxxx;
const ca = new Carina({ isBot: true }).open();
ca.subscribe(`channel:${channelId}:update`, data => {
console.log(data.online);
});
I then would like it to trigger a POST query to using the maker script part of IFTTT to trigger an event there (such as flash my lights when my favourite streamer goes online) - I also have this script working fine!
var request = require("request");
request({
uri:
"https://maker.ifttt.com/trigger/streaming/with/key/xxxxxxxxxxxxxxxxxx",
method: "POST",
}, function(error, response, body) {
console.log(body);
});
Problem I have, is I have zero knowledge of js, as to have to merge the 2 together, so that when I receive a 'true' response from the Mixer constellation server, it runs the second part of the script.
I hope that you go easy on my lack of knowledge and I look thank you for your assistance.
i think you have to simply use a function in callback of another function like this:
const Carina = require('carina').Carina;
const ws = require('ws');
Carina.WebSocket = ws;
const channelId = xxxxxx;
const ca = new Carina({ isBot: true }).open();
var request = require("request");
ca.subscribe(`channel:${channelId}:update`, data => {
if(data.online){
request({
uri:
"https://maker.ifttt.com/trigger/streaming/with/key/xxxxxxxxxxxxxxxxxx",
method: "POST",
}, function(error, response, body) {
console.log(body);
});
}
});
I'm making a request but it doesn't seem to work. If I copy code into my browser it works good, but in my console it shows up this :
{
"status" : "success",
"data" : {
"error_message" : "API access enabled, but unable to verify two-factor authentication code. If you need help with this, please contact support#bitskins.com."
}
}
What am I doing wrong? It's based on two-factor authentication that as I said works good while printing the url itself and when i'm copying it into my browser.
var url = 'https://bitskins.com/api/v1/get_item_price/?api_key='+bitskins.apikey+'&code='+bitskins.code+'&names='+encodeURIComponent(items[i].market_hash_name)+'&delimiter=!END!';
console.log(url);
request(url, function (error, response, body) {
if (!error) {
console.log(body)
}
});
In case you want, here is my api key module to generating it (api key deleted for security)
var TOTP = require('onceler').TOTP;
//Create a TOTP object with your secret
var totp = new TOTP('deleted');
// print out a code that's valid right now
// console.log(totp.now());
var code = totp.now();
module.exports = {
code: code,
apikey: 'deleted'
}
Founder of BitSkins, Inc. here. You need to have the following:
1) Your API Key
2) Your Secure Access Secret
You see the Secret when you enable Secure Access. If you do not have this, just disable/re-enable Secure Access and note the Secret down. The TOTP code you generate is with that Secret. Generate the TOTP code right before every API call and you'll be fine.
I think it should work. For me it works fine.
var API_KEY = ''; //It is very important
var SECRET_KEY = ''; //It is very important
var totp = new TOTP(SECRET_KEY);
var code = totp.now();
var options = {
url: 'https://bitskins.com/api/v1/get_item_price',
form: {
'api_key': API_KEY,
'names': 'Tec-9%20%7C%20Sandstorm%20(Minimal%20Wear)',
'delimiter': '!END!',
'code': code
}
};
function callback(error, response, body) {
if (!error) {
var info = JSON.parse(body);
console.log(info);
}
}
request.post(options, callback);
What npm package do you use to create 2FA code? I'm using "onceler" from example but I think it creates wrond codes. Here is my code:
var API_KEY = ''; //correct key from settings page
var SECRET_KEY = ''; // correct key which I copied from form with QR code.
var totp = new TOTP("SECRET_KEY");
var code = totp.now();
This code doesn't equal code which I can see in my mobile device and with this code I get error message like in author's question. But if I put code from my mobile in programm code - it works fine. So what package should I use to get correct codes?