sqlite gives error when I use discordjs-commando setProvider() - discord.js

Im using the discordjs-commando and
client.setProvider(
sqlite.open(path.join(__dirname, 'settings.sqlite3')).then(db => new Commando.SQLiteProvider(db))
).catch(console.error);
is giving me this error
Error: sqlite: filename is not defined
Any idea how to make it work?

I think I know a way to fix it
client.setProvider(
sqlite.open({ filename: path.join(__dirname, 'settings.sqlite3')}).then(db => new Commando.SQLiteProvider(db))
).catch(console.error);
use this

Yo, so this reply is probably late asf. But, I got this working by doing the following:
// This line simply checks to see if my Node.js version is version 12.
// If it isn't, it then tells me to update Node.js
if (Number(process.version.slice(1).split(".")[0]) < 12) throw new Error("Node 12.0.0 or higher is required. Update Node on your system.");
// These are my imports
const { CommandoClient, Commando } = require('discord.js-commando');
const { promisify } = require("util");
const readdir = promisify(require("fs").readdir);
const Enmap = require("enmap");
const path = require('path');
require('./.eslintrc.json');
require('dotenv').config();// I used dotenv to store my more secure info
const TOKEN = process.env.CLIENT_TOKEN;// This line reads my Client Token from dotenv
const PREFIX = process.env.CLIENT_PREFIX;// This line reads my Client Prefix from dotenv
const OWNER_ID = process.env.OWNER;// This line reads the bot's owner id from dotenv
const init = async () => {// I crteated an async wrapper for my client here
const sqlite = require('sqlite');// I imported SQLite here
const client = await new CommandoClient({// I set my client here
commandPrefix: PREFIX,
owner: OWNER_ID,
disableEveryone: true,
unknownCommandResponse: false
});
client.setProvider(// This line of code sets my SQLite DB Provider
sqlite.open({ filename: path.join(__dirname, 'settings.sqlite3') }).then(db => new Commando.SQLiteProvider(db))
).then(console.log).catch(console.error);
// Since I'm wrapping my client in an async wrapper, my commands and groups are registered here
client.registry
.registerDefaultTypes()
.registerGroups([
['admin', 'Administration'],
['mod', 'Moderation'],
['util', 'Utility'],
['misc', 'Miscellaneous'],
['twitch', 'Twitch']
])
.registerDefaultGroups()
.registerDefaultCommands()
.registerCommandsIn(path.join(__dirname, 'commands'));
client.commands = new Enmap();// This sets a new Enmap for my commands
client.aliases = new Enmap();// This sets a new Enmap for my command aliases
client.settings = new Enmap({ name: "settings" });//This sets a new Enmap for my settings
client.logger = require("./modules/Logger.js");//This line makes my bot require the internal Logger.js file I have in my bot's modules folder
require("./modules/functions.js")(client);// This line makes my bot require the internal functions.js file I have in my bot's modules folder
const evtFiles = await readdir("./events/");
client.logger.log(`Loading a total of ${evtFiles.length} events.`);
evtFiles.forEach(file => {
const eventName = file.split(".")[0];
client.logger.log(`Loading Event: ${eventName}`);
const event = require(`./events/${file}`);
// Bind the client to any event, before the existing arguments
// provided by the discord.js event.
client.on(eventName, event.bind(null, client));
client.login(TOKEN).catch(console.error);// Since my client is in an async wrapper, I imported my TOKEN here
});
};
init();// Now that I've finished with the rest of my index.js file I have ended the async wrapper here
It may not be of much use to you anymore but I hope this helps others in the future.

client.setProvider(
sqlite.open({ filename: 'database.db', driver: sqlite3.Database }).then(db => new Commando.SQLiteProvider(db))
).catch(console.error);
This will fix it for sure

Related

How can I create a React front end that allows me to deploy a Solidity contract?

