party.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const { Document } = require('camo')
  2. const Character = require('./character')
  3. const tinycolor = require('tinycolor2')
  4. const chalk = require('chalk')
  5. // Just an organised party (read: team, group) of Characters.
  6. class Party extends Document {
  7. constructor() {
  8. super()
  9. this.schema({
  10. members: [Character],
  11. name: {type: String, default: 'Unnamed Party'},
  12. colorHue: {type: Number, min: 0, max: 1},
  13. discordRoleID: {type: String, required: false}, // Will be automatically generated
  14. })
  15. }
  16. addCharacter(character) {
  17. this.members.push(character)
  18. character.partyID = this
  19. }
  20. async getRole(guild) {
  21. // Create the role, if it doesn't exist already.
  22. if (!this.discordRoleID) {
  23. const role = await guild.createRole()
  24. await this.updateRole(role)
  25. this.discordRoleID = role.id
  26. }
  27. return guild.roles.get(this.discordRoleID)
  28. }
  29. async updateRole(role) {
  30. // Update party role details.
  31. await role.edit({
  32. name: 'Party: ' + this.name,
  33. color: tinycolor.fromRatio({h: this.colorHue, s: 0.6, v: 1.0}).toHexString()
  34. })
  35. }
  36. async assignRoles(guild) {
  37. const partyRole = await this.getRole(guild)
  38. await this.updateRole(partyRole)
  39. for (const character of this.members) {
  40. if (!character.discordID) {
  41. continue
  42. }
  43. const member = guild.members.get(character.discordID)
  44. member.addRole(partyRole)
  45. }
  46. }
  47. static of(characters) {
  48. const party = this.create({
  49. characters: [],
  50. colorHue: Math.random()
  51. })
  52. for (const character of characters) {
  53. party.addCharacter(character)
  54. }
  55. return party
  56. }
  57. static async cleanDeadRoles(guild, log) {
  58. const partyRoles = guild.roles.filter(role => role.name.startsWith('Party:')).array()
  59. for (const role of partyRoles) {
  60. const party = await this.findOne({discordRoleID: role.id})
  61. if (!party) {
  62. await role.delete()
  63. log.info(`Deleted unused party role ${chalk.blue(role.name)}`)
  64. }
  65. }
  66. }
  67. }
  68. module.exports = Party