game.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env node
  2. const discord = require('discord.js')
  3. const config = require('./config')
  4. const db = require('./db')
  5. class Game {
  6. // Starts the game. Should only run once per process!
  7. async boot() {
  8. // Load the config file
  9. await config.load()
  10. // Connect to the database (nedb or mongodb)
  11. await db.connect()
  12. // Create the bot pool
  13. this.clientPool = await Promise.all(config.get('discord_bot_tokens').map(async token => {
  14. const client = new discord.Client()
  15. try {
  16. await client.login(token)
  17. } catch (err) {
  18. console.warn('Bot login failure (is the token correct?)')
  19. return null
  20. }
  21. if (client.guilds.find(g => g.id === config.get('discord_server_id'))) {
  22. console.log(`Bot ${client.user.tag} logged in successfully`)
  23. return client
  24. } else {
  25. console.warn('Bot not connected to configured Discord server - add it using the following URL:')
  26. console.warn(`https://discordapp.com/oauth2/authorize?&client_id=${client.user.id}&scope=bot&permissions=${0x00000008}&response_type=code`)
  27. return null
  28. }
  29. }).filter(promise => promise !== null))
  30. if (this.clientPool.length === 0) {
  31. throw 'No bots connected, cannot start'
  32. }
  33. // Add all players to the database (if they don't exist already)
  34. // This could take a while on large servers
  35. await Promise.all(this.guild.members.filter(m => !m.user.bot).map(async member => {
  36. const player = await db.Player.findOne({discordID: member.id})
  37. if (!player) {
  38. console.log(`Creating player data for new user ${member.user.tag}`)
  39. await db.Player.create({discordID: member.id}).save()
  40. }
  41. }))
  42. // TODO: other things
  43. }
  44. get guild() {
  45. return this.clientPool[0].guilds.find(g => g.id === config.get('discord_server_id'))
  46. }
  47. }
  48. // Let's go!!
  49. const game = new Game()
  50. game.boot()
  51. .then(() => console.log('Game started'))
  52. .catch(err => {
  53. // :(
  54. console.error('Unhandled error during boot:')
  55. console.error(err) // Human-friendly, handled errors are just strings
  56. process.exit(1)
  57. })