I dont know what module I'm missing - discord.js

Okay so here's my code:
const mineflayer = require("mineflayer");
const discord = require("discord.js");
const config = require("./config.json");
const colors = require("colors");
const client = new discord.Client({autoReconnect: true});
const options = {
host: 'mc.hypixel.net',
port: 25565,
version: '1.8.9',
username: config["minecraft-username"],
password: config["minecraft-password"],
};
// minecraft bot stuff vv
let mc;
(function init() {
console.log("Logging in.");
mc = mineflayer.createBot(options);
mc._client.once("session", session => options.session = session);
mc.once("end", () => {
setTimeout(() => {
console.log("Connection failed. Retrying..");
init();
}, 60000);
});
}());
let uuid;
let name;
mc.on("login", () => {
uuid = mc._client.session.selectedProfile.id;
name = mc._client.session.selectedProfile.name;
setTimeout(() => {
console.log("Sending to limbo.");
mc.chat("/achat \u00a7c<3");
}, 1000);
mc.chat("/gc Logged in")
});
mc.on("message", (chatMsg) => {
const msg = chatMsg.toString();
console.log("Minecraft: ".brightGreen + msg);
if (msg.endsWith(" joined the lobby!") && msg.includes("[MVP+")) {
console.log("Sending to limbo.");
mc.chat("/achat \u00a7ca");
return;
}
if (msg.startsWith("Guild >") && msg.includes(":")) {
let v = msg.split(" ", 2);
if (v[2].includes(name + ":") || v[3].includes(name + ":")) return;
let splitMsg = msg.split(" ");
let i = msg.indexOf(":");
let splitMsg2 = [msg.slice(0,i), msg.slice(i+1)];
let sender, sentMsg;
if (splitMsg[2].includes("[")) {
sender = splitMsg[3].replace(":","");
} else {
sender = splitMsg[2].replace(":","");
}
sentMsg = splitMsg2[1];
let embed = new discord.RichEmbed()
.setAuthor(sender + ": " + sentMsg, "https://www.mc-heads.net/avatar/" + sender)
.setColor("GREEN");
//channel.send(embed);
client.guilds.get(config["discord-guild"]).channels.get(config["discord-channel"]).send(embed);
}
});
// discord bot stuff vv
client.on("ready", () => {
console.log("Discord: Logged in.".bgBlue);
});
client.on("message", (message) => {
if (message.channel.id !== config["discord-channel"] || message.author.bot || message.content.startsWith(config["discord-bot-prefix"])) return;
console.log("Discord: ".blue + message.author.username + ": " + message.content);
mc.chat("/gc d. " + message.author.username.replace(" ", "") + ": " + message.content);
});
client.login(config["discord-token"]);
And here's my package.js file:
{
"name": "discord-hypixel-bridge",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "Squag",
"license": "GPL-3.0",
"dependencies": {
"discord.js": "^12.5.1",
"mineflayer": "^2.40.0",
"colors": "^1.4.0",
"follow-redirects": "^1.13.1",
"safe-buffer": "^5.2.1",
"nearley": "^2.20.0"
}
}
Here's the error that I get:
Check /app/package.json: command not found. Is a start script missing?
Can someone help me with this?

In order to use npm start to run your project, you need to add the scripts object to your package.json. Also, your file is currently called package.js, so make sure to rename that to package.json.
{
"name": "discord-hypixel-bridge",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "Squag",
"license": "GPL-3.0",
"dependencies": {
"discord.js": "^12.5.1",
"mineflayer": "^2.40.0",
"colors": "^1.4.0",
"follow-redirects": "^1.13.1",
"safe-buffer": "^5.2.1",
"nearley": "^2.20.0"
},
"scripts": {
"start": "node ."
}
}
More info on the npm docs.

Related

Github Login (oAuth ) from react- chrome extension

