fable.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. class FableCarousel < Carousel
  2. def self.sections
  3. {
  4. Emoji::FIRST => 'first',
  5. Emoji::LEFT => 'left',
  6. Emoji::RIGHT => 'right',
  7. Emoji::LAST => 'last'
  8. }
  9. end
  10. def self.update_embed(event, carousel)
  11. # Save reactions and determine section
  12. reactions = event.message.reactions
  13. section = sections.filter{ |k,v| reactions[k]&.count.to_i > 1 }.values.first
  14. # Close the embed if that is chosen
  15. return carousel.close(event) if reactions[Emoji::CROSS]&.count.to_i > 1
  16. # Fetch the corresponding emoji, and remove non-bot reactions
  17. emoji = sections.key(section)
  18. event.message.reacted_with(emoji).each do |r|
  19. event.message.delete_reaction(r.id, emoji) unless r.current_bot?
  20. end
  21. # Find next fable
  22. fable = next_fable(section, carousel)
  23. carousel.update(fable_id: fable.id)
  24. carousel.reload
  25. # Update to new fable
  26. BotResponse.new(
  27. carousel: carousel,
  28. embed: fable_embed(fable, event)
  29. )
  30. end
  31. def self.next_fable(section, carousel)
  32. # The list of fables in order, and the index of the current fable
  33. fables = Fable.order('id ASC')
  34. i = fables.map(&:id).index(carousel.fable_id)
  35. case section
  36. when 'first'
  37. fables.first
  38. when 'left'
  39. i == 0 ? fables.last : fables[i-1]
  40. when 'right'
  41. i == fables.length-1 ? fables.first : fables[i+1]
  42. when 'last'
  43. fables.last
  44. end
  45. end
  46. end