Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"bracketSpacing": true,
"singleQuote": true,
"tabWidth": 4,
"printWidth": 120
}
53 changes: 29 additions & 24 deletions config/config.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ loglevel: info
# Default: 2secs
cooldown: 2

# Bot status update interval
# How frequently should the bot update it's status (number of servers this bot is online on)
# Default: 10secs
statusinterval: 10

# OpenTTD server to Discord channel map
# Bot owners may use the 'newserver' command to create a default config to edit
#
Expand All @@ -32,32 +37,32 @@ cooldown: 2
# # Public address players use to connect to OpenTTD
# public: localhost:3979
channelMapping:
'123456789012345678':
name: OpenTTD Server
address: localhost
port: 3977
password: password
autoconnect: true
public: localhost:3979
'123456789012345678':
name: OpenTTD Server
address: localhost
port: 3977
password: password
autoconnect: true
public: localhost:3979

# Bot user permission roles
# IDs must be strings
# Role names are case sensitive
roles:
# User IDs to consider owners
ownerID:
- '123456789012345678'
# Guild roles to treat as admin
# Can be role ID's or full role names
admin:
- admin
- Admin
- '123456789012345678'
# Guild roles to treat as mods
# Can be role ID's or full role names
mod:
- mod
# Guild roles to treat as players
# OPTIONAL - leave blank to disable
# Can be role ID's or full role names
player:
# User IDs to consider owners
ownerID:
- '123456789012345678'
# Guild roles to treat as admin
# Can be role ID's or full role names
admin:
- admin
- Admin
- '123456789012345678'
# Guild roles to treat as mods
# Can be role ID's or full role names
mod:
- mod
# Guild roles to treat as players
# OPTIONAL - leave blank to disable
# Can be role ID's or full role names
player:
43 changes: 27 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ discordClient.botShutdown = function() {
channelOpenttd.disconnect();
}
});

// Wait until connection counter clears to disconect discord and end
const shutdownTimer = setInterval(() => {
if (!discordClient.openttdConnected.count) {
Expand All @@ -68,6 +68,9 @@ commandFiles.forEach(f => {
});
logger.info(`Loaded ${discordClient.commands.size} commands`);

// Load setStatus function
const setStatus = require('./modules/setStatus');

// Collection to hold coldown tracking for commands
const cooldowns = new Discord.Collection();

Expand All @@ -77,12 +80,11 @@ discordClient.once('ready', () => {
logger.debug(`Active guilds: ${discordClient.guilds.size}`);
// If we're not in any guilds prompt with invite link
if (!discordClient.guilds.size) {
discordClient.generateInvite()
.then(link => {
logger.info('Looks like this is the first run of the bot.');
logger.info('Please use the following link to add this bot to your server:');
logger.info(link);
});
discordClient.generateInvite().then(link => {
logger.info('Looks like this is the first run of the bot.');
logger.info('Please use the following link to add this bot to your server:');
logger.info(link);
});
}

// Object to help keep track of the number of OpenTTD connections active
Expand All @@ -101,6 +103,11 @@ discordClient.once('ready', () => {
}
};

// Update bot status to connected OpenTTD server amount
setInterval(() => {
setStatus(discordClient, 'WATCHING', discordClient.openttdConnected.counter);
}, discordClient.config.statusinterval * 10e2);

// Mapping for OpenTTD servers to channels
discordClient.channelMap = new Discord.Collection();
if (discordClient.config.channelMapping) {
Expand All @@ -112,7 +119,10 @@ discordClient.once('ready', () => {
logger.warn(`Unable to find Discord channel: ${channelID}`);
} else {
const config = discordClient.config.channelMapping[channelID];
discordClient.channelMap.set(channelID, new OpenTTD.Client(config, discordClient.channels.get(channelID)));
discordClient.channelMap.set(
channelID,
new OpenTTD.Client(config, discordClient.channels.get(channelID))
);
}
}
// Attempt to connect to each OpenTTD config
Expand Down Expand Up @@ -147,7 +157,9 @@ discordClient.on('message', message => {
logger.debug(`Command Name: ${commandName}, args: ${args}`);

// Check command is in cached command list
const command = discordClient.commands.get(commandName) || discordClient.commands.find(c => c.alias && c.alias.includes(commandName));
const command =
discordClient.commands.get(commandName) ||
discordClient.commands.find(c => c.alias && c.alias.includes(commandName));
if (!command) {
logger.debug(`Invalid command: ${commandName}`);
return;
Expand Down Expand Up @@ -192,12 +204,12 @@ discordClient.on('message', message => {
const timestamps = cooldowns.get(command.name);
// Get cooldown for this command
const cooldownAmount = (command.cooldown || discordClient.config.cooldown) * 1000;

// If the author has a cooldown
if (timestamps.has(message.author.id)) {
// Calculate the cooldown expiry
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;

// Check for expiry
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
Expand Down Expand Up @@ -234,10 +246,9 @@ logger.info(`OpenTTDiscord bot v${BOTVERSION}`);
logger.info('Connecting to Discord');

// Log in to discord
discordClient.login(discordClient.config.token)
.catch(error => {
logger.error(`An error occurred connecting to Discord; ${error}`);
});
discordClient.login(discordClient.config.token).catch(error => {
logger.error(`An error occurred connecting to Discord; ${error}`);
});

// Catch SIGINT and shutdown gracefully
process.on('SIGINT', () => {
Expand All @@ -248,4 +259,4 @@ process.on('message', msg => {
if (msg === 'shutdown') {
discordClient.botShutdown();
}
});
});
9 changes: 5 additions & 4 deletions modules/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ exports.load = () => {
if (!config.prefix) config.prefix = '!';
if (!config.loglevel) config.loglevel = 'info';
if (!config.cooldown) config.cooldown = 2;
if (!config.statusinterval) config.statusinterval = 10;
// Make sure some values at least exist
if (!config.roles.ownerID) config.roles.ownerID = [];
if (!config.roles.admin) config.roles.admin = [];
Expand All @@ -25,14 +26,14 @@ exports.load = () => {
};

// Saves the config back to YAML config file, returns success state
exports.save = (config) => {
exports.save = config => {
return new Promise((resolve, reject) => {
fs.writeFile(configFile, yaml.safeDump(config), (error) => {
fs.writeFile(configFile, yaml.safeDump(config), error => {
if (error) {
return reject (error);
return reject(error);
} else {
resolve('OK');
}
});
});
};
};
17 changes: 17 additions & 0 deletions modules/setStatus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const logger = require('./logger');

const setStatus = (discordClient, activityType = 'WATCHING', activeServerAmount) => {
const newActivityContent = `${activeServerAmount} Servers!`;
discordClient.user
.setActivity(newActivityContent, {
type: activityType
})
.then(() => {
logger.info(`Changed activity to 'Watching ${newActivityContent}'`);
})
.catch(reason => {
logger.error(`Couldn't change bot activity because of the reason: ${reason}`);
});
};

module.exports = setStatus;