I am building a simple chrome extension which will make some simple API calls.
For this, I need the user to be logged in with a Github Account, however, if I set up a new oAuth app on github, I need to add Homepage URL and Authorization callback URL which, as far as I understand, we don't have from a Chrome Extension popup.
IMPORTANT: I don't want to use firebase. All I need is to be able to get the user code, which I can process in my backend after to get the token and all the rest.
Need you help here ! :-)
Here is my background file
const GITHUB_AUTHORIZATION_UL = "https://github.com/login/oauth/authorize";
const CLIENT_ID = encodeURIComponent("xxxx");
const SCOPE = encodeURIComponent("user:email");
let user_signed_in = false;
function create_auth_endpoint() {
let endpoint_url = `${GITHUB_AUTHORIZATION_UL}
?client_id=${CLIENT_ID}
&scope=${SCOPE}`;
return endpoint_url;
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'login') {
chrome.identity.launchWebAuthFlow({
url: create_auth_endpoint(),
interactive: true
}, (response) => {
console.log(response)
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError)
console.log("Could not authenticate.");
sendResponse('fail');
} else {
user_signed_in = true;
sendResponse('success');
}
});
return true;
} else if (request.message === 'logout') {
user_signed_in = false;
sendResponse('success');
}
});
And my login handler from popup.tsx
const handleLogin = () => {
chrome.runtime.sendMessage({ message: 'login' }, function (response) {
console.log(response)
if (response === "success") {
window.close();
}
});
Manifest:
{
"name": "test ext",
"description": "test ext",
"version": "1.0.0",
"manifest_version": 3,
"icons": {
"16": "favicon-32.png",
"48": "favicon-32.png",
"128": "favicon-32.png"
},
"action": {
"default_popup": "popup.html",
"default_title": "test ext",
"default_icon": "favicon-32.png"
},
"permissions": ["storage", "identity"],
"options_page": "options.html",
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
]
}
I tried with various options for the requested url for github such as : http://chrome-extension://CHROME_ID/popup.html
=> This fails directly.
Interestingly, if I just input https://www.google.com, I have a popup with the github login, then I am directly to google and it fail.
However, the extension authorization is added as "accepted" in my github account.
Here is my log from the background for response :
{message: 'The user did not approve access.'}eventhough I approved it. Once I am redirected to the popup with www.google.com it fails

Cashfree Payment gateway Integration in react native and laravel (orderAmount is required error)

I am integrating CashFree payment gateway in react native app (Android). I am following this documentation https://docs.cashfree.com/docs/react-native-2-0-sdk#web-checkout. While implementing I am getting response as
{"type":"CashFreeResponse","txMsg":"orderAmount not provided","txStatus":"FAILED"}
But I am passing all the params what all required to proceed for payment.
const handlePayment = response => {
console.log('amount', total);
var mode = 'TEST';
var map = {
"appId": response.credentials.app_id,
"orderId": response.credentials.order_id,
"orderCurrency": 'INR',
"orderAmount": 150, //parseInt(response.data.price)
"customerPhone": response.user.mobile,
"customerEmail": response.user.email,
"tokenData": response.payment_info.cftoken,
"orderNote": 'Subscription Payment',
"notifyUrl": '',
"customerName": response.user.name,
};
console.log('data', map);
RNPgReactNativeSDK.startPaymentWEB(map, mode, result => {
console.log(result);
var obj = JSON.parse(result, function (key, value) {
console.log(key + '::' + value);
// Do something with the result
});
});
};
As per the Documentation mentioned on their website you need to enter the order amount as a string.
const handlePayment = response => {
console.log('amount', total);
var mode = 'TEST';
var map = {
"appId": response.credentials.app_id,
"orderId": response.credentials.order_id,
"orderCurrency": 'INR',
"orderAmount": '150',
"customerPhone": response.user.mobile,
"customerEmail": response.user.email,
"tokenData": response.payment_info.cftoken,
"orderNote": 'Subscription Payment',
"notifyUrl": '',
"customerName": response.user.name,
};
console.log('data', map);
RNPgReactNativeSDK.startPaymentWEB(map, mode, result => {
console.log(result);
var obj = JSON.parse(result, function (key, value) {
console.log(key + '::' + value);
// Do something with the result
});
});
};

Deno array output issue