I am able to build the interface for the React app. I am able to create a deploy script using "#nomiclabs/hardhat-ethers" that compiles a .sol contract and successfully deploys it. What I cannot do is combine the two.
What I want is to click a button in the React app to deploy the contract.
I want to use hardhat's ethers.getContractFactory() method to compile and then deploy.
When I add "#nomiclabs/hardhat-ethers" to my project with
const { ethers } = require("#nomiclabs/hardhat-ethers");
I get an error about Hardhat context being required, so i add
require('hardhat').config()
Then I get
"Module not found: can't resolve 'async_hooks' in /node_modules/undici/lib/api"
Is there another library I can use to achieve what I want, or am I just missing something/doing something wrong?
require('dotenv').config();
const { createAlchemyWeb3 } = require("#alch/alchemy-web3");
const web3 = createAlchemyWeb3(process.env.REACT_APP_ALCHEMY_KEY);
require('hardhat').config();
const { ethers } = require("#nomiclabs/hardhat-ethers");
export const deployAuction = async (options) => {
const AuctionFactory = new ethers.getContractFactory("Auction");
// Start deployment, returning a promise that resolves to a contract object
const auction = await AuctionFactory.deploy(
options.token,
options.paymentToken,
options.bidIncrement,
options.timeoutPeriod
);
console.log("Contract deployed to address:", auction.address);
return auction.address;
};
Please, any help is appreciated. Thank you!
Once you deployed the contract with hardhat, you will see artifacts folder which stores the deployed contracts. since your contract name is Auction you will have artifacts/contracts/Auction/Auction.json. this JSON files includes the abi code of your contract. to create a contract instance you need to bring it to your frond-end.
To create a contract instance you need 3 arguments:
1- Address of the contract
2- abi of the contract
3- provider
// I wrapped with function to be able to use "await"
const createContract = async () => {
// make sure you pass correct path
// fetching json works in next.js, I believe React18 supprts it
const res = await fetch('artifacts/contracts/Auction/Auction.json');
const artifact = await res.json();
// address is inisde the json file. 5 is goeerli.
// depending on your config, you might have a different networkId
const address = artifact.networks[5].address;
// in react.js window.ethereum will be defined. in next.js you need to add if(window.ethereum){code here}
const provider = new ethers.providers.Web3Provider(window.ethereum);
const contract = new ethers.Contract(address, artifact.abi, provider);
return contract;
};

Trying to set thirdweb token, feed that to SDK, and Receive token module array from third web. Problem- The token module is empty

