Deepstream 1 - n relation - deepstream.io

I'm trying to build a user notification using Deepstream.io. I'm using deepstream.io-storage-mongodb for storage. My data structure:
User
=================
id - email - others
Notication
=================
userId - notification
I'm try to implement 1-n modelling deepsteam tutorial. But I can't understand how can I do this. How can I store pointer or how can I point towards a List ? Or how can I implement notification using deepstream ?
Thanks in Advance.

you can try as like as given below (I'm using JS):
Receive Notication
var client = deepstream( 'localhost:6020' );
client.login();
// Unique Identification for user
let uniqueId = `userId:${userId}`;
// Mongodb collection : Notification
statusRecord = client.record.getList("Notification/" + uniqueId);
statusRecord.subscribe(function(data) {
data.forEach(function(name) {
var record = client.record.getRecord(name);
record.whenReady(function(r) {
// all notification
console.log( "r ==> ", r.get() );
});
});
});
Send Notification
const ds = deepstream( 'localhost:6020' );
ds.login();
// userId
const list = this.ds.record.getList( `Notification/${userId}` );
// id for notification
let id = `Notification/${this.ds.getUid()}`;
let record = this.ds.record.getRecord(id);
record.set( {
message: 'information'// save notification data
});
list.addEntry(id);
Hope it will solve your problem.

Related

Blacklisted words | Filter words discord.bs

I got one error with my blacklisted words, cannot read proprety ".id" of undefined. After "db.get(...)"
Thanks to help me!
// BLACKLISTED words
client.on('message', message => {
if(message.author.bot) return;
let wordarray = message.content.split(" ")
let filterWords = db.get(`blacklistwords_${message.guild.id}_${message.guild.id}`)
for(var i = 0; 1 < filterWords.length; i++) {
if(wordarray.includes(filterwords[i])) {
message.delete()
let Filter = new Discord.MessageEmbed()
.setColor('#FFE90F')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription('<a:AttentionPink:706154679796760657> | **This word is blacklisted from this guild!** Do not say that again!')
.setTimestamp()
message.author.send(Filter)
break;
}
}
});![enter image description here](https://i.stack.imgur.com/Gouis.jpg)
I think you should put your Guild ID in a var like so:
var guildID = message.guild.id;
If this is not working, well it's not the prettiest, but try using this line of code:
var guildID = bot.guilds.get(message.guild.id).id;
EDIT: Source
If the bot receives a message via DMs, it will not be able to get message.guild and that's why it says it is undefined. You can add something like if(message.channel.type === 'dm') return; so that the bot will not listen to DMs

SQLite database isn't holding multiple values under primary key in my Discord.js bot

To start off, here's my main bot.js code (Sorry if it seems like code spaghetti. I'm not the best with javascript):
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const pack = require('./package.json');
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () => {
console.log(` Bot: ${client.user.tag}
Version: ${pack.version}
Logged in and clear for takeoff.`);
});
client.on("ready", () => {
const battle_leaderboard = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!battle_leaderboard['count(*)']) {
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER;").run();
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points) VALUES (#id, #user, #guild, #points);");
client.removeScore = sql.prepare("DELETE FROM scores WHERE user=?");
});
client.on('message', message => {
if (!message.content.startsWith(auth.prefix) || message.author.bot) return;
const args = message.content.slice(auth.prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
switch (command) {
case 'ping':
client.commands.get('ping').execute(message, args);
break;
case 'mimic':
client.commands.get('mimic').execute(message, args);
break;
case 'add_role':
client.commands.get('add_role').execute(message, args);
break;
case 'remove_role':
client.commands.get('remove_role').execute(message, args);
break;
case 'bl_add_point':
if (message.member.roles.some(r=>["Fight Officiator"])) {
let score;
let member = message.mentions.members.first() || client.members.get(args[0]);
score = client.getScore.get(member.id, member.guild.id);
if (!score) {
score = { id: `${member.guild.id}-${member.id}`, user: member.username, guild: member.guild.id, points: 0}
}
score.points ++;
client.setScore.run(score);
message.channel.send(`Looks like ${member} got a win! Good one.`);
} else {
message.channel.send(`Sorry, this is only usable by GFOs.`);
};
break;
case '!bl_delete':
if (message.member.roles.some(r=>["Fight Officiator"])) {
let member = message.mentions.users.first();
client.removeScore.run(`${member.guild.id}-${member.id}`)
message.channel.send(`${member} has been set to zero on the leaderboard!`);
} else {
message.channel.send(`Sorry, this is only usable by GFOs.`);
};
break;
case 'bl':
const top5 = sql.prepare("SELECT * FROM scores WHERE guild = ? ORDER BY points DESC LIMIT 5;").all(message.guild.id);
const battleleaderboard = new Discord.RichEmbed()
.setColor('#FFD700')
.setTitle('The Battle Leaderboard - Current Rankings')
.setAuthor(`RankBot`)
.setDescription('The top fighters are displayed here.')
.setTimestamp()
.setFooter(`DM a Gang Fight Officiator to set up a spar with another member and possibly get your name registered onto RankBot's leaderboard!`);
for (const data of top5) {
battleleaderboard.addField(client.users.get(data.user), `${data.points} Win(s)`);
}
message.channel.send(battleleaderboard);
break;
};
});
client.login(auth.token);
I'm creating a bot that should be pretty simple:
The bot is a RankBot (at least that's what i dubbed it as), which is supposed to track the amount of wins in battles (since this is for a discord about a fighting game) using a special role that manually increments those wins with a command, then being able to pull up a leaderboard embed showing the people with the most wins. I'm testing it in a discord separate from the one it's for with a friend, and it seemingly worked until we commanded the bot to open the leaderboard. Nothing was shown. We thought it was strange, since it worked before when only one user was in the database, and I went to the PowerShell Command Line to see if there was an error message, and this showed up.
C:\Users\USER\Documents\OF_RankBot\bot.js:89
battleleaderboard.addField(client.users.get(data.user).tag || client.members.get(data.user).tag, `${data.points} Win(s)`);
^
TypeError: Cannot read property 'tag' of undefined
We were confused by what happened, so I removed the tag part of the command and used it again. The embed showed up this time, but it looked like this.
I assumed that what went wrong was that since they both had the same number of wins listed, the part of the bl command that sorts the users was confused. I then went and used bl_add_point on me and tried again. The near exact same embed was shown.
My guess as to what went wrong was that I messed up at some point when setting up the bl_add_point command, but I'm not sure how to fix the issue.
This isn't part of the main problem, but I can't seem to get bl_delete working either. No errors are shown when I use it. In fact, seemingly nothing happens. I'm not sure if these issues are connected, but I really only need the main issue fixed.
Thanks in advance.
edit: I found out partially what happened with the bl_delete issue, which was I simply put the prefix into the case when the prefix was already defined. Now when I put in the command, the PowerShell responds with:
C:\Users\USER\Documents\OF_RankBot\bot.js:72
client.removeScore.run(`${member.guild.id}-${member.id}`)
^
TypeError: Cannot read property 'id' of undefined

Crunchbase Data API v3.1 to Google Sheets

I'm trying to pull data from the Crunchbase Open Data Map to a Google Spreadsheet. I'm following Ben Collins's script but it no longer works since the upgrade from v3 to v3.1. Anyone had any luck modifying the script for success?
var USER_KEY = 'insert your API key in here';
// function to retrive organizations data
function getCrunchbaseOrgs() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Organizations');
var query = sheet.getRange(3,2).getValue();
// URL and params for the Crunchbase API
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
var json = getCrunchbaseData(url,query);
if (json[0] === "Error:") {
// deal with error with fetch operation
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([json]);
}
else {
if (json[0] !== 200) {
// deal with error from api
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([["Error, server returned code:",json[0]]]);
}
else {
// correct data comes back, filter down to match the name of the entity
var data = json[1].data.items.filter(function(item) {
return item.properties.name == query;
})[0].properties;
// parse into array for Google Sheet
var outputData = [
["Name",data.name],
["Homepage",data.homepage_url],
["Type",data.primary_role],
["Short description",data.short_description],
["Country",data.country_code],
["Region",data.region_name],
["City name",data.city_name],
["Blog url",data.blog_url],
["Facebook",data.facebook_url],
["Linkedin",data.linkedin_url],
["Twitter",data.twitter_url],
["Crunchbase URL","https://www.crunchbase.com/" + data.web_path]
];
// clear any old data
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
// insert new data
sheet.getRange(6,1,12,2).setValues(outputData);
// add image with formula and format that row
sheet.getRange(5,2).setFormula('=image("' + data.profile_image_url + '",4,50,50)').setHorizontalAlignment("center");
sheet.setRowHeight(5,60);
}
}
}
This code no longer pulls data as expected.
I couldn't confirm about the error messages when you ran the script. So I would like to show about the clear difference point. It seems that the endpoint was changed from https://api.crunchbase.com/v/3/ to https://api.crunchbase.com/v3.1/. So how about this modification?
From :
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
To :
var url = 'https://api.crunchbase.com/v3.1/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
Note :
From your script, I couldn't also find query. So if the script doesn't work even when you modified the endpoint, please confirm about it. You can see the detail of API v3 Compared to API v3.1 is here.
References :
API v3 Compared to API v3.1
Using the API
If this was not useful for you, I'm sorry.

Set a variable messagingSenderId in service worker (Firebase) [duplicate]

This question already has answers here:
Passing state info into a service worker before `install`
(2 answers)
Closed 5 years ago.
I would like to set a variable messagingSenderId value in my service worker, not an hardcoded one. Is it possible?
I register my service worker like this:
navigator.serviceWorker.register( 'firebase-messaging-sw.js' )
.then( function( registration ) {
messaging.useServiceWorker( registration );
});
And in my firebase-messaging-sw.js, I initialize firebase like this
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js' );
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js' );
firebase.initializeApp({
'messagingSenderId': 'my-id' // <- I want this to be variable
});
The problem is I can't find how to pass data to my service worker file. Any idea?
Thanks
As mentionned, Passing state info into a service worker before 'install' answered the question. Thanks.
Here is the answer for this use case:
You need to pass the variable in the URL like so:
var myId = 'write-your-messaging-sender-id-here';
navigator.serviceWorker.register( 'firebase-messaging-sw.js?messagingSenderId=' + myId )
.then( function( registration ) {
messaging.useServiceWorker( registration );
});
And then, in firebase service worker (firebase-messaging-sw.js), you can get this variable like so:
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js' );
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js' );
var myId = new URL(location).searchParams.get('messagingSenderId');
firebase.initializeApp({
'messagingSenderId': myId
});
This works. But URL.searchParams is a very new tool. It is less compatible than Firebase itself.
URL.searchParams: Chrome 51+, Firefox: 52+, Opera: unknown
Firebase: Chrome 50+, Firefox 44+, Opera 37+
So instead of:
var myId = new URL(location).searchParams.get('messagingSenderId');
I suggest using:
var myId = get_sw_url_parameters( 'messagingSenderId' );
function get_sw_url_parameters( param ) {
var vars = {};
self.location.href.replace( self.location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}

Get Transaction Id after completing Payment Objective c?

I was trying to get transation Id when paypal payment is done that is on didCompletePayment method, i can get only these details
Confirmation: {
client = {
environment = sandbox;
"paypal_sdk_version" = "2.12.2";
platform = iOS;
"product_name" = "PayPal iOS SDK";
};
response = {
"create_time" = "2017-02-01T07:40:43Z";
id = "PAY-4RK70135CF912010FLCIZB5A";
intent = sale;
state = approved;
};
"response_type" = payment;
}
I don't find transation ID here. Can any one suggest me how to get transation Id in detail so that i can save that to database.
I found some Curl concepts but i'm not sure where to start with.Please give me some suggestions.
Thanks in advance