My code keeps throwing an error "Please enter your Google API key", however I set it up.
google
.search(querystring.stringify({ term: args.join("") }))
.then(async response => {
const title = await translate(response.title, "es");
const snippet = await translate(response.snippet, "es");
const embed = new RichEmbed()
.setColor("0x00ff00")
.setTitle(title)
.setURL(response.formattedURL)
.addField("Resultado de Google", snippet)
.addField("Link", response.formattedURL);
message.channel.startTyping();
await delay(3000);
message.channel
.send(embed)
.then(() => message.channel.stopTyping(true));
});
Edit: Here are the variables:
const Google = require('relevant-google');
const google = new Google('APIKEY');
const querystring = require('querystring');
// Don't worry about anything else tbh
Related
I am currently using node js to publish topics to Event Grid, and subscribe to topics through Event Grid. Using the event grid API on https://learn.microsoft.com/en-us/rest/api/eventgrid/ I get an error where I do not have authorization to perform action when creating a subscription. I have created a topic and have access permission to access my Azure account therefore I am confused why I get this rest error.
My code:
const { ClientSecretCredential } = require("#azure/identity");
const { SystemTopicEventSubscriptions, EventGridManagementClientContext, DomainTopics, EventSubscriptions } = require("#azure/arm-eventgrid");
const subscriptionId = "idea number";
const resourceGroupName = "eventgrid-dev";
const domainName = "test-domain";
let tenantId = "idea number";
let clientSecret = "idea number";
let clientId = "idea number";
const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
//const client = new EventGridManagementClient(firstCredential, subscriptionId);
const clientContext = new EventGridManagementClientContext(firstCredential, subscriptionId);
// Topics
let domainTopics = new DomainTopics(clientContext);
domainTopics.beginCreateOrUpdate(resourceGroupName, domainName, "test-topic")
.then(result => {
console.log("result");
console.log(result);
})
.catch(error => {
console.log("Error");
console.log(error);
})
let subscription = new EventSubscriptions(clientContext);
subscription.beginCreateOrUpdate("/subscriptions/subscriptionId/resourceGroups/eventgrid-dev", "test-subscription",{topic: "test-topic"})
.then(result => {
console.log("result");
console.log(result);
})
.catch(error => {
console.log("Error");
console.log(error);
})
Output:
Error
RestError: The client 'subscriptionID' with object id 'subscriptionID' does not have authorization to perform action 'Microsoft.EventGrid/eventSubscriptions/Microsoft.EventGrid/test-subscription/write' over scope '/subscriptions/subscriptionID/resourceGroups/eventgrid-dev/providers/Microsoft.EventGrid/eventSubscriptions/providers/Microsoft.EventGrid/eventSubscriptions' or the scope is invalid. If access was recently granted, please refresh your credentials.
Thank you for the help!
In the case of existing an event grid domain, use the following code for creating an event grid subscription on the requested topic. Note, that the topic is created automatically during its first subscription:
let subscription = new EventSubscriptions(clientContext);
const scope = '/subscriptions/' + subscriptionId + '/resourceGroups/' + resourceGroupName + '/providers/Microsoft.EventGrid/domains/' + domainName + '/topics/test-topic';
const test_webhookEndpointUrl = ' ... ';
subscription.beginCreateOrUpdate(scope, "test-subscription",
{
destination: {
endpointType: "WebHook",
endpointUrl: test_webhookEndpointUrl
}
}
).then(result => {
console.log("result");
console.log(result);
})
.catch(error => {
console.log("Error");
console.log(error);
})
I have to download a pdf, but it requires first to collect cookies, by visiting the page which hosts the PDF link.
I click the link but a blanc PDF is downloaded with same pages number as the expected one.
(async () => {
const browser = await puppeteer.launch({
dumpio: true,
headless: false,
devtools: true,// I want to see what's going on
})
const [page] = await browser.pages();
page.on('console', msg => console.log(msg.text()));
await page.goto(url_cookie, { waitUntil: ['domcontentloaded', 'networkidle0', 'load'] });
page._client.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: './', });
page.once('response', async (response) => {
if (response.url() !== url_pdf) return;
console.log('resp', response.url());
});
const css = 'a[href="' + url + '"]';
await page.waitForSelector(css)
const eval = async css => {
const a = document.querySelector(css);
console.log(a)
return fetch(a.href, {
method: 'GET',
credentials: 'include',
}).then(r => r.text())
};
const txt = await page.evaluate(eval, [css]);
fs.writeFileSync('./test.pdf', txt,)
await page.close();
await browser.close();
})();
I'm trying to upload an image to s3 with Amplify Storage API.
I use the EXPO imagePicker to upload the image from the phone to React-Native, and it's displayed correctly.
Then I upload it to s3 with amplify Storage.put, and it reaches the correct folder in s3, with the proper filename that I gave it and with public access I provided (to the image and the bucket itself).
BUT if I try to open the photo uri in s3 it doesn't display. When I inspect the browser it shows this error on console:
If I paste in the browser the uri I get from Storage.get , i get this error:
My code is the following (I helped myself with this tutorial https://blog.expo.io/how-to-build-cloud-powered-mobile-apps-with-expo-aws-amplify-2fddc898f9a2):
_handleImagePicked = async (pickerResult) => {
const s3path = 'fotos_cdcc/' + '186620' + '/'
const imageName = '186620_4' + '.jpeg'
const key = s3path + imageName
const fileType = pickerResult.type;
const access = { level: "public", contentType: 'image/jpg' };
const imageData = await global.fetch(pickerResult.uri)
const blobData = await imageData.blob()
try {
await Storage.put(
key,
blobData,
access,
fileType
).then(result => console.log(result))
} catch (err) {
console.log('error: ', err)
}
}
The pickerResult has this form:
Object {
"cancelled": false,
"height": 750,
"type": "image",
"uri": "file:///var/mobile/Containers/Data/Application/021D6288-9E88-4080-8FBF-49F5195C2073/Library/Caches/ExponentExperienceData/%2540anonymous%252Fcaballos-app-dd2fa92e-4625-47e7-940e-1630e824347a/ImagePicker/D9EE1F24-D840-457F-B884-D208FFA56892.jpg",
"width": 748,
}
I tried making the bucket and the photo public in s3, but the error persists.
Any ideas?
Thanks in advance!
Maybe this is not an issue with aws-amplify, instead with fetch and blob. Can you try this?
function urlToBlob(url) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onerror = reject;
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
resolve(xhr.response);
}
};
xhr.open('GET', url);
xhr.responseType = 'blob'; // convert type
xhr.send();
})
}
Then instead of
const imageData = await global.fetch(pickerResult.uri)
const blobData = await imageData.blob()
Try
const blobData = await urlToBlob(pickerResult.uri)
Please find full discussion https://github.com/expo/firebase-storage-upload-example/issues/13
I am kind of new to flutter developments. Above error is getting to show up when import 'package:socket_io/socket_io.dart'; from the package socket_io: ^0.9.0+1
i'm trying to connect node js back end socket to flutter app. I don't use a emulator but a Samsung Tab as a external device.
here is my client program
void main() {
var io = new Server();
var nsp = io.of('/some');
nsp.on('connection', (Socket client) {
print('connection /some');
client.on('msg', (data) {
print('data from /some => $data');
client.emit('fromServer', "ok 2");
});
});
io.on('connection', (Socket client) {
print('connection default namespace');
client.on('msg', (data) {
print('data from default => $data');
client.emit('fromServer', "ok");
});
});
io.listen(3000);
// Dart client
IO.Socket socket = IO.io('http://localhost:3000');
socket.on('connect', (_) {
print('connect');
socket.emit('msg', 'test');
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
runApp(new MyApp());
}
and this is pubspec.ymal
: chat_app
description: A new Flutter project.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# Read more about versioning at semver.org.
version: 1.0.0+1
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
socket_io: ^0.9.0+1
socket_io_client: ^0.9.1
http: ^0.12.0
reflectable: ^2.0.9
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
and this is my back end service which is work fine written in node
const express = require('express')
const app = express()
var mongoose = require("mongoose")
var path = require('path');
var cors = require("cors");
users=[];
app.use(cors())
'use strict';
var jwt = require('jsonwebtoken');
var iss = "Blitzkrieg Software";
var sub = "joe#user.org";
var aud = "http://blitzkriegsoftware.net";
const fs = require('fs');
var privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCETEqGDNQQKnHp1HV3VNmbp30LP2ErB7b4BMQEbMN1YMSAVwll
jhVvxEs0fI6vax0vFUNLSbSPG4o4Kkrunc+tODUvYJbN7Ejv5lZptVvcfvyUJKBQ
N8NYTucxGyVhS8jiYbev7no5ZHoAGDlzTYunzfWiPJ+81lHVjgsEVwHIqw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6c
aAO9H0p0ikjknEidPMxKnpGxqnpevR17OCKPFcKIXkZST23caG7iUhuLLw4B6DV6
KnvFJR2NAkEAsL0f+WzLIE5U/Jii2t0fupTs+iWkpgYX6BHlNi9HqffO4i+SHt4r
kizkjxqBexaHThgMF1txf+jl7T7hanHlFwJBAKll5tRr7QajXf8Je/SdSqZG8DUX
aqGE81srXcPe3hoNt5gLgZFXPQZrwGJW0Nk8gHkU+EBLsmhBK7T5BTy7mKkCQBej
I6ybNUt7znf9/gHhgwXUNyF5eVzPAdGC2zH0/tOnld7AV/2S3ybspCDTfa+1oqD6
LFvPWg2uW1nwh/tRgj8CQH8wTj5Nn0srrSeW4WUj90aJY4Ec0PQLdzAW8fSr/jdj
hYCQv/Cz9xxCyeTfZC37sahbyc5UbXNtsRH7saYxogQ=
-----END RSA PRIVATE KEY-----`;
var exp = 24;
var signOptions = {
issuer : iss,
subject: sub,
audience: aud,
expiresIn: exp,
algorithm: "RS256"
};
var payload = { };
// Populate with fields and data
payload.field01 = "Data 01";
payload.field02 = "Data 02";
payload.field03 = "Data 03";
var token = jwt.sign(payload, publicKey, signOptions);
console.log("Token: " + token);
var decoded = jwt.decode(token, {complete: true});
console.log("Docoded Header: " + JSON.stringify( decoded.header));
console.log("Docoded Payload: " + JSON.stringify(decoded.payload));
app.use(express.static('public'))
app.use(cors());
app.get('/',(req,res)=>{
res.render('index')
res.status=600;
})
server = app.listen(3000,"0.0.0.0");
// app.get('/', function (req, res) {
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// res.writeHead(200, {'Content-Type': 'text/plain'});
// contents = fs.readFileSync("sliderImages.json", "utf8");
// console.log(path.join(__dirname, '/sliderImages.json'));
// res.end(contents);
// });
const io= require('socket.io')(server)
io.on('connection', (socket) => {
var dbUrl = 'mongodb://brad:1234#localhost:27017/bawa'
mongoose.connect(dbUrl ,{ useNewUrlParser: true }, (err,db) => {
// db.collection("customers").insertOne({"first_name":"gahsat","last_name":"assdf"}, function(err, res) {
// if (err) throw err;
// console.log("1 document inserted");
// db.close();
// });
// db.collection("customers").find({}, { projection: { _id: 0, first_name: 1, last_name: 1 } }).toArray(function(err, result) {
// if (err) throw err;
// console.log(result);
// db.close();
// });
console.log('Db connected',err);
})
console.info('New user connected'+socket.id)
//default username
socket.userId = "Anonymous"
//listen on change_username
socket.on('change_userId', (data) => {
console.info('change_userId: ' + data);
socket.userId = data.userId
})
socket.on('register', (data) => {
console.info('New user cregonnected '+socket.id)
console.info('register: ' + data);
socket.userId = data.userId
})
socket.on('disconnect', (data) => {
console.info('change_userId: ' + data);
socket.userId = data.userId
})
socket.on('send message', (data) => {
console.info('New user sen '+socket.id)
//var a=JSON.parse(data)
console.info('messasge: ' + data["kk"]);
io.sockets.emit('get user','sdfgsdfgsdf')
})
//listen on new_message
socket.on('new_message', async (data) => {
//broadcast the new message
let chat = chatDb.chats.find(_chat => _chat.id === data.chatId);
chat.dialog = [
...chat.dialog,
data.message
];
let userId = data.message.who;
let contactId = data.contactId;
const user = chatDb.user.find(_user => _user.id === userId);
console.info('new_message User: ' + JSON.stringify(user));
const contact = chatDb.user.find(_user => _user.id === contactId);
console.info('new_message Contact: ' + JSON.stringify(contact));
user.chatList.find(_contact => _contact.contactId === contactId).lastMessageTime = data.message.time;
contact.chatList.find(_contact => _contact.contactId === userId).lastMessageTime = data.message.time;
console.info('new_message: ' + JSON.stringify(data));
io.sockets.emit('new_message', {userId: userId, contactId: contactId, chatId: data.chatId, message: data.message});
})
//listen on typing
socket.on('typing', (data) => {
socket.broadcast.emit('typing', {userId : socket.userId, chatId: data.chatId})
})
});
console.log('Server Started')
I hope i couldn't find an answer why this happens and how to resolve..
please help
The package socket_io is not compatible with Flutter. You can therefore not use it within a Flutter application.
//server.js
const Koa = require('koa')
const app = new Koa();
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
const Router = require('koa-router');
const fs = require('fs');
const router = new Router();
const UserController = require('./server/controller/user.js');
const checkToken = require('./server/token/checkToken.js');
router.get('/user/login', async ctx => {
ctx.body = JSON.parse(fs.readFileSync( './pass.json'));
console.log(ctx.body);
});
router.post('/signin', async (ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p>Try again</p>`;
}
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8090, () => {
console.log('The server is running at http://localhost:' + 8090);
});
koa:2.52
koa-bodyparse:4.21
koa-router:7.4
when I type http://localhost:8090/user/login can get the Json data,but type http://localhost:8090/signin always show 405 Methods Not Allowed ,(debian firefxo) show Request Method "GET",response Allow: POST,Connection: "keep-alive"
I hope get your help.
I guess you shouldn't use the chrome to do the post cause when you type some url, the default method is GET not POST, you can check it out from the NETwork。 Try postman it will work.Sorry for my bad english,I hope it will help XD