I am trying to run an API with deno which should show some PDF-Metadata from files from a given directory.
This works fine until the PDF-ID. The PDF-ID should be the last two digits from the file name (eg. jk03.pdf, fh04.pdf,...). If I run the API, all Metadata is shown as an array inside of an object, unless the ID which creates its own array. Does anyone know how I can implement the ID without creating its own array.
This is what I got until now:
import { PDFDocument } from 'https://cdn.skypack.dev/pdf-lib#^1.11.1?dts';
import { opine, json } from "https://deno.land/x/opine#1.3.4/mod.ts";
const app = opine();
const port = 3000;
app.use(json());
let metaData = new Array();
let pdfData = new Object();
app.get("/pdf", async(req, res) => {
const basePath = './Documents/';
for (const dirEntry of Deno.readDirSync("./Documents")) {
async function readDocumentMetadata() {
const filePath = basePath + dirEntry.name
const existingPdfBytes = await Deno.readFile(filePath);
const pdfDoc = await PDFDocument.load(existingPdfBytes, {
updateMetadata: false
});
var pdfId = dirEntry.name.match(/[0-9]+/g)[0];
const file = Deno.openSync(filePath, { read: true });
const fileInfo = Deno.fstatSync(file.rid);
pdfData = {
ID : pdfId[0],
Name : dirEntry.name,
Size : fileInfo.size + " Bytes",
Pages : pdfDoc.getPageCount(),
CreationDate : pdfDoc.getCreationDate(),
ModificationDate : pdfDoc.getModificationDate()
};
metaData.push(pdfData);
};
await readDocumentMetadata();
};
res.json(metaData);
});
console.log("Server running on port", (port));
app.listen(port);
This is the error message i get:
{
"resource": "/c:/Users/JK/deno/deno-vs-node/GetAllPdf.ts",
"owner": "deno",
"code": "2531",
"severity": 8,
"message": "Object is possibly 'null'.",
"source": "deno-ts",
"startLineNumber": 25,
"startColumn": 21,
"endLineNumber": 25,
"endColumn": 50
}
I added .toString() to the end of the line and it works perfectly now;
const pdfId = dirEntry.name.match(/[0-9]+/)?.toString();

How to sort data coming from the API by date in Angular 4