I am running VisualStudio Code, Sanity Studio, and Thirdweb
When I inspect the element on localhost:3000, I am able to see the array of my imported tokens on Sanity, but NOT on Thirdweb.
Here is a snippet of my code:
const sdk = new ThirdwebSDK(
new ethers.Wallet(
process.env.NEXT_PUBLIC_METAMASK_KEY,
ethers.getDefaultProvider('https://rinkeby_xyz),
),
)
const Portfolio = () => {
const[sanityTokens, setSanityTokens] = useState([])
const[thirdWebTokens, setThirdWebTokens] = useState([])
useEffect (() => {
const getSanityAndThirdWebTokens = async () => {
const coins = await fetch("https://xyz"
)
const sanityTokens = (await coins.json()).result
setSanityTokens(sanityTokens)
setThirdWebTokens(
sanityTokens.map(token => sdk.getTokenModule(token.contractAddress))
)
}
return getSanityAndThirdWebTokens()
}, [])
console.log('Sanity', sanityTokens)
console.log('Thirdweb', thirdWebTokens)
Error Message: Unhandled Runtime Error
TypeError: sdk.getTokenModule is not a function
How do I get the ThirdWeb array to show up?
A lot has changed with thirdwebSDK. getTokenModule is no longer a valid function as of this time, instead try sdk.getToken(token.contractAddress) in the part of the code where you have sdk.getTokenModule(token.contractAddress)
On the latest versions of thirdweb SDK, this is how you initialize the SDK:
const sdk = ThirdwebSDK.fromPrivateKey(PRIVATE_KEY, "rinkeby")
With that being said, you are not referencing a PRIVATE_KEY, you have NEXT_PUBLIC_METAMASK_KEY, which you should never do, this would make it so your private key is exposed to the client and anyone visiting your page will get full access to your wallet and will be able to steal all your funds.
What you should do is instantiate the SDK with a read-only RPC, no need to pass a private key at all in this situation. You can instantiate the SDK like this:
const sdk = new ThirdwebSDK("rinkeby")
And again, getTokenModule is not a function, you need to import getToken and pass the contract address.
I hope that helps.

Trying to Call Google Cloud Function, Where Do I Put The Function URL And /path/to/credentials.json in CloudFunctionsServiceClient?

I copied this code from https://cloud.google.com/nodejs/docs/reference/functions/latest/functions/v1.cloudfunctionsserviceclient:
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The name of the function to be called.
*/
// const name = 'abc123'
/**
* Required. Input to be passed to the function.
*/
// const data = 'abc123'
// Imports the Functions library
const {CloudFunctionsServiceClient} = require('#google-cloud/functions').v1;
// Instantiates a client
const functionsClient = new CloudFunctionsServiceClient();
async function callCallFunction() {
// Construct request
const request = {
name,
data,
};
// Run request
const response = await functionsClient.callFunction(request);
console.log(response);
}
callCallFunction();
This doesn't help me that much. I have a cloud function (in Python) that simply prints "hello world" or something simple like that. My cloud function can only be run through a "service account" that I created and I downloaded the .json file containing my credentials for this service account.
I'm making a Next.js app (with typescript) and I want to call this function in the app. So keeping the above example in mind where do I put these variables?
https://us-central1-<projectname>.cloudfunctions.net/<functionname>
/path/to/credentials.json
You can use your credentials.json by passing it on the constructor. Also you won't be needing to explicitly call the URL of the function. Properly defining the function in name should tell your code to use the function.
Using your code, I modified it to include the use of the credentials.json and defining of name. You can check this reference to construct the name properly.
const project = 'your-project' // update with your project name
const location = 'us-central1' //update this with the actual location of your function
const func_name = 'function-1' // update with your function name
const name = `projects/${project}/locations/${location}/functions/${func_name}`
const keyFilename = '/credentials.json' // update with the full path of your json
const data = '{"message":"test"}' // update with your request body
// Imports the Functions library
const {CloudFunctionsServiceClient} = require('#google-cloud/functions').v1;
// Instantiates a client
const options = {keyFilename};
const functionsClient = new CloudFunctionsServiceClient(options);
async function callCallFunction() {
// Construct request
const request = {
name,
data,
};
// Run request
const response = await functionsClient.callFunction(request);
console.log(response);
}
callCallFunction();
Test run:

How to send a message based on event Google PubSub?

I need some help with PubSub...
I need to send a message to a topic every time someone accept cookies in my website. This message should contain the encodedURL that contains the services accepted.
I have this script:
const topicName = "myTopic";
const data = JSON.stringify({
encodeConsentURL:""
});
// Imports the Google Cloud client library
const { PubSub } = require("#google-cloud/pubsub");
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function publishMessageWithCustomAttributes() {
// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);
// Add two custom attributes, origin and username, to the message
const customAttributes = {};
const messageId = await pubSubClient
.topic(topicName)
.publish(dataBuffer, customAttributes);
console.log(`Message ${messageId} published.`);
console.log(customAttributes);
}
publishMessageWithCustomAttributes().catch(console.error);
This code works, it sends the message, what I'm finding very hard to do is how to set everything right for running this code in my cookie script. In my cookie script I have a function that writes the cookie, in the same function I would like to send the message, is this possible? Thanks in advance!
It is a bit late, but I don't get it, if you already have a working cookie script and a working publish script, isn't it just about putting them together?
If you still need help I'll be happy to help you
Something like
const runEverything = async () => {
try {
await checkCookiesThing()
await publishMessage()
} catch (e) {
console.error(e)
}
}

Guild Members TImeout: Members didn't arrive in time

So I have this command that shows the riches users in a server this command worked yesterday however recently it has stopped working.
const { MessageEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
const { prefix } = require("../../botconfig.json");
const db = require('quick.db')
let bal = require('../../database/balance');
let rep = require('../../database/rep');
let work = require('../../database/works');
module.exports = {
config:{
name: "rich",
aliases: ["r"],
category: "currency",
description: "Tells who is rich",
usage: ""
},
run: async (client, message, args) => {
// Get all members of the server before doing anything
message.guild.members.fetch().then(guildMembers => {
let board = [];
for (let key of Object.keys(bal)) {
// Checks if the collection of GuildMembers contains the key.
if (guildMembers.has(key)) {
let value = Object.assign({user: guildMembers.get(key).user}, bal[key]);
board.push(value);
}
}
const emojis = [':first_place:', ':second_place:', ':third_place:', ':small_blue_diamond:', ':small_blue_diamond:']
board = board.sort((a,b) => b.balance-a.balance).splice(0, 5);
let top = board.map((x, i) => `${emojis[i]} **${x.balance.toLocaleString()}** - ${x.user.tag}`).join('\n');
let embed = new MessageEmbed()
.setColor("RANDOM")
.addField(`Richest users in **${message.guild.name}**`, `${top}`)
.setFooter('Switch Version 1.1');
return message.channel.send(embed);
}).catch(console.error)
}
}
The error code when the !rich command is used is as follows:
Guild_Members_Timeout: Members didn't arrive in time
I don't know if this is an issue within the bot or if it is an issue with discord.
Okay I have found the answer to my own problem it seems I needed to add intents to my discord bot to fetch the members.
All I did was add this line of code and it worked.
const intents = new Intents([
Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need
"GUILD_MEMBERS", // lets you request guild members (i.e. fixes the issue)
]);
const client = new Client({ ws: { intents } });
None of my discord.js guildmember events are emitting, my user caches are basically empty, and my functions are timing out? . In this post it is explained in great detail and that helped me out a lot.TLDR:go to discord developer portal on your particular application ,go to bot , on bot permissions tick whatever is needed and copy the number.Then use this number as a constructor parameter for new Discord.Intents('insert the number here').This worked for me.

Resources