-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit e1f707b
Showing
13 changed files
with
6,397 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
{ | ||
"env": { | ||
"browser": true, | ||
"commonjs": true, | ||
"es2021": true | ||
}, | ||
"extends": "eslint:recommended", | ||
"parserOptions": { | ||
"ecmaVersion": "latest" | ||
}, | ||
"rules": { | ||
"no-undef": "warn", | ||
"no-unused-vars": "warn", | ||
"no-prototype-builtins": "off", | ||
"no-case-declarations": "off", | ||
"no-async-promise-executor": "off", | ||
"indent": [ | ||
"error", | ||
2, | ||
{ "SwitchCase": 1 } | ||
], | ||
"linebreak-style": [ | ||
"error", | ||
"unix" | ||
], | ||
"quotes": [ | ||
"error", | ||
"single" | ||
], | ||
"semi": [ | ||
"error", | ||
"always" | ||
] | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
.idea/ | ||
node_modules/ | ||
config.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,197 @@ | ||
const { ArchipelagoClient, ItemsHandlingFlags, SessionStatus } = require('archipelago.js'); | ||
const { User } = require('discord.js'); | ||
const { v4: uuid } = require('uuid'); | ||
|
||
class ArchipelagoInterface { | ||
version = { major: 0, minor: 3, build: 6 }; | ||
itemsHandling = ItemsHandlingFlags.REMOTE_ALL; | ||
|
||
|
||
/** | ||
* @param textChannel discord.js TextChannel | ||
* @param {string} host | ||
* @param {string} gameName | ||
* @param {string} slotName | ||
* @param {string|null} password optional | ||
*/ | ||
constructor(textChannel, host, gameName, slotName, password=null) { | ||
this.textChannel = textChannel; | ||
this.messageQueue = []; | ||
this.players = new Map(); | ||
this.APClient = new ArchipelagoClient(host); | ||
|
||
// Controls which messages should be printed to the channel | ||
this.showHints = true; | ||
this.showItems = true; | ||
this.showProgression = true; | ||
this.showChat = true; | ||
|
||
this.APClient.connect({ | ||
uuid: uuid(), | ||
game: gameName, | ||
name: slotName, | ||
version: this.version, | ||
items_handling: this.itemsHandling, | ||
}).then(() => { | ||
// Start handling queued messages | ||
this.queueTimeout = setTimeout(this.queueHandler, 5000); | ||
|
||
// Set up packet listeners | ||
this.APClient.addListener('print', this.printHandler); | ||
this.APClient.addListener('printJSON', this.printJSONHandler); | ||
|
||
// Inform the user AginahBot has connected to the game | ||
textChannel.send('Connection established.'); | ||
}).catch(async (err) => { | ||
await this.textChannel.send('A problem occurred while connecting to the AP server:\n' + | ||
`\`\`\`${JSON.stringify(err)}\`\`\``); | ||
}); | ||
} | ||
|
||
/** | ||
* Send queued messages to the TextChannel in batches of five or less | ||
* @returns {Promise<void>} | ||
*/ | ||
queueHandler = async () => { | ||
let messages = []; | ||
|
||
for (let message of this.messageQueue) { | ||
switch(message.type) { | ||
case 'hint': | ||
// Ignore hint messages if they should not be displayed | ||
if (!this.showHints) { continue; } | ||
|
||
// Replace player names with Discord User objects | ||
for (let alias of this.players.keys()) { | ||
if (message.content.includes(alias)) { | ||
message.content = message.content.replace(alias, this.players.get(alias)); | ||
} | ||
} | ||
break; | ||
|
||
case 'item': | ||
// Ignore item messages if they should not be displayed | ||
if (!this.showItems) { continue; } | ||
break; | ||
|
||
case 'progression': | ||
// Ignore progression messages if they should not be displayed | ||
if (!this.showProgression) { continue; } | ||
break; | ||
|
||
case 'chat': | ||
// Ignore chat messages if they should not be displayed | ||
if (!this.showChat) { continue; } | ||
break; | ||
|
||
default: | ||
console.warn(`Ignoring unknown message type: ${message.type}`); | ||
break; | ||
} | ||
|
||
messages.push(message.content); | ||
} | ||
|
||
// Clear the message queue | ||
this.messageQueue = []; | ||
|
||
// Send messages to TextChannel in batches of five, spaced two seconds apart to avoid rate limit | ||
while (messages.length > 0) { | ||
await this.textChannel.send(messages.splice(0, 5).join('\n')); | ||
await new Promise((resolve) => setTimeout(resolve, 2000)); | ||
} | ||
|
||
// Set timeout to run again after five seconds | ||
this.queueTimeout = setTimeout(this.queueHandler, 5000); | ||
}; | ||
|
||
/** | ||
* Listen for a print packet and add that message to the message queue | ||
* @param {Object} packet | ||
* @returns {Promise<void>} | ||
*/ | ||
printHandler = async (packet) => { | ||
this.messageQueue.push({ | ||
type: packet.text.includes('[Hint]') ? 'hint' : 'chat', | ||
content: packet.text, | ||
}); | ||
}; | ||
|
||
/** | ||
* Listen for a printJSON packet, convert it to a human-readable format, and add the message to the queue | ||
* @param {Object} packet | ||
* @returns {Promise<void>} | ||
*/ | ||
printJSONHandler = async (packet) => { | ||
let message = { type: 'chat', content: '', }; | ||
packet.data.forEach((part) => { | ||
// Plain text parts do not have a "type" property | ||
if (!part.hasOwnProperty('type') && part.hasOwnProperty('text')) { | ||
message.content += part.text; | ||
return; | ||
} | ||
|
||
switch(part.type){ | ||
case 'player_id': | ||
message.content += '**'+this.APClient.players.alias(parseInt(part.text, 10))+'**'; | ||
break; | ||
|
||
case 'item_id': | ||
message.content += '**'+this.APClient.items.name(parseInt(part.text, 10))+'**'; | ||
|
||
// Identify this message as containing an item | ||
if (message.type !== 'progression') { message.type = 'item'; } | ||
|
||
// Identify if this message contains a progression item | ||
if (part?.flags === 0b001) { message.type = 'progression'; } | ||
break; | ||
|
||
case 'location_id': | ||
message.content += '**'+this.APClient.locations.name(parseInt(part.text, 10))+'**'; | ||
break; | ||
|
||
case 'color': | ||
message.content += part.text; | ||
break; | ||
|
||
default: | ||
console.warn(`Ignoring unknown message type ${part.type} with text "${part.text}".`); | ||
return; | ||
} | ||
}); | ||
|
||
// Identify hint messages | ||
if (message.content.includes('[Hint]')) { message.type = 'hint'; } | ||
|
||
this.messageQueue.push(message); | ||
}; | ||
|
||
/** | ||
* Associate a Discord user with a specified alias | ||
* @param {string} alias | ||
* @param {User} discordUser | ||
* @returns {*} | ||
*/ | ||
setPlayer = (alias, discordUser) => this.players.set(alias, discordUser); | ||
|
||
/** | ||
* Disassociate a Discord user with a specified alias | ||
* @param alias | ||
* @returns {boolean} | ||
*/ | ||
unsetPlayer = (alias) => this.players.delete(alias); | ||
|
||
/** | ||
* Determine the status of the ArchipelagoClient object | ||
* @returns {SessionStatus} | ||
*/ | ||
getStatus = () => this.APClient.status; | ||
|
||
/** Close the WebSocket connection on the ArchipelagoClient object */ | ||
disconnect = () => { | ||
clearTimeout(this.queueTimeout); | ||
this.APClient.disconnect(); | ||
}; | ||
} | ||
|
||
module.exports = ArchipelagoInterface; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2020 LegendaryLinux | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
# ArchipelaBot | ||
A Discord bot designed to provide Archipelago-specific functionality. | ||
Find it in use at the [Archipelago Discord](https://discord.gg/B5pjMYy). | ||
|
||
## Current Features | ||
- Automatically delete ROM files, and compressed files containing them | ||
- Generate single-player or multiplayer games using the `generate` command | ||
- Connect to a running Archipelago server as a spectator and print messages to a Discord channel | ||
|
||
## Supported Games | ||
All games supported by the Multiworld Multi-Game Randomizer | ||
[Archipelago](https://github.com/ArchipelagoMW/Archipelago) | ||
are compatible and have full MultiWorld compatibility with each other. | ||
|
||
# Self-Hosting | ||
|
||
## Prerequisites | ||
- `node` and `npm` should be installed to run the bot and install dependencies | ||
- `unrar` should be installed on your system to process `.rar` files. | ||
- A MySQL 8 server should be installed, and a database available. | ||
|
||
## Configuration | ||
A `config.json` file is required to be present in the base directory of the repository. This file should contain | ||
your Discord bot's secret key. | ||
|
||
Example config: | ||
```json | ||
{ | ||
"token": "discord-bot-token" | ||
} | ||
``` | ||
|
||
If you intend to create your own bot on Discord using the code in this repository, your bot will need | ||
permissions granted by the permissions integer `277025508416`. | ||
|
||
The following permissions will be granted | ||
to ArchipelaBot: | ||
- View Channels | ||
- Send Messages | ||
- Send Messages in Threads | ||
- Embed Links | ||
- Attach Files | ||
- Add Reactions | ||
- Read Message History | ||
- Use Application Commands | ||
|
||
## Setup | ||
```shell script | ||
# Clone the repo | ||
git clone https://github.com/LegendaryLinux/ArchipelaBot | ||
|
||
# Enter its directory | ||
cd ArchipelaBot | ||
|
||
# Install required packages | ||
npm install | ||
|
||
# Set up your config.json file | ||
vim config.json | ||
|
||
# Run the bot | ||
node bot.js | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{ | ||
"presets": { | ||
"zelda3": {}, | ||
"factorio": {}, | ||
"zelda5": {}, | ||
"subnautica": {}, | ||
"minecraft": {}, | ||
"slay-the-spire": {}, | ||
"risk-of-rain-2": {}, | ||
"timespinner": {}, | ||
"metroid3": {} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
const { Client, Events, GatewayIntentBits, Partials } = require('discord.js'); | ||
const config = require('./config.json'); | ||
const { generalErrorHandler } = require('./errorHandlers'); | ||
const fs = require('fs'); | ||
|
||
// Catch all unhandled errors | ||
process.on('uncaughtException', (err) => generalErrorHandler(err)); | ||
process.on('unhandledRejection', (err) => generalErrorHandler(err)); | ||
|
||
const client = new Client({ | ||
partials: [ Partials.GuildMember, Partials.Message, Partials.Reaction ], | ||
intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, | ||
GatewayIntentBits.GuildMembers ], | ||
}); | ||
client.devMode = process.argv[2] && process.argv[2] === 'dev'; | ||
client.slashCommandCategories = []; | ||
|
||
client.tempData = { | ||
apInterfaces: new Map(), | ||
}; | ||
|
||
// Load slash command category files | ||
fs.readdirSync('./slashCommandCategories').filter((file) => file.endsWith('.js')).forEach((categoryFile) => { | ||
const slashCommandCategory = require(`./slashCommandCategories/${categoryFile}`); | ||
client.slashCommandCategories.push(slashCommandCategory); | ||
}); | ||
|
||
// Run the interactions through the interactionListeners | ||
client.on(Events.InteractionCreate, async(interaction) => { | ||
// Handle slash command interactions independently of other interactions | ||
if (interaction.isChatInputCommand()) { | ||
for (const listener of client.slashCommandCategories.commands) { | ||
if (listener.commandBuilder.name === interaction.commandName) { | ||
return listener(interaction); | ||
} | ||
} | ||
|
||
// If this slash command has no known listener, notify the user and log a warning | ||
console.warn(`Unknown slash command received: ${interaction.commandName}`); | ||
return interaction.reply('Unknown command.'); | ||
} | ||
}); | ||
|
||
// Use the general error handler to handle unexpected errors | ||
client.on(Events.Error, async(error) => generalErrorHandler(error)); | ||
|
||
client.once(Events.ClientReady, async () => { | ||
// Login and initial setup successful | ||
console.info(`Connected to Discord. Active in ${client.guilds.cache.size} guilds.`); | ||
}); | ||
|
||
client.login(config.token); |
Oops, something went wrong.