This is the JSON data i am fetching from POSTMAN. I want it to be ordered in a nearest to todays date. I tried many angular pipes but unfortunately nothings working. Any help would be great. I want to sort the date by the "broadcastOn" field. Thanks in advance.
[ {
"messageId": "09ca0609-bde7-4360-9d3f-04d6878f874c",
"broadcastOn": "2018-02-08T11:06:05.000Z",
"message": "{"title":"Server Side Test 2","text":"Different Message again","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}"
},
{
"messageId": "0a5b4d0c-051e-4955-bd33-4d40c65ce8f7",
"broadcastOn": "2018-02-08T10:36:27.000Z",
"message": "{"title":"Broadcast","text":"Broadcast","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}"
},
{
"messageId": "0a98a3f3-aa30-4e82-825a-c8c7efcef741",
"broadcastOn": "2018-02-08T11:45:00.000Z",
"message": "{"title":"Me sending the message","text":"Me sending the message","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}"
},
{
"messageId": "0cb4e30f-756a-4730-a533-594ddcd45335",
"broadcastOn": "2018-02-08T11:01:57.000Z",
"message": "{"title":"Server Side Test","text":"Different Message","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}"
}
]
Im adding a snippet from the service section as well for your reference..
addMessage(message) {
let header: Headers = new Headers();
header.append('Authorization', 'bearer' + this.authservice.getAccessToken());
let options = new RequestOptions({headers: header});
this.sent.push(message);
return this.http.post('https://sexhops8j5.execute-api.us-west-2.amazonaws.com/dev/notifications/broadcast', message, options)
.map(response =>
{
return response.json();
});
}
getMessage(){
let header: Headers = new Headers();
header.append('Authorization', 'bearer' + this.authservice.getAccessToken());
let options = new RequestOptions({headers: header});
return this.http.get('https://sexhops8j5.execute-api.us-west-2.amazonaws.com/dev/notifications/sent', options)
.map(response => {
let message=[];
for(let item of response.json()){
let parsedMessages = JSON.parse(item.message);
message.push({...parsedMessages, BroadcastOn: item.broadcastOn,MessageId: item.messageId});
}
console.log(message);
return message;
});
}
I'm adding a snippet of the .ts file as well
sendMessage(form){
this.messageService.addMessage({message:this.form.value.string, title:this.form.value.titleText, url:this.form.value.imageurl, image:this.form.value.image, broadcastOn:this.date})
.subscribe(message => { this.getSentMessages();console.log(message);}
);
this.message = '';
this.inputImage='';
this.inputTitle='';
this.inputString='';
this.inputUrl='';
}
getSentMessages(){
this.messageService.getMessage()
.subscribe(message => {this.sentMessages = message});
}
It's not necessary lodash, nor moment. broadcastOn is a string. The date is yyy-mm-ddTHH:mm, so, if a date is bigger that other, the string is bigger that other
getSentMessages(){
this.messageService.getMessage()
.subscribe(message => {
this.sentMessages = message.sort((a,b)=>{
return a.broadcastOn==b.broadcastOn?0
:a.broadcastOn>b.broadcastOn?1:-1
}));
});
}
With help of lodash and moment you can do it like this :
var sortedMessages = _.sortBy(messages, function(o) { return
moment(o.broadcastOn);
}).reverse();
//OR (With ES6 way)
var sortedMessages = _.sortBy(messages,(o) => moment(o.broadcastOn) ).reverse();
WORKING DEMO (Angular 5)
var messages = [ {
"messageId": "09ca0609-bde7-4360-9d3f-04d6878f874c",
"broadcastOn": "2018-02-08T11:06:05.000Z",
"message": {"title":"Server Side Test 2","text":"Different Message again","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}
},
{
"messageId": "0a5b4d0c-051e-4955-bd33-4d40c65ce8f7",
"broadcastOn": "2018-02-08T10:36:27.000Z",
"message": {"title":"Broadcast","text":"Broadcast","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}
},
{
"messageId": "0a98a3f3-aa30-4e82-825a-c8c7efcef741",
"broadcastOn": "2018-02-08T11:45:00.000Z",
"message": {"title":"Me sending the message","text":"Me sending the message","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}
},
{
"messageId": "0cb4e30f-756a-4730-a533-594ddcd45335",
"broadcastOn": "2018-02-08T11:01:57.000Z",
"message": {"title":"Server Side Test","text":"Different Message","image":"https://api.adorable.io/avatars/285/abott#adorable.png","url":"https://www.google.co.in"}
}
]
var sortedMessages = _.sortBy(messages, function(o) { return moment(o.broadcastOn); })
.reverse();
console.log(sortedMessages);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>

Node.js API - Works with Postman but not works in Angular.js

I am trying to create a mean application. as a sample, if I post the request through postman the data created at mlab.
in case if I post the same using $http way, it's not working getting the error as :
{
"message": "Family validation failed",
"name": "ValidationError",
"errors": {
"username": {
"message": "Path `username` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "username"
},
"kind": "required",
"path": "username"
},
"password": {
"message": "Path `password` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "password"
},
"kind": "required",
"path": "password"
}
}
}
and the node with mongoose :
.post(function( req, res ){
var family = new Family();
family.username = req.body.username,
family.password = req.body.password,
family.familyLeader = req.body.familyLeader,
family.husband = req.body.husband,
family.wife = req.body.wife,
family.kids = req.body.kids;
family.save(function( err, newFamily ) {
if( err ) {
if ( err.code == 11000) {
return res.json({ success: false, message: 'A user with that username already exists. '});
}
else {
return res.send( err );
}
}
res.json({ message: 'Family created!', newFamily: newFamily });
});
})
here is my angular code :
vm.createNewFamily = function() {
$http({
method : 'POST',
url : '/api/family',
data : vm.form,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function ( data ) {
console.log('retured!', data );
})
}
my full api.js ( node )
var Family = require('../models/model_family');
module.exports = function( app, express ) {
var apiRoute = express.Router();
apiRoute.use(function( req, res, next ) {
console.log( 'some one using the app!' );
next();
})
apiRoute.get('/', function( req, res ) {
res.json({"namea" : "Arif"})
});
apiRoute.route('/family')
.get(function( req, res ){
res.send('family get processing');
})
.post(function( req, res ){
var family = new Family();
family.username = req.body.username,
family.password = req.body.password,
family.familyLeader = req.body.familyLeader,
family.husband = req.body.husband,
family.wife = req.body.wife,
family.kids = req.body.kids;
family.save(function( err, newFamily ) {
if( err ) {
if ( err.code == 11000) {
return res.json({ success: false, message: 'A user with that username already exists. '});
}
else {
return res.send( err );
}
}
res.json({ message: 'Family created!', newFamily: newFamily });
});
})
return apiRoute;
}
EDIT
If you only have problems with username then check you angular data bindings. Im thinking you have typo somewhere like this
<input ng-model="useranme">
Hope this helps.
Put your this code above all the routes in your main server file
----------
----------
var app=express();
app.use(bodyParser.urlencoded({
extended: true
}));
---------
---------

Resources