Reputation: 21
i am creating a discord bot with firebase inside it. But it is showing this error . I included all the necessary things and initialized the config but still giving this error
TypeError: firebase.database() is not a function
This is what i have tried
createReplay("hello", "hi")
var firebase = require("firebase/app");
require('firebase/database');
var firebaseConfig = {
apiKey: "AIzaSyBPKn****MaX081m3T0-6RFbDk",
authDomain: "linkify****baseapp.com",
projectId: "link****f9",
storageBucket: "link****9.appspot.com",
messagingSenderId: "606****0165",
appId: "1:606071650165:****652d31e39129e453c"
};
// Initialize Firebase
var app = firebase.initializeApp(firebaseConfig);
function createReplay(title, msg){
app.database().ref( server + '/links/' + title).set({ //'server' is already declared outside
message: msg
});
}
Upvotes: 1
Views: 445
Reputation: 50830
Discord bots run on a server which is a secure environment that can be accessed only by you and the people you have authorized. In that case, it's ideal to use the Firebase Admin SDK instead of the Javascript SDK you are trying to use.
The Admin SDK which has full access to your Firebase project's resources and does not follow any security rules. That being said you must authorize yourself i.e. checking user's Discord IDs and returning the user's data only.
To install the Admin SDK, use npm (or yarn):
npm install firebase-admin
# yarn add firebase-admin
To initialize the Admin SDK you need a service account and you can get one from the Service Accounts tab in Firebase project's settings as a JSON file. Copy the following code to initialize your Admin SDK:
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert("./serviceAccountKey.json"),
databaseURL: "https://<project-id>.firebaseio.com/"
})
const database = admin.database()
// Discord JS (or REST API) code . . .
The syntax for NodeJS Admin SDK is same to that of the Javascript client SDK so that should not be a problem. But here's how your function with Admin SDK look like:
async function createReplay(title, msg){
return admin.database().ref( server + '/links/' + title).set({
message: msg
}).then(() => {
console.log("Replay Added")
return true
}).catch((e) => console.log(e));
}
Upvotes: 2