How to split my chat commands into differents files? - node.js

I'm creating a basic nodejs based chatbot for discord using discordjs.
In my main script, when a 'message' event is sent, the bot checks if the message match with a specific command and, in this case call it. The functions corresponding to these commands are in methods in a "TextCommand" class, inported in the main script, but the TextCommand file is getting too big I think...
I tried to split each command in one file and export it, but I can't import it as methods into TextCommand class.
index.js
const TextCommand = require('./src/commands.js');
client.on('message', (msg) => {
if (!msg.author.bot) {
let command;
let reg;
let prefix;
if (msg.guild != undefined){ // Guild commands
db.query(`SELECT prefix FROM guilds WHERE discord_id=${msg.guild.id};`, (err, result) => {
if (err) throw err;
prefix = result[0].prefix
command = new TextCommand(prefix, msg)
reg = new RegExp('^' + prefix, 'i')
if (msg.content.startsWith(prefix + 'help')) {
command.help();
} else if (msg.content.startsWith(prefix + 'ping')) {
command.ping();
} else if (msg.content.startsWith(prefix + 'search')) {
command.search();
TextCommand file
module.exports = class TextCommand {
constructor(prefix, msg){
this.message = msg;
this.prefix = prefix;
}
ping(){
this.message.channel.send('pong !');
}
search(){
let search = this.message.content.slice(this.prefix.length + 'search '.length).replace(/ /g, '+');
this.message.channel.send(`http://google.com/search?q=${search}`);
}
I do not understand how to use class extands... but maybe it's a part of the solution, I would include my functions into TextCommands just wrinting them somewhere else (and export it)

Instead of using a class to hold every command you own, try exporting commands.
For instance, in the ready event, you'll want to search the commands folder for command files, which may follow the format of <command name>.js, so a command !foo would be foo.js in the folder commands.
To find all the files in the commands folder:
const { promisify } = require('util');
const readdir = promisify(require('fs').readdir);
client.commands = new Map();
client.on('ready', async () => {
readdir('./commands/', (error, files) => {
if (error) throw error;
files.forEach(file => {
if (!file.endsWith('.js')) return; // make sure the file is what you are looking for
try {
const properties = require(`./commands/${file}`);
client.commands.set(properties.help.name, properties);
} catch (err) {
throw err;
}
});
}
});
This basically defines a Map, extended from the client object called client.commands. This map will contain the command properties, which is used to run the command later. The readdir reads the directory of ./commands/ for any file (using the module fs), and tries to filter them so they are only javascript files (ending with .js), and then adds the commands to the map with its properties.
Later, on the message event, you'll want to test to see if the message content is the command that you have coded:
client.on('message', async (message) => {
if (!message.guild) return; // exit if the message does not have a guild
if (message.author.bot) return; // exit if the message author is a bot
// ... your database code to get the prefix ...
const args = message.content.slice(prefix.length).trim().split(/ +/g).call(Function.prototype.call, String.prototype.trim);
const command = args.shift().toLowerCase();
const cmd = client.commands.get(command);
if (!cmd) return; // the message is not a command we know of
cmd.run(client, message, args); // run the command with client object, message object and args array
});
This code does the basic checks, to make sure the bot is only responding to a user in a guild channel (you may also want to check if the message is from Discord: message.system).
After, it'll separate the content after the prefix into an array, splitting on a space, and then trimming every element of leading and trailing white space.
It'll then assign the first element of the args array to the constant command, to then be checked if that command exists in our map.
If it does, it'll run the command (apart of the module.exports), passing along the client object, message object, and the arguments array.
Finally, in a command file, such as foo.js, you'll need to have some important code to make sure the bot registers said the file is a command we want to run. This is:
module.exports.run = async (client, message, args) => {
// ... command logic
message.channel.send('Hello!');
};
module.exports.help = {
name: 'foo'
};
This is the basic layout of the command file the system is able to read. The first line exports the run process of the command, which is an async function. It also exports the help object, which includes the name of the command. It's best that this is the same as the file name since this name is what the command is responding to.
In my opinion, this is a better method than creating the class holding all the commands, but I'll keep an open mind!

Related

How to remove the command from a message sending ${message.content} Discord.js

I am working on a command where you type ?send it will then delete your message and send the message through the node.js bot but right now it sends the full message including the command How am I able to make it so that it will remove the prefix and command and just send what follows the command
My Code
module.exports = {
name: `send`,
description: "sends a message through the bot",
execute (client, message, args){
const channel = client.channels.cache.get('id');
const Crash = message.guild.roles.cache.find(r => r.name === "Crash");
if(message.member.roles.cache.has(Crash.id)) {
message.delete({timeout: 100})
message.channel.send(`${message.content}`);
} else {
message.channel.send(`You cant use this command`);
}
}
}
It looks like you're using a command handler that passes the args of the message command to the 3rd parameter of the execute function. I'm not sure how your command handler works but I assume args is an array of words in the message, not including the command or prefix. Try using the Array.join() function to join the args into a single string (with a space in between the words) and send that:
message.channel.send(`${args.join(" ")}`);

Dynamic Slash Command Options List via Database Query?

Background:
I am building a discord bot that operates as a Dungeons & Dragons DM of sorts. We want to store game data in a database and during the execution of certain commands, query data from said database for use in the game.
All of the connections between our Discord server, our VPS, and the VPS' backend are functional and we are now implementing slash commands since traditional ! commands are being removed from support in April.
We are running into problems making the slash commands though. We want to set them up to be as efficient as possible which means no hard-coded choices for options. We want to build those choice lists via data from the database.
The problem we are running into is that we can't figure out the proper way to implement the fetch to the database within the SlashCommandBuilder.
Here is what we currently have:
const {SlashCommandBuilder} = require('#discordjs/builders');
const fetch = require('node-fetch');
const {REST} = require('#discordjs/rest');
const test = require('../commonFunctions/test.js');
var options = async function getOptions(){
let x = await test.getClasses();
console.log(x);
return ['test','test2'];
}
module.exports = {
data: new SlashCommandBuilder()
.setName('get-test-data')
.setDescription('Return Class and Race data from database')
.addStringOption(option =>{
option.setName('class')
.setDescription('Select a class for your character')
.setRequired(true)
for(let op of options()){
//option.addChoice(op,op);
}
return option
}
),
async execute(interaction){
},
};
This code produces the following error when start the npm for our bot on our server:
options is not a function or its return value is not iterable
I thought that maybe the function wasn't properly defined, so I replaced the contents of it with just a simple array return and the npm started without errors and the values I had passed showed up in the server.
This leads me to think that the function call in the modules.exports block is immediatly attempting to get the return value of the function and as the function is async, it isn't yet ready and is either returning undefined or a promise or something else not iteratable.
Is there a proper way to implement the code as shown? Or is this way too complex for discord.js to handle?
Is there a proper way to implement the idea at all? Like creating a json object that contains the option data which is built and saved to a file at some point prior to this command being registered and then having the code above just pull in that file for the option choices?
Alright, I found a way. Ian Malcom would be proud (LMAO).
Here is what I had to do for those with a similar issues:
I had to basically re-write our entire application. It sucks, I know, but it works so who cares?
When you run your index file for your npm, make sure that you do the following things.
Note: you can structure this however you want, this is just how I set up my js files.
Setup a function that will setup the data you need, it needs to be an async function as does everything downstream from this point on relating to the creation and registration of the slash commands.
Create a js file to act as your application setup "module". "Module" because we're faking a real module by just using the module.exports method. No package.jsons needed.
In the setup file, you will need two requires. The first is a, as of yet, non-existent data manager file; we'll do that next. The second is a require for node:fs.
Create an async function in your setup file called setup and add it to your module.exports like so:
module.exports = { setup }
In your async setup function or in a function that it calls, make a call to the function in your still as of yet non-existent data manager file. Use await so that the application doesn't proceed until something is returned. Here is what mine looks like, note that I am writing my data to a file to read in later because of my use case, you may or may not have to do the same for yours:
async function setup(){
console.log('test');
//build option choice lists
let listsBuilt = await buildChoiceLists();
if (listsBuilt){
return true;
} else {
return false;
}
}
async function buildChoiceLists(){
let classListBuilt = await buildClassList();
return true;
}
async function buildClassList(){
let classData = await classDataManager.getClassData();
console.log(classData);
classList = classData;
await writeFiles();
return true;
}
async function writeFiles(){
fs.writeFileSync('./CommandData/classList.json', JSON.stringify(classList));
}
Before we finish off this file, if you want to store anything as a property in this file and then get it later on, you can do so. In order for the data to return properly though, you will need to define a getter function in your exports. Here is an example:
var classList;
module.exports={
getClassList: () => classList,
setup
};
So, with everything above you should have something that looks like this:
const classDataManager = require('./DataManagers/ClassData.js')
const fs = require('node:fs');
var classList;
async function setup(){
console.log('test');
//build option choice lists
let listsBuilt = await buildChoiceLists();
if (listsBuilt){
return true;
} else {
return false;
}
}
async function buildChoiceLists(){
let classListBuilt = await buildClassList();
return true;
}
async function buildClassList(){
let classData = await classDataManager.getClassData();
console.log(classData);
classList = classData;
await writeFiles();
return true;
}
async function writeFiles(){
fs.writeFileSync('./CommandData/classList.json', JSON.stringify(classList));
}
module.exports={
getClassList: () => classList,
setup
};
Next that pesky non-existent DataManager file. For mine, each data type will have its own, but you might want to just combine them all into a single .js file for yours.
Same with the folder name, I called mine DataManagers, if you're combining them all into one, you could just call the file DataManager and leave it in the same folder as your appSetup.js file.
For the data manager file all we really need is a function to get our data and then return it in the format we want it to be in. I am using node-fetch. If you are using some other module for data requests, write your code as needed.
Instead of explaining everything, here is the contents of my file, not much has to be explained here:
const fetch = require('node-fetch');
async function getClassData(){
return new Promise((resolve) => {
let data = "action=GetTestData";
fetch('http://xxx.xxx.xxx.xx/backend/characterHandler.php', {
method: 'post',
headers: { 'Content-Type':'application/x-www-form-urlencoded'},
body: data
}).then(response => {
response.json().then(res => {
let status = res.status;
let clsData = res.classes;
let rcData = res.races;
if (status == "Success"){
let text = '';
let classes = [];
let races = [];
if (Object.keys(clsData).length > 0){
for (let key of Object.keys(clsData)){
let cls = clsData[key];
classes.push({
"name": key,
"code": key.toLowerCase()
});
}
}
if (Object.keys(rcData).length > 0){
for (let key of Object.keys(rcData)){
let rc = rcData[key];
races.push({
"name": key,
"desc": rc.Desc
});
}
}
resolve(classes);
}
});
});
});
}
module.exports = {
getClassData
};
This file contacts our backend php and requests data from it. It queries the data then returns it. Then we format it into an JSON structure for use later on with option choices for the slash command.
Once all of your appSetup and data manager files are complete, we still need to create the commands and register them with the server. So, in your index file add something similar to the following:
async function getCommands(){
let cmds = await comCreator.appSetup();
console.log(cmds);
client.commands = cmds;
}
getCommands();
This should go at or near the top of your index.js file. Note that comCreator refers to a file we haven't created yet; you can name this require const whatever you wish. That's it for this file.
Now, the "comCreator" file. I named mine deploy-commands.js, but you can name it whatever. Once again, here is the full file contents. I will explain anything that needs to be explained after:
const {Collection} = require('discord.js');
const {REST} = require('#discordjs/rest');
const {Routes} = require('discord-api-types/v9');
const app = require('./appSetup.js');
const fs = require('node:fs');
const config = require('./config.json');
async function appSetup(){
console.log('test2');
let setupDone = await app.setup();
console.log(setupDone);
console.log(app.getClassList());
return new Promise((resolve) => {
const cmds = [];
const cmdFiles = fs.readdirSync('./commands').filter(f => f.endsWith('.js'));
for (let file of cmdFiles){
let cmd = require('./commands/' + file);
console.log(file + ' added to commands!');
cmds.push(cmd.data.toJSON());
}
const rest = new REST({version: '9'}).setToken(config.token);
rest.put(Routes.applicationGuildCommands(config.clientId, config.guildId), {body: cmds})
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
let commands = new Collection();
for (let file of cmdFiles){
let cmd = require('./commands/' + file);
commands.set(cmd.data.name, cmd);
}
resolve(commands);
});
}
module.exports = {
appSetup
};
Most of this is boiler plate for slash command creation though I did combine the creation and registering of the commands into the same process. As you can see, we are grabbing our command files, processing them into a collection, registering that collection, and then resolving the promise with that variable.
You might have noticed that property, was used to then set the client commands in the index.js file.
Config just contains your connection details for your discord server app.
Finally, how I accessed the data we wrote for the SlashCommandBuilder:
data: new SlashCommandBuilder()
.setName('get-test-data')
.setDescription('Return Class and Race data from database')
.addStringOption(option =>{
option.setName('class')
.setDescription('Select a class for your character')
.setRequired(true)
let ops = [];
let data = fs.readFileSync('./CommandData/classList.json','utf-8');
ops = JSON.parse(data);
console.log('test data class options: ' + ops);
for(let op of ops){
option.addChoice(op.name,op.code);
}
return option
}
),
Hopefully this helps someone in the future!

My fs.writeFile won't log anything into my JSON file?

I am creating a Discord.js Bot currently, and I am trying to create a prefix and have it log into the JSON file, however, using fs.writeFile, it will not log anything into the file, is there something I am doing wrong?
try {
//Checks User Permissions
if(!message.member.hasPermission("MANAGE_SERVER")) return;
if(!args[0]) return;
//Calls the prefixes.json file
let prefixes = require('../prefixes.json');
//Fetches the prefix they want to change
prefixes[message.guild.id] = {
prefixes: args[0]
};
//Logs the Prefix for the Guild
fs.writeFile("../prefixes.json", JSON.stringify(prefixes), (err) => {
if(err) console.log(err);
})
//Main Embed Code
let embed = new Discord.MessageEmbed()
.setAuthor('Prefix Changed!')
.setDescription(`The new prefix for ${message.guild.name} is set to \`${args[0]}\`!`)
.setTimestamp()
.setColor(colours.main)
message.channel.send(embed)
} catch(e) {
let embed = new Discord.MessageEmbed()
.setColor(colours.red)
.setDescription(`Error:\`\`\`${e.message}\`\`\``)
message.channel.send(embed)
}};
I think you want to use fs.writeFileSync(), it's just easier unless the async version is absolutely needed. If you are trying to perform an operation on that file after fs.writeFile() is called, it's done asynchronously, so you'd have to make sure the writeFile() is done before resuming any other operations relevant to that file.

My discord.js help command doesn't exactly work

First things first, my help command does work but not in the way I would like it to work.
My first issue is that the commands are being sent in separate messages which is kind of annoying when you have a lot of commands.
My second issue is that when the message is sent in an embed, it shows up like this:
Command
Description
Usage
Undefined
I tried multiple ways to get rid of 'Undefined'.
My code:
const fs = require("fs");
const Discord = require("discord.js");
module.exports.run = async(bot, message, args, con) => {
fs.readdir("./commands/", (err, files) => {
if(err) console.error(err);
let jsfiles = files.filter(f => f.split(".").pop() === "js");
if(jsfiles.length <= 0) {
console.log("No commands to load!");
return;
}
var namelist = "";
var desclist = "";
var usage = "";
let result = jsfiles((f, i) => {
let props = require(`./${f}`);
namelist = props.help.name;
desclist = props.help.description;
usage = props.help.usage;
// send help text
let helpembed = new Discord.RichEmbed()
.setTitle("Commands")
.setFooter("Please report any bugs to Vati#1662")
.setColor("RANDOM")
.addField(`**${namelist}** \n${desclist} \n${usage}`)
message.author.sendEmbed(helpembed);
});
})
}
module.exports.help = {
name: "help",
description: "shows all commands",
usage: "help"
}
When you use RichEmbed.addField() it expects at least two arguments: the title of the field and its value.
.addField(`**${namelist}** \n${desclist} \n${usage}`) // this has only the title argument
Try putting the three "sections" in three different fields.
.addField("Name:", namelist, true) // the 'true' means that they're inline fileds
.addField("Usage:", usage, true) // they will try to fit on the same line
.addField("Description:", desclist) // if there's no third argument, the default is 'false'
The commands are sent in different messages because you're running the whole code for every command, and not only adding the fields for every command. If you don't want to spend time on all this stuff, you can use the discord.js-commando library: it's a framework that deals with the commands and also handles errors, incomplete commands, and a lot of other stuff. If you want to check it out, you can find the docs here.

How to get console.log line numbers shown in Nodejs?

Got an old application, that prints out quite a lot of messages using console.log, but I just can not find in which files and lines console.log is called.
Is there a way to hook into the app and show file name and line numbers?
Having full stack trace for each call is a bit noisy. I've just improved the #noppa's solution to print only the initiator:
['log', 'warn', 'error'].forEach((methodName) => {
const originalMethod = console[methodName];
console[methodName] = (...args) => {
let initiator = 'unknown place';
try {
throw new Error();
} catch (e) {
if (typeof e.stack === 'string') {
let isFirst = true;
for (const line of e.stack.split('\n')) {
const matches = line.match(/^\s+at\s+(.*)/);
if (matches) {
if (!isFirst) { // first line - current function
// second line - caller (what we are looking for)
initiator = matches[1];
break;
}
isFirst = false;
}
}
}
}
originalMethod.apply(console, [...args, '\n', ` at ${initiator}`]);
};
});
It also patches other methods (useful for Nodejs, since warn and error don't come with a stack trace as in Chrome).
So your console would look something like:
Loading settings.json
at fs.readdirSync.filter.forEach (.../settings.js:21:13)
Server is running on http://localhost:3000 or http://127.0.0.1:3000
at Server.app.listen (.../index.js:67:11)
For a temporary hack to find the log statements that you want to get rid of, it's not too difficult to override console.log yourself.
var log = console.log;
console.log = function() {
log.apply(console, arguments);
// Print the stack trace
console.trace();
};
// Somewhere else...
function foo(){
console.log('Foobar');
}
foo();
That will print something like
Foobar
Trace
at Console.console.log (index.js:4:13)
at foo (index.js:10:13)
at Object.<anonymous> (index.js:12:1)
...
A lot of noise in there but the second line in the call stack, at foo (index.js:10:13), should point you to the right place.
All solutions to this question so far rely on splitting and matching the stack trace as a string, which will break in (the unlikely) case the format of that string is changed in the future. Inspired by this gist on GitHub and the other answers here, I want to provide my own solution:
'use strict';
const path = require('path');
['debug', 'log', 'warn', 'error'].forEach((methodName) => {
const originalLoggingMethod = console[methodName];
console[methodName] = (firstArgument, ...otherArguments) => {
const originalPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const callee = new Error().stack[1];
Error.prepareStackTrace = originalPrepareStackTrace;
const relativeFileName = path.relative(process.cwd(), callee.getFileName());
const prefix = `${relativeFileName}:${callee.getLineNumber()}:`;
if (typeof firstArgument === 'string') {
originalLoggingMethod(prefix + ' ' + firstArgument, ...otherArguments);
} else {
originalLoggingMethod(prefix, firstArgument, ...otherArguments);
}
};
});
// Tests:
console.log('%s %d', 'hi', 42);
console.log({ a: 'foo', b: 'bar'});
Unlike the other solutions, this script
outputs no additional lines and
handles string substitutions correctly.
You can color the prefix with chalk or color.js, but I didn't want to introduce dependencies for this here.
The above script uses the V8 API to customize stack traces. The callee is a CallSite object with the following methods in case you want to customize the prefix:
getThis: returns the value of this
getTypeName: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object’s [[Class]] internal property.
getFunction: returns the current function
getFunctionName: returns the name of the current function, typically its name property. If a name property is not available an attempt is made to infer a name from the function’s context.
getMethodName: returns the name of the property of this or one of its prototypes that holds the current function
getFileName: if this function was defined in a script returns the name of the script
getLineNumber: if this function was defined in a script returns the current line number
getColumnNumber: if this function was defined in a script returns the current column number
getEvalOrigin: if this function was created using a call to eval returns a string representing the location where eval was called
isToplevel: is this a top-level invocation, that is, is this the global object?
isEval: does this call take place in code defined by a call to eval?
isNative: is this call in native V8 code?
isConstructor: is this a constructor call?
isAsync: is this an async call (i.e. await or Promise.all())?
isPromiseAll: is this an async call to Promise.all()?
getPromiseIndex: returns the index of the promise element that was followed in Promise.all() for async stack traces, or null if the CallSite is not a Promise.all() call.
This answer is a cross-post of an answer I just gave to a similar question as more people might find this page.
I found Dmitry Druganov's answer really nice, but I tried it on Windows 10 (with Node 8.9.4) and it didn't work well. It was printing the full path, something like:
Loading settings.json
at fs.readdirSync.filter.forEach (D:\Users\Piyin\Projects\test\settings.js:21:13)
Server is running on http://localhost:3000 or http://127.0.0.1:3000
at Server.app.listen (D:\Users\Piyin\Projects\test\index.js:67:11)
So I took said answer and made these improvements (from my point of view):
Assume the important line of the stack trace is the third one (the first one is the word Error and the second one is where you place this script)
Remove the current script folder path (given by __dirname, which in my case is D:\Users\Piyin\Projects\test). Note: For this to work well, the script should be on the project's main Javascript
Remove the starting at
Place the file information before the actual log
Format the information as Class.method at path/to/file:line:column
Here it is:
['log','warn','error'].forEach((methodName) => {
const originalMethod = console[methodName];
console[methodName] = (...args) => {
try {
throw new Error();
} catch (error) {
originalMethod.apply(
console,
[
(
error
.stack // Grabs the stack trace
.split('\n')[2] // Grabs third line
.trim() // Removes spaces
.substring(3) // Removes three first characters ("at ")
.replace(__dirname, '') // Removes script folder path
.replace(/\s\(./, ' at ') // Removes first parentheses and replaces it with " at "
.replace(/\)/, '') // Removes last parentheses
),
'\n',
...args
]
);
}
};
});
And here's the new output:
fs.readdirSync.filter.forEach at settings.js:21:13
Loading settings.json
Server.app.listen at index.js:67:11
Server is running on http://localhost:3000 or http://127.0.0.1:3000
Here's the minified-by-hand code (240 bytes):
['log','warn','error'].forEach(a=>{let b=console[a];console[a]=(...c)=>{try{throw new Error}catch(d){b.apply(console,[d.stack.split('\n')[2].trim().substring(3).replace(__dirname,'').replace(/\s\(./,' at ').replace(/\)/,''),'\n',...c])}}});
Slightly modified version of noppa's answer, this version will output something like:
/file/in-which/console/is/called.js:75:23
The stuff you want to log.
This is clean and convenient (especially for use in VSCode - which will turn the file path into a link).
const { log } = console;
function proxiedLog(...args) {
const line = (((new Error('log'))
.stack.split('\n')[2] || '…')
.match(/\(([^)]+)\)/) || [, 'not found'])[1];
log.call(console, `${line}\n`, ...args);
}
console.info = proxiedLog;
console.log = proxiedLog;
// test
console.log('Hello!');
The snippet will only work well in a NodeJS environment…
Appends the line number to the end of the log
const stackTrace = function () {
let obj = {}
Error.captureStackTrace(obj, stackTrace)
return obj.stack
}
const getLine = function (stack) {
let matchResult = stack.match(/\(.*?\)|\s.+/g) || []
let arr = matchResult.map((it) => {
return it.split(' ').pop().replace(/\(|\)/g, '')
})
return arr[1] ?? ''
}
const log = function (...args) {
let stack = stackTrace() || ''
let matchResult = getLine(stack)
let line = matchResult
for (var i in arguments) {
if (typeof arguments[i] == 'object') {
// util.inspect(arguments[i], false, 2, false)
arguments[i] = JSON.stringify(arguments[i])
}
}
arguments[i] += ' ' + line
console.log.apply(console, arguments)
}
log("test")
Simple & exhaustive solution if you want to temporarily find the origin of logs:
{
const logOriginal = process.stdout.write
// #ts-ignore
const log = (msg) => logOriginal.call(process.stdout, msg + '\n')
;['stdout', 'stderr'].forEach((stdName) => {
// #ts-ignore
var methodOriginal = process[stdName].write
// #ts-ignore
process[stdName].write = function (...args) {
log('LOG:')
// #ts-ignore
methodOriginal.apply(process[stdName], args)
// #ts-ignore
log(new Error().stack.replace(/^Error/, 'LOGGED FROM:'))
}
})
Error.stackTraceLimit = Infinity
}
const showName = (name) => {
return
console.log(name)
}
showName(“Crush”)

Resources