sxcybot

Discord bot for OSRS based channels
git clone git://git.wimdupont.com/sxcybot.git
Log | Files | Refs | README | LICENSE

commit 5e86942bde5a0eaa01d6fa09a70d368839ef1c7c
parent f09fc3f1205e13455db62affeca7fc46ae6130fd
Author: Wim Dupont <wim@wimdupont.com>
Date:   Sat,  1 Apr 2023 17:46:58 +0200

add discordIds to pvmRoleUser

Diffstat:
Mpom.xml | 4++--
Dsrc/main/java/com/sxcy/sxcybot/SxcyBotApplication.java | 101-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/client/ClientErrorHandler.java | 27---------------------------
Dsrc/main/java/com/sxcy/sxcybot/client/GrandExchangeClient.java | 43-------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/client/HiScoreClient.java | 94-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/config/AppConfig.java | 15---------------
Dsrc/main/java/com/sxcy/sxcybot/config/PersistenceConfig.java | 23-----------------------
Dsrc/main/java/com/sxcy/sxcybot/enums/Command.java | 46----------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/enums/OsrsCombatStat.java | 17-----------------
Dsrc/main/java/com/sxcy/sxcybot/enums/PvmRole.java | 14--------------
Dsrc/main/java/com/sxcy/sxcybot/exceptions/EntityNotFoundException.java | 8--------
Dsrc/main/java/com/sxcy/sxcybot/exceptions/InsufficientPrivilegesException.java | 10----------
Dsrc/main/java/com/sxcy/sxcybot/listeners/AdminCommandListener.java | 124-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/CommandListener.java | 131-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/EventWaiterUtil.java | 36------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/GuildMemberEventListener.java | 45---------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/Listener.java | 7-------
Dsrc/main/java/com/sxcy/sxcybot/listeners/PollReactionListener.java | 111-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/PrivateListener.java | 9---------
Dsrc/main/java/com/sxcy/sxcybot/listeners/TimeOutRunner.java | 28----------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/BanlistListener.java | 57---------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/EditBanlistListener.java | 54------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/EditPvmListener.java | 54------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/EditRoleListener.java | 55-------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/EditRuleListener.java | 54------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/RoleAssignListener.java | 100-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/banlist/AddBanlistUserListener.java | 47-----------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/banlist/DeleteBanlistUserListener.java | 41-----------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/banlist/UpdateBanlistUserListener.java | 59-----------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/AddPvmListener.java | 77-----------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java | 47-----------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java | 80-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/role/AddRoleListener.java | 56--------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/role/DeleteRoleListener.java | 53-----------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/role/UpdateRoleListener.java | 55-------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/rule/AddRuleListener.java | 40----------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/rule/DeleteRuleListener.java | 51---------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/admin/rule/UpdateRuleListener.java | 51---------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/BB8Listener.java | 25-------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/CombatStatsListener.java | 51---------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/CustomPollListener.java | 51---------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/EventListener.java | 58----------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/ForumListener.java | 31-------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/HelpListener.java | 35-----------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/HiscoreBossListener.java | 50--------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/KillCountListener.java | 53-----------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/PingListener.java | 19-------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/PollListener.java | 66------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/PriceListener.java | 43-------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/PvmListListener.java | 43-------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/PvmRoleCheckListener.java | 33---------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/PvmRolePollListener.java | 33---------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/RuleListener.java | 45---------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/RulesListener.java | 41-----------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/listeners/member/StatsListener.java | 31-------------------------------
Dsrc/main/java/com/sxcy/sxcybot/model/CombatDto.java | 130-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/model/EditListenerDto.java | 93-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/model/HiScoreBuilder.java | 11-----------
Dsrc/main/java/com/sxcy/sxcybot/model/OsrsBossKc.java | 56--------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/model/OsrsItem.java | 64----------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/model/OsrsStat.java | 65-----------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/ChannelDetailRepository.java | 9---------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/GuildEventDmerRepository.java | 9---------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/GuildRoleRepository.java | 18------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/PollRepository.java | 13-------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/RuleRepository.java | 14--------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/UserRepository.java | 16----------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/dao/ChannelDetail.java | 158-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/dao/Event.java | 85-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/dao/GuildEventDmer.java | 75---------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/dao/GuildRole.java | 109-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/dao/Poll.java | 118-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/dao/Rule.java | 93-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/dao/User.java | 185-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/PvmKcSnapshotRepository.java | 14--------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java | 13-------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmKcSnapshot.java | 148-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java | 169-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmUserKc.java | 184-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/osrs/OsrsHiscoreBossRepository.java | 13-------------
Dsrc/main/java/com/sxcy/sxcybot/repository/osrs/OsrsHiscoreStatRepository.java | 9---------
Dsrc/main/java/com/sxcy/sxcybot/repository/osrs/dao/OsrsHiscoreBoss.java | 126-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/repository/osrs/dao/OsrsHiscoreStat.java | 93-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/CleanupScheduler.java | 62--------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/OsrsMonitoringService.java | 103-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/PvMRoleResolver.java | 75---------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/ChannelDetailService.java | 34----------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/GuildEventDmerService.java | 23-----------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/GuildRoleService.java | 45---------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/PollService.java | 36------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/RuleService.java | 37-------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/UserService.java | 38--------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmKcSnapshotService.java | 36------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java | 92-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleSnapshotComparatorService.java | 99-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleUserService.java | 39---------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/osrs/CombatCalculatorService.java | 29-----------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/osrs/OsrsHiscoreBossService.java | 30------------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/osrs/OsrsHiscoreStatService.java | 24------------------------
Dsrc/main/java/com/sxcy/sxcybot/services/osrs/StatMessageSender.java | 49-------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/util/Constants.java | 38--------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/util/CustomPollFiller.java | 80-------------------------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/util/DiscordMemberFinderUtil.java | 50--------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/util/EditListenerUtil.java | 42------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/util/JdaUtil.java | 37-------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/util/NumberFormatter.java | 15---------------
Dsrc/main/java/com/sxcy/sxcybot/util/ReleaseNotesUtil.java | 65-----------------------------------------------------------------
Dsrc/main/java/com/sxcy/sxcybot/util/SpringSecurityAuditorAware.java | 21---------------------
Asrc/main/java/com/wimdupont/sxcybot/SxcyBotApplication.java | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/client/ClientErrorHandler.java | 27+++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/client/GrandExchangeClient.java | 43+++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/client/HiScoreClient.java | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/config/AppConfig.java | 15+++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/config/PersistenceConfig.java | 23+++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/enums/Command.java | 46++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/enums/OsrsCombatStat.java | 17+++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/enums/PvmRole.java | 14++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/exceptions/EntityNotFoundException.java | 8++++++++
Asrc/main/java/com/wimdupont/sxcybot/exceptions/InsufficientPrivilegesException.java | 10++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/AdminCommandListener.java | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/CommandListener.java | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/EventWaiterUtil.java | 36++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/GuildMemberEventListener.java | 45+++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/Listener.java | 7+++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/PollReactionListener.java | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/PrivateListener.java | 9+++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/TimeOutRunner.java | 28++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/BanlistListener.java | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/EditBanlistListener.java | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/EditPvmListener.java | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/EditRoleListener.java | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/EditRuleListener.java | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/RoleAssignListener.java | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/AddBanlistUserListener.java | 47+++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/DeleteBanlistUserListener.java | 41+++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/UpdateBanlistUserListener.java | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/AddPvmListener.java | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java | 47+++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/role/AddRoleListener.java | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/role/DeleteRoleListener.java | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/role/UpdateRoleListener.java | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/rule/AddRuleListener.java | 40++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/rule/DeleteRuleListener.java | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/admin/rule/UpdateRuleListener.java | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/BB8Listener.java | 23+++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/CombatStatsListener.java | 44++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/CustomPollListener.java | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/EventListener.java | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/ForumListener.java | 31+++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/HelpListener.java | 35+++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/HiscoreBossListener.java | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/KillCountListener.java | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/PingListener.java | 19+++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/PollListener.java | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/PriceListener.java | 43+++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/PvmListListener.java | 41+++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/PvmRoleCheckListener.java | 33+++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/PvmRolePollListener.java | 33+++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/RuleListener.java | 45+++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/RulesListener.java | 41+++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/listeners/member/StatsListener.java | 31+++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/model/CombatDto.java | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/model/EditListenerDto.java | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/model/HiScoreBuilder.java | 11+++++++++++
Asrc/main/java/com/wimdupont/sxcybot/model/OsrsBossKc.java | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/model/OsrsItem.java | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/model/OsrsStat.java | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/ChannelDetailRepository.java | 9+++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/GuildEventDmerRepository.java | 9+++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/GuildRoleRepository.java | 18++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/PollRepository.java | 13+++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/RuleRepository.java | 14++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/UserRepository.java | 16++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/dao/ChannelDetail.java | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/dao/Event.java | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/dao/GuildEventDmer.java | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/dao/GuildRole.java | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/dao/Poll.java | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/dao/Rule.java | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/dao/User.java | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmKcSnapshotRepository.java | 14++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java | 14++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmKcSnapshot.java | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmUserKc.java | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/osrs/OsrsHiscoreBossRepository.java | 13+++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/osrs/OsrsHiscoreStatRepository.java | 9+++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/osrs/dao/OsrsHiscoreBoss.java | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/repository/osrs/dao/OsrsHiscoreStat.java | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/CleanupScheduler.java | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/OsrsMonitoringService.java | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/PvMRoleResolver.java | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/ChannelDetailService.java | 34++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/GuildEventDmerService.java | 23+++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/GuildRoleService.java | 45+++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/PollService.java | 36++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/RuleService.java | 37+++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/UserService.java | 38++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmKcSnapshotService.java | 36++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleSnapshotComparatorService.java | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleUserService.java | 39+++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/osrs/CombatCalculatorService.java | 29+++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/osrs/OsrsHiscoreBossService.java | 30++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/osrs/OsrsHiscoreStatService.java | 24++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/services/osrs/StatMessageSender.java | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/Constants.java | 38++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/CustomPollFiller.java | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/DiscordMemberFinderUtil.java | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/EditListenerUtil.java | 42++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/JdaUtil.java | 37+++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/NumberFormatter.java | 15+++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/ReleaseNotesUtil.java | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/java/com/wimdupont/sxcybot/util/SpringSecurityAuditorAware.java | 21+++++++++++++++++++++
Asrc/main/resources/db/migration/V1_11__add_discordid_to_pvmrole_user.sql | 1+
Msrc/main/resources/releasenotes.csv | 4++--
Dsrc/test/java/com/sxcy/sxcybot/SxcyBotApplicationTests.java | 17-----------------
Dsrc/test/java/com/sxcy/sxcybot/client/GrandExchangeClientTest.java | 49-------------------------------------------------
Dsrc/test/java/com/sxcy/sxcybot/client/HiScoreClientTest.java | 112-------------------------------------------------------------------------------
Asrc/test/java/com/wimdupont/sxcybot/SxcyBotApplicationTests.java | 17+++++++++++++++++
Asrc/test/java/com/wimdupont/sxcybot/client/GrandExchangeClientTest.java | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/test/java/com/wimdupont/sxcybot/client/HiScoreClientTest.java | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
223 files changed, 6144 insertions(+), 6099 deletions(-)

diff --git a/pom.xml b/pom.xml @@ -8,11 +8,11 @@ <version>3.0.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> - <groupId>com.sxcy</groupId> + <groupId>com.wimdupont</groupId> <artifactId>sxcybot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sxcybot</name> - <description>Sxcy's OSRS oriented Discord Bot</description> + <description>OSRS oriented Discord Bot</description> <properties> <java.version>17</java.version> diff --git a/src/main/java/com/sxcy/sxcybot/SxcyBotApplication.java b/src/main/java/com/sxcy/sxcybot/SxcyBotApplication.java @@ -1,101 +0,0 @@ -package com.sxcy.sxcybot; - -import com.sxcy.sxcybot.enums.Command; -import com.sxcy.sxcybot.listeners.AdminCommandListener; -import com.sxcy.sxcybot.listeners.CommandListener; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.GuildMemberEventListener; -import com.sxcy.sxcybot.listeners.PollReactionListener; -import com.sxcy.sxcybot.services.PvMRoleResolver; -import com.sxcy.sxcybot.services.guild.ChannelDetailService; -import com.sxcy.sxcybot.util.Constants.Commands; -import com.sxcy.sxcybot.util.ReleaseNotesUtil; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.JDABuilder; -import net.dv8tion.jda.api.entities.Activity; -import net.dv8tion.jda.api.requests.GatewayIntent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; - -import javax.security.auth.login.LoginException; -import java.util.Arrays; - -@SpringBootApplication -@EnableScheduling -@ComponentScan -public class SxcyBotApplication implements CommandLineRunner { - - private static final Logger LOGGER = LoggerFactory.getLogger(SxcyBotApplication.class); - private final CommandListener commandListener; - private final AdminCommandListener adminCommandListener; - private final EventWaiterUtil eventWaiterUtil; - private final PollReactionListener pollReactionListener; - private final GuildMemberEventListener guildMemberEventListener; - private final ReleaseNotesUtil releaseNotesUtil; - private final ChannelDetailService channelDetailService; - private final PvMRoleResolver pvMRoleResolver; - private final String token; - - public SxcyBotApplication(CommandListener commandListener, - AdminCommandListener adminCommandListener, - EventWaiterUtil eventWaiterUtil, - PollReactionListener pollReactionListener, - GuildMemberEventListener guildMemberEventListener, - ReleaseNotesUtil releaseNotesUtil, - ChannelDetailService channelDetailService, - PvMRoleResolver pvMRoleResolver, - @Value("${discord.bot.token}") String token) { - this.commandListener = commandListener; - this.adminCommandListener = adminCommandListener; - this.eventWaiterUtil = eventWaiterUtil; - this.pollReactionListener = pollReactionListener; - this.guildMemberEventListener = guildMemberEventListener; - this.releaseNotesUtil = releaseNotesUtil; - this.channelDetailService = channelDetailService; - this.pvMRoleResolver = pvMRoleResolver; - this.token = token; - } - - public static void main(String[] args) { - SpringApplication.run(SxcyBotApplication.class, args); - } - - @Override - public void run(String[] args) throws LoginException { - LOGGER.debug("Jda to be created"); - JDA jda = JDABuilder.createLight(token, - GatewayIntent.GUILD_MESSAGES, - GatewayIntent.DIRECT_MESSAGES, - GatewayIntent.GUILD_MESSAGE_REACTIONS, - GatewayIntent.GUILD_MEMBERS, - GatewayIntent.GUILD_BANS - ) - .addEventListeners(commandListener, adminCommandListener, eventWaiterUtil, guildMemberEventListener, pollReactionListener) - .setActivity(Activity.listening(Commands.COMMAND_PREFIX + Command.HELP.name().toLowerCase())) - .build(); - try { - LOGGER.debug("Awaiting jda " + jda); - jda.awaitReady(); - LOGGER.debug("Jda " + jda + " ready"); - channelDetailService.setJda(jda); - processArgs(jda, args); - } catch (InterruptedException e) { - LOGGER.error(e.getMessage(), e); - } - } - - private void processArgs(JDA jda, String... args) { - if (args.length > 0) { - if (Arrays.stream(args).anyMatch("notes"::equalsIgnoreCase)) - releaseNotesUtil.showReleaseNotes(jda); - if (Arrays.stream(args).anyMatch("snap"::equalsIgnoreCase)) - pvMRoleResolver.resolvePvMRoles(); - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/client/ClientErrorHandler.java b/src/main/java/com/sxcy/sxcybot/client/ClientErrorHandler.java @@ -1,27 +0,0 @@ -package com.sxcy.sxcybot.client; - -import net.dv8tion.jda.api.entities.MessageChannel; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.client.DefaultResponseErrorHandler; - -import java.io.IOException; - -public class ClientErrorHandler extends DefaultResponseErrorHandler { - - private final MessageChannel channel; - - public ClientErrorHandler(MessageChannel channel) { - this.channel = channel; - } - - @Override - public void handleError(ClientHttpResponse response) throws IOException { - String errorMsg = String.format("No results found. (%s)", response.getStatusText()); - if (channel != null) { - channel.sendMessage(errorMsg).queue(); - } else { - throw new RuntimeException(errorMsg); - } - } - -} diff --git a/src/main/java/com/sxcy/sxcybot/client/GrandExchangeClient.java b/src/main/java/com/sxcy/sxcybot/client/GrandExchangeClient.java @@ -1,43 +0,0 @@ -package com.sxcy.sxcybot.client; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.model.OsrsItem; -import com.sxcy.sxcybot.util.NumberFormatter; -import net.dv8tion.jda.api.entities.MessageChannel; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -import java.time.Duration; -import java.util.Map; - -@Component -public class GrandExchangeClient { - private static final String URL = "https://api.weirdgloop.org/exchange/history/osrs/latest?name=%s&lang=en"; - - private final ObjectMapper objectMapper; - - public GrandExchangeClient(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } - - @SuppressWarnings("unchecked") - public String getPrice(String itemName, MessageChannel channel) throws EntityNotFoundException { - RestTemplate restTemplate = new RestTemplateBuilder() - .errorHandler(new ClientErrorHandler(channel)) - .setReadTimeout(Duration.ofSeconds(30)) - .build(); - Object result = restTemplate.getForEntity(String.format(URL, itemName), Object.class).getBody(); - if (result != null) { - try { - return NumberFormatter.format(objectMapper - .convertValue(((Map<String, Object>) result).values().iterator().next(), OsrsItem.class).price()); - } catch (IllegalArgumentException e) { - throw new EntityNotFoundException(String.format("Item with name %s not found.", itemName)); - } - } else { - throw new EntityNotFoundException(String.format("Item with name %s not found.", itemName)); - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/client/HiScoreClient.java b/src/main/java/com/sxcy/sxcybot/client/HiScoreClient.java @@ -1,94 +0,0 @@ -package com.sxcy.sxcybot.client; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.model.HiScoreBuilder; -import com.sxcy.sxcybot.model.OsrsBossKc; -import com.sxcy.sxcybot.model.OsrsStat; -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreStat; -import com.sxcy.sxcybot.services.osrs.OsrsHiscoreBossService; -import com.sxcy.sxcybot.services.osrs.OsrsHiscoreStatService; -import com.sxcy.sxcybot.util.NumberFormatter; -import net.dv8tion.jda.api.entities.MessageChannel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -@Component -public class HiScoreClient { - - private static final String URL = "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=%s"; - private static final Logger LOGGER = LoggerFactory.getLogger(HiScoreClient.class); - - private static final int STATS_START = 0; - private static final int STATS_END = 23; - private static final int BOSS_START = 38; - private static final int BOSS_END = 88; - - private final OsrsHiscoreBossService osrsHiscoreBossService; - private final OsrsHiscoreStatService osrsHiscoreStatService; - - public HiScoreClient(OsrsHiscoreBossService osrsHiscoreBossService, - OsrsHiscoreStatService osrsHiscoreStatService) { - this.osrsHiscoreBossService = osrsHiscoreBossService; - this.osrsHiscoreStatService = osrsHiscoreStatService; - } - - public Optional<List<OsrsStat>> getHiScoreStats(String playername, MessageChannel channel) { - List<OsrsHiscoreStat> hiscoreStats = osrsHiscoreStatService.findAll(); - return getHiScores(playername, channel, (osrsStat, hiScoreStatValues, i) -> OsrsStat.Builder.newBuilder() - .name(hiscoreStats.stream().filter(f -> f.getOrderValue() == i).findFirst().orElseThrow(() - -> new EntityNotFoundException(String.format("OsrsStatName for order %s not found!", i))) - .getName()) - .rank(NumberFormatter.format(hiScoreStatValues.get(0))) - .level(hiScoreStatValues.get(1)) - .experience(NumberFormatter.format(hiScoreStatValues.get(2))) - .build(), STATS_START, STATS_END); - } - - public Optional<List<OsrsBossKc>> getHiScoreBossKc(String playername, MessageChannel channel) { - List<OsrsHiscoreBoss> hiscoreBosses = osrsHiscoreBossService.findAll(); - return getHiScores(playername, channel, (osrsKc, hiScoreKcValues, i) -> OsrsBossKc.Builder.newBuilder() - .name(hiscoreBosses.stream().filter(f -> f.getOrderValue() == i).findFirst().orElseThrow(() - -> new EntityNotFoundException(String.format("OsrsBoss for order %s not found!", i))) - .getName()) - .rank(hiScoreKcValues.get(0)) - .kc(hiScoreKcValues.get(1)) - .build(), BOSS_START, BOSS_END); - } - - private <T> Optional<List<T>> getHiScores(String playername, MessageChannel channel, HiScoreBuilder<T> hiScoreBuilder, int fromIndex, int toIndex) { - List<T> hiScoreList = new ArrayList<>(); - RestTemplate restTemplate = new RestTemplateBuilder() - .errorHandler(new ClientErrorHandler(channel)) - .setReadTimeout(Duration.ofSeconds(30)) - .build(); - String result = restTemplate.getForObject(String.format(URL, playername), String.class); - if (result != null) { - int i = fromIndex; - List<String> hiScores = Arrays.stream(result.split("\n")).toList(); - try { - for (String osrsHiScoresStats : hiScores.subList(fromIndex, toIndex + 1)) { - List<String> hiScoreStatValues = Arrays.stream(osrsHiScoresStats.split(",")).toList(); - try { - hiScoreList.add(hiScoreBuilder.accept(osrsHiScoresStats, hiScoreStatValues, i)); - } catch (EntityNotFoundException e) { - LOGGER.error(e.getMessage(), e); - } - i++; - } - } catch (RuntimeException e) { - return Optional.empty(); - } - } - return Optional.of(hiScoreList); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/config/AppConfig.java b/src/main/java/com/sxcy/sxcybot/config/AppConfig.java @@ -1,15 +0,0 @@ -package com.sxcy.sxcybot.config; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -@SuppressWarnings("unused") -public class AppConfig { - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/config/PersistenceConfig.java b/src/main/java/com/sxcy/sxcybot/config/PersistenceConfig.java @@ -1,23 +0,0 @@ -package com.sxcy.sxcybot.config; - -import com.sxcy.sxcybot.util.SpringSecurityAuditorAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.domain.AuditorAware; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; - -@Configuration -@EnableJpaAuditing(auditorAwareRef = "auditorProvider") -public class PersistenceConfig { - - private final SpringSecurityAuditorAware springSecurityAuditorAware; - - public PersistenceConfig(SpringSecurityAuditorAware springSecurityAuditorAware) { - this.springSecurityAuditorAware = springSecurityAuditorAware; - } - - @Bean - public AuditorAware<String> auditorProvider() { - return springSecurityAuditorAware; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/enums/Command.java b/src/main/java/com/sxcy/sxcybot/enums/Command.java @@ -1,46 +0,0 @@ -package com.sxcy.sxcybot.enums; - -public enum Command { - - FORUM("Get forum link - BUMP IT UP!"), - PING("Get time in ms for bot to respond."), - RULE("Show rule by using command with rule number, separated by space."), - RULES("Show list of all the rules."), - // EVENT("Create an event."), - POLL("Start a poll with default options (Accept, Deny, Unsure), separate command by title with space."), - CPOLL("Start a custom poll - choose your own poll options and reaction emoji's, separate command by title with space."), - PVMPOLL("Poll current standings of the PvM Role competition."), - PVMCHECK("Check if PvM competitors can be found."), - HELP("Show all commands with description."), - - - //-----OSRS----- - STATS("Check HiScores for all stats, separate command by playername with space."), - CBSTATS("Check HiScores for combat stats, separate command by playername with space."), - KC("Check HiScores for all kc's, separate command by playername with space."), - PRICE("Check the GE for the latest price of an item, separate command by name of item with space."), - PVMLIST("Show list of PvM Role competitors."), - BOSSLIST("Shows list of all hiscore bosses with their PvM Role point multipliers."); - - public enum Admin { - - EDITRULE("Add/Edit/Delete record of rulelist."), - EDITBANLIST("Add/Edit/Delete record of banlist."), - BANLIST("Show list of banned users."), - ROLE("Add/remove a role to/from a member."), - EDITROLE("Add/Delete record of roles."), - EDITPVM("Add/Edit/Delete record of the PvM Role competition"); - - public final String description; - - Admin(String description) { - this.description = description; - } - } - - public final String description; - - Command(String description) { - this.description = description; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/enums/OsrsCombatStat.java b/src/main/java/com/sxcy/sxcybot/enums/OsrsCombatStat.java @@ -1,17 +0,0 @@ -package com.sxcy.sxcybot.enums; - -public enum OsrsCombatStat { - ATTACK("Attack"), - DEFENCE("Defence"), - HITPOINTS("Hitpoints"), - MAGIC("Magic"), - PRAYER("Prayer"), - RANGED("Ranged"), - STRENGTH("Strength"); - - public final String value; - - OsrsCombatStat(String value) { - this.value = value; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/enums/PvmRole.java b/src/main/java/com/sxcy/sxcybot/enums/PvmRole.java @@ -1,14 +0,0 @@ -package com.sxcy.sxcybot.enums; - -public enum PvmRole { - UNUSED(0), - GENERAL(1), - RAIDS(2), - WILDERNESS(3); - - public final int value; - - PvmRole(int value) { - this.value = value; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/exceptions/EntityNotFoundException.java b/src/main/java/com/sxcy/sxcybot/exceptions/EntityNotFoundException.java @@ -1,8 +0,0 @@ -package com.sxcy.sxcybot.exceptions; - -public class EntityNotFoundException extends Exception { - - public EntityNotFoundException(String msg) { - super(msg); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/exceptions/InsufficientPrivilegesException.java b/src/main/java/com/sxcy/sxcybot/exceptions/InsufficientPrivilegesException.java @@ -1,10 +0,0 @@ -package com.sxcy.sxcybot.exceptions; - -import java.util.List; - -public class InsufficientPrivilegesException extends Exception { - - public InsufficientPrivilegesException(List<String> rolelist) { - super(String.format("Only following ranks can execute this command: %s", rolelist)); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/AdminCommandListener.java b/src/main/java/com/sxcy/sxcybot/listeners/AdminCommandListener.java @@ -1,124 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import com.sxcy.sxcybot.enums.Command; -import com.sxcy.sxcybot.enums.Command.Admin; -import com.sxcy.sxcybot.exceptions.InsufficientPrivilegesException; -import com.sxcy.sxcybot.listeners.admin.BanlistListener; -import com.sxcy.sxcybot.listeners.admin.EditBanlistListener; -import com.sxcy.sxcybot.listeners.admin.EditPvmListener; -import com.sxcy.sxcybot.listeners.admin.EditRoleListener; -import com.sxcy.sxcybot.listeners.admin.EditRuleListener; -import com.sxcy.sxcybot.listeners.admin.RoleAssignListener; -import com.sxcy.sxcybot.repository.guild.dao.GuildRole; -import com.sxcy.sxcybot.services.guild.GuildRoleService; -import com.sxcy.sxcybot.util.Constants.Commands; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Role; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.springframework.stereotype.Component; - -import javax.annotation.Nonnull; -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.stream.Stream; - -@Component -public class AdminCommandListener extends ListenerAdapter { - - private static final int GOD = 0; - private static final int ADMIN_ROLE = 1; - private static final int SUB_ADMIN = 5; - private static final int STAFF_ROLE = 10; - - private final EditRuleListener editRuleListener; - private final EditBanlistListener editBanlistListener; - private final RoleAssignListener roleAssignListener; - private final BanlistListener banlistListener; - private final EditRoleListener editRoleListener; - private final EditPvmListener editPvmListener; - private final GuildRoleService guildRoleService; - - public AdminCommandListener(EditRuleListener editRuleListener, - EditBanlistListener editBanlistListener, - RoleAssignListener roleAssignListener, - BanlistListener banlistListener, - EditRoleListener editRoleListener, - EditPvmListener editPvmListener, - GuildRoleService guildRoleService) { - this.editRuleListener = editRuleListener; - this.editBanlistListener = editBanlistListener; - this.roleAssignListener = roleAssignListener; - this.banlistListener = banlistListener; - this.editRoleListener = editRoleListener; - this.editPvmListener = editPvmListener; - this.guildRoleService = guildRoleService; - } - - @Override - public void onMessageReceived(@Nonnull MessageReceivedEvent event) { - if (event.getChannelType().isGuild()) { - String msg = event.getMessage().getContentRaw().toLowerCase(); - if (msg.startsWith(Commands.COMMAND_PREFIX)) { - Optional<Admin> adminCommand = messageToAdminCommand(msg); - if (adminCommand.isPresent() && event.getMember() != null) { - Stream<Role> roleStream = event.getMember().getRoles().stream(); - try { - switch (adminCommand.get()) { - case EDITRULE -> { - isPrivileged(roleStream, event, ADMIN_ROLE); - editRuleListener.proces(event); - } - case EDITBANLIST -> { - isPrivileged(roleStream, event, ADMIN_ROLE); - editBanlistListener.proces(event); - } - case ROLE -> { - isPrivileged(roleStream, event, SUB_ADMIN); - roleAssignListener.proces(event); - } - case BANLIST -> { - isPrivileged(roleStream, event, STAFF_ROLE); - banlistListener.proces(event); - } - case EDITROLE -> { - isPrivileged(roleStream, event, GOD); - editRoleListener.proces(event); - } - case EDITPVM -> { - isPrivileged(roleStream, event, STAFF_ROLE); - editPvmListener.proces(event); - } - default -> { - } - } - } catch (InsufficientPrivilegesException e) { - event.getChannel().sendMessage(e.getMessage()).queue(); - } - } - } - } - } - - private Optional<Command.Admin> messageToAdminCommand(String msg) { - for (Command.Admin adminCommand : Command.Admin.values()) { - if (msg.split(" ")[0].equals(Commands.COMMAND_PREFIX + adminCommand.name().toLowerCase())) { - return Optional.of(adminCommand); - } - } - return Optional.empty(); - } - - private void isPrivileged(Stream<Role> roleStream, MessageReceivedEvent event, int elevation) throws InsufficientPrivilegesException { - List<GuildRole> guildRoles = guildRoleService.findAllByElevationLessThanEqual(elevation); - if (roleStream.noneMatch(hasPrivilage(event, guildRoles))) - throw new InsufficientPrivilegesException(guildRoles.stream().map(GuildRole::getName).toList()); - } - - private Predicate<Role> hasPrivilage(MessageReceivedEvent event, List<GuildRole> guildRoles) { - return f -> f.hasPermission(Permission.ADMINISTRATOR) - || (event.getMember() != null && event.getMember().isOwner()) - || guildRoles.stream().map(GuildRole::getName).anyMatch(e -> e.equalsIgnoreCase(f.getName())); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/CommandListener.java b/src/main/java/com/sxcy/sxcybot/listeners/CommandListener.java @@ -1,131 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import com.sxcy.sxcybot.enums.Command; -import com.sxcy.sxcybot.listeners.member.BB8Listener; -import com.sxcy.sxcybot.listeners.member.CombatStatsListener; -import com.sxcy.sxcybot.listeners.member.CustomPollListener; -import com.sxcy.sxcybot.listeners.member.EventListener; -import com.sxcy.sxcybot.listeners.member.ForumListener; -import com.sxcy.sxcybot.listeners.member.HelpListener; -import com.sxcy.sxcybot.listeners.member.HiscoreBossListener; -import com.sxcy.sxcybot.listeners.member.KillCountListener; -import com.sxcy.sxcybot.listeners.member.PingListener; -import com.sxcy.sxcybot.listeners.member.PollListener; -import com.sxcy.sxcybot.listeners.member.PriceListener; -import com.sxcy.sxcybot.listeners.member.PvmListListener; -import com.sxcy.sxcybot.listeners.member.PvmRoleCheckListener; -import com.sxcy.sxcybot.listeners.member.PvmRolePollListener; -import com.sxcy.sxcybot.listeners.member.RuleListener; -import com.sxcy.sxcybot.listeners.member.RulesListener; -import com.sxcy.sxcybot.listeners.member.StatsListener; -import com.sxcy.sxcybot.util.Constants.Commands; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.springframework.stereotype.Component; - -import javax.annotation.Nonnull; -import java.util.Optional; - -@Component -public class CommandListener extends ListenerAdapter { - - private final BB8Listener bb8Listener; - private final RuleListener ruleListener; - private final RulesListener rulesListener; - private final PingListener pingListener; - private final EventListener eventListener; - private final ForumListener forumListener; - private final PollListener pollListener; - private final CustomPollListener customPollListener; - private final HelpListener helpListener; - private final StatsListener statsListener; - private final CombatStatsListener combatStatsListener; - private final PriceListener priceListener; - private final KillCountListener killCountListener; - private final PvmListListener pvmListListener; - private final HiscoreBossListener hiscoreBossListener; - private final PvmRoleCheckListener pvmRoleCheckListener; - private final PvmRolePollListener pvmRolePollListener; - - public CommandListener(BB8Listener bb8Listener, - RuleListener ruleListener, - RulesListener rulesListener, - PingListener pingListener, - EventListener eventListener, - ForumListener forumListener, - PollListener pollListener, - CustomPollListener customPollListener, - HelpListener helpListener, - StatsListener statsListener, - CombatStatsListener combatStatsListener, - PriceListener priceListener, - KillCountListener killCountListener, - PvmListListener pvmListListener, - HiscoreBossListener hiscoreBossListener, - PvmRoleCheckListener pvmRoleCheckListener, - PvmRolePollListener pvmRolePollListener) { - this.bb8Listener = bb8Listener; - this.ruleListener = ruleListener; - this.rulesListener = rulesListener; - this.pingListener = pingListener; - this.eventListener = eventListener; - this.forumListener = forumListener; - this.pollListener = pollListener; - this.customPollListener = customPollListener; - this.helpListener = helpListener; - this.statsListener = statsListener; - this.combatStatsListener = combatStatsListener; - this.priceListener = priceListener; - this.killCountListener = killCountListener; - this.pvmListListener = pvmListListener; - this.hiscoreBossListener = hiscoreBossListener; - this.pvmRoleCheckListener = pvmRoleCheckListener; - this.pvmRolePollListener = pvmRolePollListener; - } - - @Override - public void onMessageReceived(@Nonnull MessageReceivedEvent event) { - if (event.getChannelType().isGuild()) { - String msg = event.getMessage().getContentRaw().toLowerCase(); - if (msg.startsWith(Commands.COMMAND_PREFIX)) { - Optional<Command> command = messageToCommand(msg); - if (command.isPresent()) { - switch (command.get()) { - case RULE -> ruleListener.proces(event); - case RULES -> rulesListener.proces(event); - case PING -> pingListener.proces(event); - -// case EVENT: -// eventListener.proces(event); -// break; - case CBSTATS -> combatStatsListener.proces(event); - case STATS -> statsListener.proces(event); - case PRICE -> priceListener.proces(event); - case FORUM -> forumListener.proces(event); - case POLL -> pollListener.proces(event); - case CPOLL -> customPollListener.proces(event); - case KC -> killCountListener.proces(event); - case PVMLIST -> pvmListListener.proces(event); - case BOSSLIST -> hiscoreBossListener.proces(event); - case PVMPOLL -> pvmRolePollListener.proces(event); - case PVMCHECK -> pvmRoleCheckListener.proces(event); - case HELP -> helpListener.proces(event); - default -> { - } - } - } else if (Commands.BB8.equals(msg)) { - bb8Listener.proces(event); - } - } - } - } - - private Optional<Command> messageToCommand(String msg) { - for (Command command : Command.values()) { - if (msg.split(" ")[0].equals(Commands.COMMAND_PREFIX + command.name().toLowerCase())) { - return Optional.of(command); - } - } - return Optional.empty(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/EventWaiterUtil.java b/src/main/java/com/sxcy/sxcybot/listeners/EventWaiterUtil.java @@ -1,36 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import com.jagrosh.jdautilities.commons.waiter.EventWaiter; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; -import java.util.function.Predicate; - -@Component -public class EventWaiterUtil extends EventWaiter { - - private static final int TIMEOUT = 1; - private static final TimeUnit TIME_UNIT = TimeUnit.MINUTES; - - public void waitForPrivateChannelEvent(Consumer<PrivateMessageReceivedEvent> action, PrivateMessageReceivedEvent event, PrivateChannel privateChannel) { - waitForEvent(PrivateMessageReceivedEvent.class, verifyAuthor(event), action, TIMEOUT, TIME_UNIT, new TimeOutRunner(privateChannel)); - } - - public void waitForPrivateChannelEvent(Consumer<PrivateMessageReceivedEvent> action, MessageReceivedEvent event, PrivateChannel privateChannel) { - waitForEvent(PrivateMessageReceivedEvent.class, verifyAuthor(event), action, TIMEOUT, TIME_UNIT, new TimeOutRunner(privateChannel)); - } - - private Predicate<PrivateMessageReceivedEvent> verifyAuthor(MessageReceivedEvent event) { - return messageReceivedEvent -> messageReceivedEvent.getAuthor().getId().equals(event.getAuthor().getId()); - } - - private Predicate<PrivateMessageReceivedEvent> verifyAuthor(PrivateMessageReceivedEvent event) { - return privateMessageReceivedEvent -> privateMessageReceivedEvent.getAuthor().getId().equals(event.getAuthor().getId()); - } - - -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/GuildMemberEventListener.java b/src/main/java/com/sxcy/sxcybot/listeners/GuildMemberEventListener.java @@ -1,45 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import com.sxcy.sxcybot.services.guild.GuildEventDmerService; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import javax.annotation.Nonnull; -import java.util.Optional; - -@Component -public class GuildMemberEventListener extends ListenerAdapter { - - private static final Logger LOGGER = LoggerFactory.getLogger(GuildMemberEventListener.class); - private final GuildEventDmerService guildEventDmerService; - - public GuildMemberEventListener(GuildEventDmerService guildEventDmerService) { - this.guildEventDmerService = guildEventDmerService; - } - - @Override - public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { - guildEventDmerService.findAll().forEach(guildEventDmer -> - event.getGuild().loadMembers().onSuccess(memberList -> { - if (!memberList.isEmpty()) { - Optional<Member> member = memberList.stream().filter(f -> guildEventDmer.getName().equalsIgnoreCase(f.getUser().getName())).findFirst(); - if (member.isPresent()) { - try { - PrivateChannel privateChannel = member.get().getUser().openPrivateChannel().complete(true); - privateChannel.sendMessage(String.format("**%s** has been removed from channel _%s_", event.getUser().getName(), event.getGuild().getName())).queue(); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } - }) - ); - } -} - diff --git a/src/main/java/com/sxcy/sxcybot/listeners/Listener.java b/src/main/java/com/sxcy/sxcybot/listeners/Listener.java @@ -1,7 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; - -public interface Listener { - void proces(MessageReceivedEvent event); -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/PollReactionListener.java b/src/main/java/com/sxcy/sxcybot/listeners/PollReactionListener.java @@ -1,111 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import com.sxcy.sxcybot.services.guild.PollService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.MessageEmbed; -import net.dv8tion.jda.api.entities.MessageEmbed.Field; -import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; -import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.springframework.stereotype.Component; - -import javax.annotation.Nonnull; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -@Component -public class PollReactionListener extends ListenerAdapter { - - private final PollService pollService; - - public PollReactionListener(PollService pollService) { - this.pollService = pollService; - } - - @Override - public void onMessageReactionAdd(@Nonnull MessageReactionAddEvent event) { - if (isPoll(event)) { - event.getChannel().retrieveMessageById(event.getMessageId()).queue(message -> { - if (message.getEmbeds().size() == 1) { - MessageEmbed messageEmbed = message.getEmbeds().get(0); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(messageEmbed.getTitle()); - embedBuilder.setColor(messageEmbed.getColor()); - embedBuilder.setFooter(String.format("Last voted on %s", LocalDate.now()), event.getGuild().getIconUrl()); - String username = JdaUtil.getName(event); - for (MessageEmbed.Field field : messageEmbed.getFields()) { - List<String> nameSplit = field.getValue() != null ? new ArrayList<>(Arrays.asList(field.getValue().split(System.lineSeparator()))) : null; - if (field.getValue() != null && username != null && nameSplit.remove(username)) { - String value = String.join(System.lineSeparator(), nameSplit); - embedBuilder.addField(field); - embedBuilder.getFields() - .set(messageEmbed.getFields().indexOf(field), - new Field(getFieldNameWithCount(field, value), value, field.isInline())); - } else { - if (field.getName() != null && field.getName().contains(event.getReactionEmote().getEmoji())) { - String value = !field.getValue().contains("‎") - ? field.getValue() + System.lineSeparator() + username : username; - embedBuilder.addField(getFieldNameWithCount(field, value), value, field.isInline()); - } else { - embedBuilder.addField(field); - } - } - } - message.editMessageEmbeds(embedBuilder.build()).queue(); - message.removeReaction(event.getReaction().getReactionEmote().getEmoji(), event.getUser()).queue(); - } - }); - } - } - - public String getFieldNameWithCount(Field field, String updatedValue) { - return field.getName().replaceAll("\\(+\\d+\\)+", String.format("(%s)", getCount(updatedValue))); - } - - private long getCount(String fieldValue) { - if (fieldValue.isEmpty()) { - return 0; - } - return Arrays.stream(fieldValue.split(System.lineSeparator())).count(); - - } -// @Override -// public void onMessageReactionRemove(@Nonnull MessageReactionRemoveEvent event) { -// //event.user is null here! -// if (pollService.findByMessageId(event.getMessageId()).isPresent()) { -// event.getJDA().retrieveUserById(event.getUserId()).queue(user -> { -// if (!user.isBot()) { -// event.getChannel().retrieveMessageById(event.getMessageId()).queue(message -> { -// if (message.getEmbeds().size() == 1) { -// MessageEmbed messageEmbed = message.getEmbeds().get(0); -// EmbedBuilder embedBuilder = new EmbedBuilder(); -// embedBuilder.setTitle(messageEmbed.getTitle()); -// embedBuilder.setColor(messageEmbed.getColor()); -// for (MessageEmbed.Field field : messageEmbed.getFields()) { -// embedBuilder.addField(field); -// if (field.getName() != null && field.getName().contains(event.getReactionEmote().getEmoji())) { -// if (field.getValue() != null) { -// embedBuilder.getFields() -// .set(messageEmbed.getFields().indexOf(field), -// new Field(field.getName(), field.getValue().replace(user.getName(), ""), field.isInline())); -// message.editMessageEmbeds(embedBuilder.build()).queue(); -// } -// } -// } -// message.editMessageEmbeds(embedBuilder.build()).queue(); -// } -// }); -// } -// }); -// } -// } - - private boolean isPoll(GenericMessageReactionEvent event) { - return event.getUser() != null - && !event.getUser().isBot() - && pollService.findByMessageId(event.getMessageId()).isPresent(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/PrivateListener.java b/src/main/java/com/sxcy/sxcybot/listeners/PrivateListener.java @@ -1,9 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; - -public interface PrivateListener { - - void proces(PrivateMessageReceivedEvent privateEvent, MessageReceivedEvent event); -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/TimeOutRunner.java b/src/main/java/com/sxcy/sxcybot/listeners/TimeOutRunner.java @@ -1,28 +0,0 @@ -package com.sxcy.sxcybot.listeners; - -import net.dv8tion.jda.api.entities.MessageChannel; - -public class TimeOutRunner implements Runnable { - - private final MessageChannel messageChannel; - - public TimeOutRunner(MessageChannel messageChannel) { - this.messageChannel = messageChannel; - } - - /** - * When an object implementing interface {@code Runnable} is used - * to create a thread, starting the thread causes the object's - * {@code run} method to be called in that separately executing - * thread. - * <p> - * The general contract of the method {@code run} is that it may - * take any action whatsoever. - * - * @see Thread#run() - */ - @Override - public void run() { - messageChannel.sendMessage("Timed out... Please try again later.").queue(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/BanlistListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/BanlistListener.java @@ -1,57 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.repository.guild.dao.User; -import com.sxcy.sxcybot.services.guild.UserService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.List; - - -@Component -public class BanlistListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(BanlistListener.class); - private final UserService userService; - - public BanlistListener(UserService userService) { - this.userService = userService; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle("List of banned users:"); - List<User> bannedList = userService.findAllBanned(); - int i = 1; - for (User user : bannedList) { - embedBuilder.addField(user.getName(), - String.format("%s", user.getDescription()) + System.lineSeparator() + - String.format("||_By: %s - %s | Last edit: %s - %s_||", - user.getCreatedBy(), user.getCreatedDate(), user.getLastModifiedBy(), user.getLastModifiedDate()), - false); - - if (JdaUtil.requiresBuild(embedBuilder, bannedList.size(), i)) { - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clear(); - } - i++; - } - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/EditBanlistListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/EditBanlistListener.java @@ -1,54 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.listeners.admin.banlist.AddBanlistUserListener; -import com.sxcy.sxcybot.listeners.admin.banlist.DeleteBanlistUserListener; -import com.sxcy.sxcybot.listeners.admin.banlist.UpdateBanlistUserListener; -import com.sxcy.sxcybot.model.EditListenerDto; -import com.sxcy.sxcybot.util.EditListenerUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class EditBanlistListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(EditBanlistListener.class); - private final AddBanlistUserListener addBanlistUserListener; - private final UpdateBanlistUserListener updateBanlistListener; - private final DeleteBanlistUserListener deleteBanlistListener; - private final EditListenerUtil editListenerUtil; - - public EditBanlistListener(AddBanlistUserListener addBanlistUserListener, - UpdateBanlistUserListener updateBanlistListener, - DeleteBanlistUserListener deleteBanlistListener, - EditListenerUtil editListenerUtil) { - this.addBanlistUserListener = addBanlistUserListener; - this.updateBanlistListener = updateBanlistListener; - this.deleteBanlistListener = deleteBanlistListener; - this.editListenerUtil = editListenerUtil; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() - .addListener(addBanlistUserListener) - .updateListener(updateBanlistListener) - .deleteListener(deleteBanlistListener) - .event(event) - .privateChannel(privateChannel) - .entityName("user to banlist") - .build(); - editListenerUtil.procesEditEvent(editListenerDto); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/EditPvmListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/EditPvmListener.java @@ -1,54 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.listeners.admin.pvmrole.AddPvmListener; -import com.sxcy.sxcybot.listeners.admin.pvmrole.DeletePvmListener; -import com.sxcy.sxcybot.listeners.admin.pvmrole.UpdatePvmListener; -import com.sxcy.sxcybot.model.EditListenerDto; -import com.sxcy.sxcybot.util.EditListenerUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class EditPvmListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(EditPvmListener.class); - private final EditListenerUtil editListenerUtil; - private final AddPvmListener addPvmListener; - private final UpdatePvmListener updatePvmListener; - private final DeletePvmListener deletePvmListener; - - public EditPvmListener(EditListenerUtil editListenerUtil, - AddPvmListener addPvmListener, - UpdatePvmListener updatePvmListener, - DeletePvmListener deletePvmListener) { - this.editListenerUtil = editListenerUtil; - this.addPvmListener = addPvmListener; - this.updatePvmListener = updatePvmListener; - this.deletePvmListener = deletePvmListener; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() - .addListener(addPvmListener) - .updateListener(updatePvmListener) - .deleteListener(deletePvmListener) - .event(event) - .privateChannel(privateChannel) - .entityName("PvM competitor") - .build(); - editListenerUtil.procesEditEvent(editListenerDto); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/EditRoleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/EditRoleListener.java @@ -1,55 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.listeners.admin.role.AddRoleListener; -import com.sxcy.sxcybot.listeners.admin.role.DeleteRoleListener; -import com.sxcy.sxcybot.listeners.admin.role.UpdateRoleListener; -import com.sxcy.sxcybot.model.EditListenerDto; -import com.sxcy.sxcybot.util.EditListenerUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class EditRoleListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(EditRoleListener.class); - private final AddRoleListener addRoleListener; - private final UpdateRoleListener updateRoleListener; - private final DeleteRoleListener deleteRoleListener; - private final EditListenerUtil editListenerUtil; - - public EditRoleListener(AddRoleListener addRoleListener, - UpdateRoleListener updateRoleListener, - DeleteRoleListener deleteRoleListener, - EditListenerUtil editListenerUtil) { - this.addRoleListener = addRoleListener; - this.updateRoleListener = updateRoleListener; - this.deleteRoleListener = deleteRoleListener; - this.editListenerUtil = editListenerUtil; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() - .addListener(addRoleListener) - .deleteListener(deleteRoleListener) - //TODO why not implemented? -// .updateListener(updateRoleListener) - .event(event) - .privateChannel(privateChannel) - .entityName("role") - .build(); - editListenerUtil.procesEditEvent(editListenerDto); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/EditRuleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/EditRuleListener.java @@ -1,54 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.listeners.admin.rule.AddRuleListener; -import com.sxcy.sxcybot.listeners.admin.rule.DeleteRuleListener; -import com.sxcy.sxcybot.listeners.admin.rule.UpdateRuleListener; -import com.sxcy.sxcybot.model.EditListenerDto; -import com.sxcy.sxcybot.util.EditListenerUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class EditRuleListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(EditRuleListener.class); - private final AddRuleListener addRuleListener; - private final UpdateRuleListener updateRuleListener; - private final DeleteRuleListener deleteRuleListener; - private final EditListenerUtil editListenerUtil; - - public EditRuleListener(AddRuleListener addRuleListener, - UpdateRuleListener updateRuleListener, - DeleteRuleListener deleteRuleListener, - EditListenerUtil editListenerUtil) { - this.addRuleListener = addRuleListener; - this.updateRuleListener = updateRuleListener; - this.deleteRuleListener = deleteRuleListener; - this.editListenerUtil = editListenerUtil; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() - .addListener(addRuleListener) - .updateListener(updateRuleListener) - .deleteListener(deleteRuleListener) - .event(event) - .privateChannel(privateChannel) - .entityName("rule") - .build(); - editListenerUtil.procesEditEvent(editListenerDto); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/RoleAssignListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/RoleAssignListener.java @@ -1,100 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.repository.guild.dao.GuildRole; -import com.sxcy.sxcybot.services.guild.GuildRoleService; -import com.sxcy.sxcybot.util.DiscordMemberFinderUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.entities.Role; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; - -import static com.sxcy.sxcybot.util.Constants.ADDED_ROLE_ELEVATION; - -@Component -public class RoleAssignListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(RoleAssignListener.class); - private final EventWaiterUtil eventWaiterUtil; - private final GuildRoleService guildRoleService; - private final DiscordMemberFinderUtil discordMemberFinderUtil; - - public RoleAssignListener(EventWaiterUtil eventWaiterUtil, - GuildRoleService guildRoleService, - DiscordMemberFinderUtil discordMemberFinderUtil) { - this.eventWaiterUtil = eventWaiterUtil; - this.guildRoleService = guildRoleService; - this.discordMemberFinderUtil = discordMemberFinderUtil; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.RED); - discordMemberFinderUtil.onMemberFoundVerification(event, embedBuilder, privateChannel, member -> { - embedBuilder.clearFields(); - embedBuilder.setTitle("Type the numbers of the roles to add separated by a whitespace. If the member already has any role, it will get removed instead."); - List<GuildRole> rolesToAdd = guildRoleService.findAllByElevationGreaterThanEqual(ADDED_ROLE_ELEVATION) - .stream().sorted(Comparator.nullsLast(Comparator.comparing(GuildRole::getOrderValue))).toList(); - for (GuildRole guildRole : rolesToAdd) { - embedBuilder.addField(String.valueOf(guildRole.getOrderValue()), String.valueOf(guildRole.getName()), true); - } - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - eventWaiterUtil.waitForPrivateChannelEvent(roleReceiver -> { - String roleMessage = roleReceiver.getMessage().getContentRaw(); -// try { - String[] roleNumbers = roleMessage.split(" "); - embedBuilder.clearFields(); - embedBuilder.setTitle("Role assigner:"); - for (String roleNumber : roleNumbers) { - try { - Optional<GuildRole> discordRole = rolesToAdd.stream().filter(f -> Integer.parseInt(roleNumber) == f.getOrderValue()).findFirst(); - if (discordRole.isPresent()) { - Optional<Role> role = event.getGuild().getRoles().stream().filter(f -> discordRole.get().getName().equalsIgnoreCase(f.getName())).findFirst(); - if (role.isPresent()) { - String action; - if (member.getRoles().contains(role.get())) { - event.getGuild().removeRoleFromMember(member, role.get()).queue(); - action = "removed"; - } else { - event.getGuild().addRoleToMember(member, role.get()).queue(); - action = "assigned"; - } - embedBuilder.addField(String.format("\"%s\" has been succesfully %s.", discordRole.get().getName(), action), "", false); - event.getChannel().sendMessage(String.format("Role \"%s\" has been %s to %s by %s", - role.get().getName(), action, member.getUser(), event.getMember().getUser().getName())).queue(); - } else { - privateChannel.sendMessage("No such role is available in the channel, please contact your channel owner.").queue(); - } - } else { - privateChannel.sendMessage(String.format("%s is not in the suggested list, please try again later.", roleNumber)).queue(); - } - } catch (NumberFormatException e) { - privateChannel.sendMessage(String.format("%s is not a valid number, please try again later.", roleNumber)).queue(); - } - } - if (embedBuilder.getFields().isEmpty()) { - embedBuilder.addField("No roles changed.", "", false); - } - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - }, event, privateChannel); - }); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/banlist/AddBanlistUserListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/banlist/AddBanlistUserListener.java @@ -1,47 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.banlist; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.User; -import com.sxcy.sxcybot.services.guild.UserService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -@Component -public class AddBanlistUserListener implements PrivateListener { - - private final EventWaiterUtil eventWaiterUtil; - private final UserService userService; - - public AddBanlistUserListener(EventWaiterUtil eventWaiterUtil, - UserService userService) { - this.eventWaiterUtil = eventWaiterUtil; - this.userService = userService; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Name of the user you want to ban?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { - privateChannel.sendMessage("Description?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { - User userToBan = User.Builder.newBuilder() - .name(nameReceiver.getMessage().getContentRaw()) - .description(descriptionReceiver.getMessage().getContentRaw()) - .banned(true) - .createdBy(JdaUtil.getName(event)) - .lastModifiedBy(JdaUtil.getName(event)) - .build(); - User bannedUser = userService.save(userToBan); - privateChannel.sendMessage(String.format("User %s has been succesfully banned.", bannedUser.getName())).queue(); - event.getChannel().sendMessage(String.format("User %s has been banned by %s. (%s)", - bannedUser.getName(), JdaUtil.getUser(event), bannedUser.getDescription() - )).queue(); - }, privateMessageReceivedEvent, privateChannel); - }, privateMessageReceivedEvent, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/banlist/DeleteBanlistUserListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/banlist/DeleteBanlistUserListener.java @@ -1,41 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.banlist; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.User; -import com.sxcy.sxcybot.services.guild.UserService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -@Component -public class DeleteBanlistUserListener implements PrivateListener { - - private final UserService userService; - private final EventWaiterUtil eventWaiterUtil; - - public DeleteBanlistUserListener(UserService userService, - EventWaiterUtil eventWaiterUtil) { - this.userService = userService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateEvent.getChannel(); - privateChannel.sendMessage("Name of the user you want to delete?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { - try { - User userToDelete = userService.findByName(nameReceiver.getMessage().getContentRaw()); - userService.delete(userToDelete); - privateChannel.sendMessage(String.format("%s succesfully deleted.", userToDelete)).queue(); - event.getChannel().sendMessage(String.format("User %s has been deleted from the banlist by %s", userToDelete, JdaUtil.getUser(event))).queue(); - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, event, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/banlist/UpdateBanlistUserListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/banlist/UpdateBanlistUserListener.java @@ -1,59 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.banlist; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.User; -import com.sxcy.sxcybot.services.guild.UserService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -@Component -public class UpdateBanlistUserListener implements PrivateListener { - - private final EventWaiterUtil eventWaiterUtil; - private final UserService userService; - - public UpdateBanlistUserListener(EventWaiterUtil eventWaiterUtil, - UserService userService) { - this.eventWaiterUtil = eventWaiterUtil; - this.userService = userService; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Name of the user you want to update (\"showlist\" to show all names in banlist).").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { - if (nameReceiver.getMessage().getContentRaw().equalsIgnoreCase("showlist")) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle("Banned users:"); - userService.findAllBanned().stream().map(User::getName).toList().forEach(f -> - embedBuilder.addField(f, "", false)); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - this.proces(privateMessageReceivedEvent, event); - return; - } - try { - User userToUpdate = userService.findByName(nameReceiver.getMessage().getContentRaw()); - privateChannel.sendMessage(String.format("Type the new description for the ban of %s.", nameReceiver.getMessage().getContentRaw())).queue(); - eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { - userToUpdate.setDescription(descriptionReceiver.getMessage().getContentRaw()); - userToUpdate.setLastModifiedBy(JdaUtil.getName(event)); - User saved = userService.save(userToUpdate); - privateChannel.sendMessage(saved + " edited.").queue(); - event.getChannel().sendMessage(String.format("Banned user %s has been edited by %s.", saved.getName(), JdaUtil.getUser(event))).queue(); - }, privateMessageReceivedEvent, privateChannel); - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, event, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/AddPvmListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/AddPvmListener.java @@ -1,77 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.pvmrole; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleSnapshotComparatorService; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import com.sxcy.sxcybot.util.DiscordMemberFinderUtil; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -@Component -public class AddPvmListener implements PrivateListener { - - private final EventWaiterUtil eventWaiterUtil; - private final DiscordMemberFinderUtil discordMemberFinderUtil; - private final PvmRoleUserService pvmRoleUserService; - private final PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService; - - public AddPvmListener(EventWaiterUtil eventWaiterUtil, - DiscordMemberFinderUtil discordMemberFinderUtil, - PvmRoleUserService pvmRoleUserService, - PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService) { - this.eventWaiterUtil = eventWaiterUtil; - this.discordMemberFinderUtil = discordMemberFinderUtil; - this.pvmRoleUserService = pvmRoleUserService; - this.pvmRoleSnapshotComparatorService = pvmRoleSnapshotComparatorService; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.RED); - embedBuilder.setTitle("Add member for PvM competition"); - discordMemberFinderUtil.onMemberFoundVerification(event, embedBuilder, privateChannel, member -> { - embedBuilder.clearFields(); - embedBuilder.addField("Type the RSN (RuneScape name) of the member.", "", true); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - eventWaiterUtil.waitForPrivateChannelEvent((rsnReceiver) -> { - String creator = JdaUtil.getName(event); - try { - PvmRoleUser pvmRoleUser = pvmRoleUserService.save(PvmRoleUser.Builder.newBuilder() - .rsn(rsnReceiver.getMessage().getContentRaw()) - .discordName(member.getEffectiveName()) - .createdBy(creator) - .lastModifiedBy(creator) - .build() - ); - event.getChannel().sendMessage(String.format("%s (RSN: %s) has been added to the PvM competition by %s!", - member, pvmRoleUser.getRsn(), creator)).queue(); - privateChannel.sendMessage(String.format("%s (RSN: %s) has been succesfully added!", - member, pvmRoleUser.getRsn())).queue(); - try { - pvmRoleSnapshotComparatorService.takeSnapshot(event.getChannel(), pvmRoleUser, true, true); - } catch (EntityNotFoundException e) { - event.getChannel().sendMessage(e.getMessage()).queue(); - } - } catch (DataIntegrityViolationException e) { - if (e.getRootCause() != null) { - privateChannel.sendMessage(e.getRootCause().getMessage()).queue(); - } else if (e.getMessage() != null) - privateChannel.sendMessage(e.getMessage()).queue(); - privateChannel.sendMessage("Please try updating the existing PvM competitor instead.").queue(); - } - }, event, privateChannel); - }); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java @@ -1,47 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.pvmrole; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmKcSnapshotService; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -@Component -public class DeletePvmListener implements PrivateListener { - - private final PvmRoleUserService pvmRoleUserService; - private final PvmKcSnapshotService pvmKcSnapshotService; - private final EventWaiterUtil eventWaiterUtil; - - public DeletePvmListener(PvmRoleUserService pvmRoleUserService, - PvmKcSnapshotService pvmKcSnapshotService, - EventWaiterUtil eventWaiterUtil) { - this.pvmRoleUserService = pvmRoleUserService; - this.pvmKcSnapshotService = pvmKcSnapshotService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Type the discord name of the user you want to delete.").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(discordNameReceiver -> { - String discordName = discordNameReceiver.getMessage().getContentRaw(); - try { - PvmRoleUser pvmRoleUser = pvmRoleUserService.findByDiscordName(discordName); - pvmKcSnapshotService.deleteAll(pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser)); - pvmRoleUserService.delete(pvmRoleUser); - privateChannel.sendMessage(String.format("%s has been succesfully deleted.", pvmRoleUser)).queue(); - event.getChannel().sendMessage(String.format("PvM competitor %s has been deleted by %s", discordName, JdaUtil.getUser(event))).queue(); - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java @@ -1,80 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.pvmrole; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -import static com.sxcy.sxcybot.enums.Command.PVMLIST; -import static com.sxcy.sxcybot.util.Constants.Commands.COMMAND_PREFIX; - -@Component -public class UpdatePvmListener implements PrivateListener { - - private final PvmRoleUserService pvmRoleUserService; - private final EventWaiterUtil eventWaiterUtil; - - public UpdatePvmListener(PvmRoleUserService pvmRoleUserService, - EventWaiterUtil eventWaiterUtil) { - this.pvmRoleUserService = pvmRoleUserService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.RED); - embedBuilder.setTitle("Update user for PvM competition."); - embedBuilder.addField("Type the discord name of the user you want to update.", "", false); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - eventWaiterUtil.waitForPrivateChannelEvent(discordNameReceiver -> { - String discordName = discordNameReceiver.getMessage().getContentRaw(); - try { - PvmRoleUser pvmRoleUserToUpdate = pvmRoleUserService.findByDiscordName(discordName); - embedBuilder.addField("Confirm by typing ``yes or y``.", - String.format("Is " + System.lineSeparator() + "Discord: %s | RSN: %s " + System.lineSeparator() + "the correct member?" - , pvmRoleUserToUpdate.getDiscordName(), pvmRoleUserToUpdate.getRsn()), false); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - eventWaiterUtil.waitForPrivateChannelEvent(memberVerifyReceiver -> { - String verifyMessage = memberVerifyReceiver.getMessage().getContentRaw(); - if ("y".equalsIgnoreCase(verifyMessage) || "yes".equalsIgnoreCase(verifyMessage)) { - embedBuilder.addField("Type the new RSN for the update.", "", false); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - eventWaiterUtil.waitForPrivateChannelEvent(newRsnReceiver -> { - String newRsn = newRsnReceiver.getMessage().getContentRaw(); - pvmRoleUserToUpdate.setRsn(newRsn); - pvmRoleUserToUpdate.setLastModifiedBy(JdaUtil.getName(event)); - try { - PvmRoleUser savedPvmRoleUser = pvmRoleUserService.save(pvmRoleUserToUpdate); - newRsnReceiver.getChannel().sendMessage(savedPvmRoleUser + " edited").queue(); - event.getChannel().sendMessage(String.format("RSN for PvM competitor %s has been changed to %s by %s", - discordName, newRsn, JdaUtil.getUser(event))).queue(); - } catch (DataIntegrityViolationException e) { - if (e.getMessage() != null) - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } else { - privateChannel.sendMessage(String.format("You can check all competitors with the \"%s\" command.", COMMAND_PREFIX + PVMLIST.name().toLowerCase())).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/role/AddRoleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/role/AddRoleListener.java @@ -1,56 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.role; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.GuildRole; -import com.sxcy.sxcybot.services.guild.GuildRoleService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.entities.Role; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.util.Comparator; -import java.util.Optional; - -import static com.sxcy.sxcybot.util.Constants.ADDED_ROLE_ELEVATION; - -@Component -public class AddRoleListener implements PrivateListener { - - private final GuildRoleService guildRoleService; - private final EventWaiterUtil eventWaiterUtil; - - public AddRoleListener(GuildRoleService guildRoleService, - EventWaiterUtil eventWaiterUtil) { - this.guildRoleService = guildRoleService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Name of the role you want to add?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { - String roleName = nameReceiver.getMessage().getContentRaw(); - Optional<Role> role = event.getGuild().getRoles().stream().filter(f -> roleName.equalsIgnoreCase(f.getName())).findFirst(); - if (role.isPresent()) { - int orderValue = guildRoleService.findAll().stream().filter(f -> f.getOrderValue() != null).max(Comparator.comparing(GuildRole::getOrderValue)).map(GuildRole::getOrderValue).orElse(0) + 1; - GuildRole roleToAdd = GuildRole.Builder.newBuilder() - .name(roleName) - .orderValue(orderValue) - .elevation(ADDED_ROLE_ELEVATION) - .build(); - GuildRole guildRole = guildRoleService.save(roleToAdd); - privateChannel.sendMessage(String.format("Role %s has been succesfully added.", guildRole.getName())).queue(); - event.getChannel().sendMessage(String.format("Role %s has been added by %s.", - guildRole.getName(), JdaUtil.getUser(event) - )).queue(); - } else { - privateChannel.sendMessage(String.format("Role with name %s is not available in the channel, please contact a channel owner to have it added.", roleName)).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/role/DeleteRoleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/role/DeleteRoleListener.java @@ -1,53 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.role; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.GuildRole; -import com.sxcy.sxcybot.services.guild.GuildRoleService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -import static com.sxcy.sxcybot.util.Constants.ADDED_ROLE_ELEVATION; -import static com.sxcy.sxcybot.util.Constants.Commands.COMMAND_PREFIX; - -@Component -public class DeleteRoleListener implements PrivateListener { - - private final GuildRoleService guildRoleService; - private final EventWaiterUtil eventWaiterUtil; - - public DeleteRoleListener(GuildRoleService guildRoleService, - EventWaiterUtil eventWaiterUtil) { - this.guildRoleService = guildRoleService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Name of the role you want to delete?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { - try { - GuildRole guildRole = guildRoleService.findByName(nameReceiver.getMessage().getContentRaw()); - if (guildRole.getElevation() == ADDED_ROLE_ELEVATION) { - guildRoleService.delete(guildRole); - guildRoleService.findAll().stream().filter(f -> f.getOrderValue() != null && f.getOrderValue() > guildRole.getOrderValue()).toList() - .forEach(role -> { - role.setOrderValue(role.getOrderValue() - 1); - guildRoleService.save(role); - }); - privateChannel.sendMessage(String.format("%s succesfully deleted.", guildRole)).queue(); - event.getChannel().sendMessage(String.format("Role %s has been deleted by %s", guildRole, JdaUtil.getUser(event))).queue(); - } else { - privateChannel.sendMessage(String.format("Only roles that can be added with the %srole command can be deleted.", COMMAND_PREFIX)).queue(); - } - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, event, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/role/UpdateRoleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/role/UpdateRoleListener.java @@ -1,55 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.role; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.GuildRole; -import com.sxcy.sxcybot.services.guild.GuildRoleService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -import static com.sxcy.sxcybot.util.Constants.ADDED_ROLE_ELEVATION; -import static com.sxcy.sxcybot.util.Constants.Commands.COMMAND_PREFIX; - -@Component -public class UpdateRoleListener implements PrivateListener { - - private final GuildRoleService guildRoleService; - private final EventWaiterUtil eventWaiterUtil; - - public UpdateRoleListener(GuildRoleService guildRoleService, - EventWaiterUtil eventWaiterUtil) { - this.guildRoleService = guildRoleService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Type the name of the role you want to update.").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(oldRoleNameReceiver -> { - String roleName = oldRoleNameReceiver.getMessage().getContentRaw(); - privateChannel.sendMessage("Type the new name for the role.").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(newRoleNameReceiver -> { - try { - GuildRole oldRole = guildRoleService.findByName(roleName); - if (oldRole.getElevation() == ADDED_ROLE_ELEVATION) { - GuildRole guildRoleToUpdate = guildRoleService.findByName(roleName); - guildRoleToUpdate.setName(newRoleNameReceiver.getMessage().getContentRaw()); - - GuildRole guildRole = guildRoleService.save(guildRoleToUpdate); - newRoleNameReceiver.getChannel().sendMessage(guildRole + " edited").queue(); - event.getChannel().sendMessage(String.format("Role %s has been changed to %s by %s", roleName, newRoleNameReceiver.getMessage().getContentRaw(), JdaUtil.getUser(event))).queue(); - } else { - privateChannel.sendMessage(String.format("Only roles that can be added with the %srole command can be updated.", COMMAND_PREFIX)).queue(); - } - } catch (EntityNotFoundException exc) { - oldRoleNameReceiver.getChannel().sendMessage(exc.getMessage()).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - }, privateMessageReceivedEvent, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/rule/AddRuleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/rule/AddRuleListener.java @@ -1,40 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.rule; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.Rule; -import com.sxcy.sxcybot.services.guild.RuleService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.util.Comparator; - -@Component -public class AddRuleListener implements PrivateListener { - - private final RuleService ruleService; - private final EventWaiterUtil eventWaiterUtil; - - public AddRuleListener(RuleService ruleService, - EventWaiterUtil eventWaiterUtil) { - this.ruleService = ruleService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - privateMessageReceivedEvent.getChannel().sendMessage("Type rule description please").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(e -> { - String msg = e.getMessage().getContentRaw(); - int number = ruleService.findAll().stream().max(Comparator.comparing(Rule::getNumber)).map(Rule::getNumber).orElse(0) + 1; - Rule rule = ruleService.save(Rule.Builder.newBuilder() - .number(number) - .description(msg) - .build()); - e.getChannel().sendMessage(rule + " saved").queue(); - event.getChannel().sendMessage(String.format("Rule #%s has been added by %s.", number, JdaUtil.getUser(event))).queue(); - }, privateMessageReceivedEvent, privateMessageReceivedEvent.getChannel()); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/rule/DeleteRuleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/rule/DeleteRuleListener.java @@ -1,51 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.rule; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.Rule; -import com.sxcy.sxcybot.services.guild.RuleService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - - -@Component -public class DeleteRuleListener implements PrivateListener { - - private final RuleService ruleService; - private final EventWaiterUtil eventWaiterUtil; - - public DeleteRuleListener(RuleService ruleService, - EventWaiterUtil eventWaiterUtil) { - this.ruleService = ruleService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Type the # of the rule you wish to delete please.").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(ruleDeleltionReceiver -> { - try { - int ruleNumber = Integer.parseInt(ruleDeleltionReceiver.getMessage().getContentRaw()); - Rule rule = ruleService.findByNumber(ruleNumber); - ruleService.delete(rule); - ruleService.findAll().stream().filter(f -> f.getNumber() > ruleNumber).toList() - .forEach(ruleToUpdate -> { - ruleToUpdate.setNumber(ruleToUpdate.getNumber() - 1); - ruleService.save(ruleToUpdate); - }); - privateChannel.sendMessage(String.format("%s has been succesfully deleted.", rule)).queue(); - event.getChannel().sendMessage(String.format("Rule %s has been deleted by %s", rule, JdaUtil.getUser(event))).queue(); - } catch (NumberFormatException e) { - privateChannel.sendMessage("Please try again later with a valid rule number.").queue(); - } catch (EntityNotFoundException e) { - privateChannel.sendMessage(e.getMessage()).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/admin/rule/UpdateRuleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/admin/rule/UpdateRuleListener.java @@ -1,51 +0,0 @@ -package com.sxcy.sxcybot.listeners.admin.rule; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.PrivateListener; -import com.sxcy.sxcybot.repository.guild.dao.Rule; -import com.sxcy.sxcybot.services.guild.RuleService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.stereotype.Component; - - -@Component -public class UpdateRuleListener implements PrivateListener { - - private final RuleService ruleService; - private final EventWaiterUtil eventWaiterUtil; - - public UpdateRuleListener(RuleService ruleService, - EventWaiterUtil eventWaiterUtil) { - this.ruleService = ruleService; - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { - PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); - privateChannel.sendMessage("Type the rule number you want to update.").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(ruleNumberReciever -> { - try { - int ruleNumber = Integer.parseInt(ruleNumberReciever.getMessage().getContentRaw()); - privateChannel.sendMessage(String.format("Type the new rule description for rule %s.", ruleNumber)).queue(); - eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { - try { - Rule ruleToUpdate = ruleService.findByNumber(ruleNumber); - ruleToUpdate.setDescription(descriptionReceiver.getMessage().getContentRaw()); - Rule rule = ruleService.save(ruleToUpdate); - descriptionReceiver.getChannel().sendMessage(rule + " edited").queue(); - event.getChannel().sendMessage(String.format("Rule #%s has been edited by %s", ruleNumber, JdaUtil.getUser(event))).queue(); - } catch (EntityNotFoundException exc) { - ruleNumberReciever.getChannel().sendMessage(exc.getMessage()).queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } catch (NumberFormatException exc) { - ruleNumberReciever.getChannel().sendMessage("No valid rule number.").queue(); - } - }, privateMessageReceivedEvent, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/BB8Listener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/BB8Listener.java @@ -1,25 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import net.dv8tion.jda.api.entities.MessageChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.io.InputStream; - -import static com.sxcy.sxcybot.util.Constants.Emoji.FLAMES; -import static com.sxcy.sxcybot.util.Constants.Emoji.THUMBS_UP; - -@Component -public class BB8Listener implements Listener { - - private static final String BB8_IMAGE = "/images/bb8.jpg"; - - @Override - public void proces(MessageReceivedEvent event) { - MessageChannel channel = event.getChannel(); - InputStream in = getClass().getResourceAsStream(BB8_IMAGE); - channel.sendMessage("BEEP BOOP! " + THUMBS_UP + " " + FLAMES) - .addFile(in, "bb8.jpg").queue(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/CombatStatsListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/CombatStatsListener.java @@ -1,51 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.model.CombatDto; -import com.sxcy.sxcybot.model.OsrsStat; -import com.sxcy.sxcybot.services.osrs.CombatCalculatorService; -import com.sxcy.sxcybot.services.osrs.StatMessageSender; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.util.List; - -import static com.sxcy.sxcybot.enums.OsrsCombatStat.ATTACK; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.DEFENCE; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.HITPOINTS; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.MAGIC; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.PRAYER; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.RANGED; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.STRENGTH; - -@Component -public class CombatStatsListener implements Listener { - - private final StatMessageSender statMessageSender; - private final CombatCalculatorService combatCalculatorService; - - private static final List<String> COMBAT_STAT_LIST = List.of(ATTACK.value, STRENGTH.value, DEFENCE.value, HITPOINTS.value, RANGED.value, PRAYER.value, MAGIC.value); - - public CombatStatsListener(StatMessageSender statMessageSender, - CombatCalculatorService combatCalculatorService) { - this.statMessageSender = statMessageSender; - this.combatCalculatorService = combatCalculatorService; - } - - @Override - public void proces(MessageReceivedEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - event.getChannel().sendTyping().queue(e -> - statMessageSender.sendStatMessage(event, embedBuilder, this::isCombatStat, - f -> embedBuilder.addField(f.name(), "Level " + f.level(), true) - , osrsStatList -> embedBuilder.addField("COMBAT", String.valueOf(combatCalculatorService.getCombatLevel(CombatDto.build(osrsStatList))), false) - ) - ); - } - - private boolean isCombatStat(OsrsStat osrsStat) { - return COMBAT_STAT_LIST.contains(osrsStat.name()); - } - -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/CustomPollListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/CustomPollListener.java @@ -1,51 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.util.CustomPollFiller; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.LinkedHashSet; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class CustomPollListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(CustomPollListener.class); - private final CustomPollFiller customPollFiller; - - public CustomPollListener(CustomPollFiller customPollFiller) { - this.customPollFiller = customPollFiller; - } - - @Override - public void proces(MessageReceivedEvent event) { - String msg = event.getMessage().getContentRaw(); - try { - String title = msg.substring(msg.indexOf(" ")); - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle(title); - embedBuilder.setFooter("Let the polling begin!", event.getGuild().getIconUrl()); - - customPollFiller.fillPoll(privateChannel, event, embedBuilder, new LinkedHashSet<>()); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } catch (StringIndexOutOfBoundsException e) { - event.getChannel().sendMessage("Please enter a descriptive title for the poll after the command, separated by space.").queue(); - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/EventListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/EventListener.java @@ -1,58 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.repository.guild.dao.Event; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class EventListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(EventListener.class); - private final EventWaiterUtil eventWaiterUtil; - - public EventListener(EventWaiterUtil eventWaiterUtil) { - this.eventWaiterUtil = eventWaiterUtil; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (!event.getAuthor().isBot() && event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - privateChannel.sendMessage("Name of the event?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { - privateChannel.sendMessage("Description?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { - privateChannel.sendMessage("TimeZone, UTC or PT?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(timeZoneReceiver -> { - privateChannel.sendMessage("Date?").queue(); - eventWaiterUtil.waitForPrivateChannelEvent(dateReceiver -> - finishEventCreation(nameReceiver, descriptionReceiver, timeZoneReceiver, dateReceiver, event), event, privateChannel); - }, event, privateChannel); - }, event, privateChannel); - }, event, privateChannel); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } - - private void finishEventCreation(PrivateMessageReceivedEvent nameReceiver, - PrivateMessageReceivedEvent descriptionReceiver, - PrivateMessageReceivedEvent timeZoneReceiver, - PrivateMessageReceivedEvent dateReceiver, - MessageReceivedEvent event) { - Event createdEvent = Event.Builder.newBuilder() - .name(nameReceiver.getMessage().getContentRaw()) - .description(descriptionReceiver.getMessage().getContentRaw()) - .build(); - event.getChannel().sendMessage("Event created :" + createdEvent).queue(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/ForumListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/ForumListener.java @@ -1,31 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.services.guild.ChannelDetailService; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.MessageChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -@Component -public class ForumListener implements Listener { - - private final ChannelDetailService channelDetailService; - - public ForumListener(ChannelDetailService channelDetailService) { - this.channelDetailService = channelDetailService; - } - - @Override - public void proces(MessageReceivedEvent event) { - channelDetailService.findAll().stream().findAny().ifPresent(channelDetail -> { - MessageChannel channel = event.getChannel(); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.RED); - embedBuilder.setTitle("Link to the forum post", channelDetail.getForumUrl()); - channel.sendMessageEmbeds(embedBuilder.build()).queue(); - }); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/HelpListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/HelpListener.java @@ -1,35 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.enums.Command; -import com.sxcy.sxcybot.enums.Command.Admin; -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.util.Constants.Commands; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -@Component -public class HelpListener implements Listener { - - @Override - public void proces(MessageReceivedEvent event) { - event.getChannel().sendTyping().queue(); - EmbedBuilder embedBuilder = new EmbedBuilder(); - - embedBuilder.setColor(Color.red); - embedBuilder.setTitle("List of Commands"); - for (Command command : Command.values()) { - embedBuilder.addField(Commands.COMMAND_PREFIX + command.name().toLowerCase(), command.description, false); - } - EmbedBuilder adminEmbedBuilder = new EmbedBuilder(); - adminEmbedBuilder.setColor(Color.red); - adminEmbedBuilder.setTitle("List of Admin Commands"); - for (Admin admin : Admin.values()) { - adminEmbedBuilder.addField(Commands.COMMAND_PREFIX + admin.name().toLowerCase(), admin.description, false); - } - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - event.getChannel().sendMessageEmbeds(adminEmbedBuilder.build()).queue(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/HiscoreBossListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/HiscoreBossListener.java @@ -1,50 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.enums.PvmRole; -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; -import com.sxcy.sxcybot.services.osrs.OsrsHiscoreBossService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.List; - -@Component -public class HiscoreBossListener implements Listener { - - private final OsrsHiscoreBossService osrsHiscoreBossService; - - public HiscoreBossListener(OsrsHiscoreBossService osrsHiscoreBossService) { - this.osrsHiscoreBossService = osrsHiscoreBossService; - } - - @Override - public void proces(MessageReceivedEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - List<OsrsHiscoreBoss> hiscoreBossList = osrsHiscoreBossService.findAll(); - for (PvmRole pvmRole : PvmRole.values()) { - int i = 1; - embedBuilder.setTitle(String.format("List of %s bosses:", pvmRole)); - for (OsrsHiscoreBoss osrsHiscoreBoss : hiscoreBossList) { - if (pvmRole.value == osrsHiscoreBoss.getPvmRole()) { - embedBuilder.addField(osrsHiscoreBoss.getName(), - String.format("Multiplier: %s", - osrsHiscoreBoss.getMultiplier()), - true); - if (JdaUtil.requiresBuild(embedBuilder, hiscoreBossList.size(), i)) { - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - } - } - i++; - } - if (embedBuilder.getFields().size() > 0) - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/KillCountListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/KillCountListener.java @@ -1,53 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.client.HiScoreClient; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.model.OsrsBossKc; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.List; - -@Component -public class KillCountListener implements Listener { - - private final HiScoreClient hiScoreClient; - - public KillCountListener(HiScoreClient hiScoreClient) { - this.hiScoreClient = hiScoreClient; - } - - @Override - public void proces(MessageReceivedEvent event) { - String msg = event.getMessage().getContentRaw(); - try { - String player = msg.substring(msg.indexOf(" ")).trim(); - List<OsrsBossKc> bossKcList = hiScoreClient.getHiScoreBossKc(player, event.getChannel()).orElseThrow(() - -> new EntityNotFoundException(String.format("No HiScores found for %s.", player))); - - event.getChannel().sendTyping().queue(q -> { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(String.format("Killcount for %s", player)); - embedBuilder.setColor(Color.RED); - int i = 1; - bossKcList.stream().filter(f -> !"-1".equals(f.kc())).forEach(f -> { - embedBuilder.addField(f.name(), String.format("Kc: %s%sRank: %s", f.kc(), System.lineSeparator(), f.rank()), true); - if (JdaUtil.requiresBuild(embedBuilder, bossKcList.size(), i)) { - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clearFields(); - } - }); - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - }); - - } catch (StringIndexOutOfBoundsException e) { - event.getChannel().sendMessage("Please enter a player name after the command, separated by space.").queue(); - } catch (EntityNotFoundException e) { - event.getChannel().sendMessage(e.getMessage()).queue(); - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/PingListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/PingListener.java @@ -1,19 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import net.dv8tion.jda.api.entities.MessageChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -@Component -public class PingListener implements Listener { - - @Override - public void proces(MessageReceivedEvent event) { - MessageChannel channel; - channel = event.getChannel(); - long time = System.currentTimeMillis(); - channel.sendMessage("Pong") - .queue(response -> response.editMessageFormat("Pong: %d ms", System.currentTimeMillis() - time).queue()); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/PollListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/PollListener.java @@ -1,66 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.repository.guild.dao.Poll; -import com.sxcy.sxcybot.services.guild.PollService; -import com.sxcy.sxcybot.util.Constants.Reaction; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -@Component -public class PollListener implements Listener { - - private final PollService pollService; - - public PollListener(PollService pollService) { - this.pollService = pollService; - } - - @Override - public void proces(MessageReceivedEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - String msg = event.getMessage().getContentRaw(); - try { - String title = msg.substring(msg.indexOf(" ")); - - embedBuilder.setColor(Color.red); - embedBuilder.setTitle(title); - embedBuilder.addField("✅ Accept (0)", "", true); - embedBuilder.addField("❎ Deny (0)", "", true); - embedBuilder.addField("❓ Unsure (0)", "", true); - embedBuilder.setFooter("Let the polling begin!", event.getGuild().getIconUrl()); - - event.getChannel().sendTyping().queue(typing -> - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(message -> { - message.addReaction(Reaction.CHECK_MARK_BUTTON) - .and(message.addReaction(Reaction.CROSS_MARK_BUTTON)) - .and(message.addReaction(Reaction.QUESTION_MARK)) - .queue(); - pollService.save(Poll.Builder.newBuilder().messageId(message.getId()).build()); - })); - } catch (StringIndexOutOfBoundsException e) { - event.getChannel().sendMessage("Please enter a descriptive title for the poll after the command, separated by space.").queue(); - } - } - -// private Poll createPoll(String messageId) { -// List<PollReaction> pollReactionList = newArrayList(); -// Poll poll = Poll.builder() -// .pollReactions(newArrayList(pollReactionList)) -// .messageId(messageId) -// .build(); -// PollReaction pollReaction = PollReaction.builder() -// .reactionId("reactionId") -// .poll(poll) -// .build(); -// pollReactionList.add(pollReaction); -// poll.setPollReactions(pollReactionList); -// -// return poll; -// -// } -} - diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/PriceListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/PriceListener.java @@ -1,43 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.client.GrandExchangeClient; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.Listener; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -@Component -public class PriceListener implements Listener { - - private final GrandExchangeClient grandExchangeClient; - - public PriceListener(GrandExchangeClient grandExchangeClient) { - this.grandExchangeClient = grandExchangeClient; - } - - @Override - public void proces(MessageReceivedEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - String msg = event.getMessage().getContentRaw(); - try { - String itemName = msg.substring(msg.indexOf(" ")).trim(); - event.getChannel().sendTyping().queue(typing -> { - try { - String result = grandExchangeClient.getPrice(itemName, event.getChannel()); - embedBuilder.setTitle("Price of item"); - embedBuilder.setColor(Color.RED); - embedBuilder.addField(itemName, result, false); - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - } catch (EntityNotFoundException e) { - event.getChannel().sendMessage(e.getMessage()).queue(); - } - }); - } catch (StringIndexOutOfBoundsException e) { - event.getChannel().sendMessage("Please enter an item name after the command, separated by space.").queue(); - } - - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/PvmListListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/PvmListListener.java @@ -1,43 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.List; - -@Component -public class PvmListListener implements Listener { - - private final PvmRoleUserService pvmRoleUserService; - - public PvmListListener(PvmRoleUserService pvmRoleUserService) { - this.pvmRoleUserService = pvmRoleUserService; - } - - @Override - public void proces(MessageReceivedEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle("List of PvM Role competitors:"); - List<PvmRoleUser> pvmRoleUsers = pvmRoleUserService.findAll(); - int i = 1; - for (PvmRoleUser pvmRoleUser : pvmRoleUsers) { - embedBuilder.addField(pvmRoleUser.getDiscordName(), - String.format("RSN: %s", pvmRoleUser.getRsn()) + System.lineSeparator() + - String.format("||_Created by: %s - %s | Last edit: %s - %s_||", - pvmRoleUser.getCreatedBy(), pvmRoleUser.getCreatedDate(), pvmRoleUser.getLastModifiedBy(), pvmRoleUser.getLastModifiedDate()), - false); - if (JdaUtil.requiresBuild(embedBuilder, pvmRoleUsers.size(), i)) { - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clear(); - } - i++; - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/PvmRoleCheckListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/PvmRoleCheckListener.java @@ -1,33 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.services.OsrsMonitoringService; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class PvmRoleCheckListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(PvmRoleCheckListener.class); - private final OsrsMonitoringService osrsMonitoringService; - - public PvmRoleCheckListener(OsrsMonitoringService osrsMonitoringService) { - this.osrsMonitoringService = osrsMonitoringService; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - osrsMonitoringService.monitorPvmRoleUserHiscores(privateChannel); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/PvmRolePollListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/PvmRolePollListener.java @@ -1,33 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.services.PvMRoleResolver; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.exceptions.RateLimitedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class PvmRolePollListener implements Listener { - - private static final Logger LOGGER = LoggerFactory.getLogger(PvmRolePollListener.class); - private final PvMRoleResolver pvMRoleResolver; - - public PvmRolePollListener(PvMRoleResolver pvMRoleResolver) { - this.pvMRoleResolver = pvMRoleResolver; - } - - @Override - public void proces(MessageReceivedEvent event) { - if (event.getMember() != null) { - try { - PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); - pvMRoleResolver.resolvePvMRoles(false, privateChannel); - } catch (RateLimitedException e) { - LOGGER.error(e.getMessage(), e); - } - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/RuleListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/RuleListener.java @@ -1,45 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - - -import com.sxcy.sxcybot.enums.Command; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.services.guild.RuleService; -import com.sxcy.sxcybot.util.Constants.Commands; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.MessageChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; - - -@Component -public class RuleListener implements Listener { - - private final RuleService ruleService; - - public RuleListener(RuleService ruleService) { - this.ruleService = ruleService; - } - - @Override - public void proces(MessageReceivedEvent event) { - MessageChannel channel = event.getChannel(); - int ruleNumber; - String description; - try { - ruleNumber = Integer.parseInt(event.getMessage().getContentRaw().substring(Commands.COMMAND_PREFIX.length() + Command.RULE.name().length() + 1)); - description = ruleService.findByNumber(ruleNumber).getDescription(); - } catch (NumberFormatException | EntityNotFoundException e) { - channel.sendMessage(e.getMessage()).queue(); - return; - } - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.RED); - embedBuilder.setTitle("Show rule result"); - embedBuilder.addField(String.format("Rule #%s", ruleNumber), description, false); - channel.sendMessageEmbeds(embedBuilder.build()).queue(); - } - -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/RulesListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/RulesListener.java @@ -1,41 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.repository.guild.dao.Rule; -import com.sxcy.sxcybot.services.guild.RuleService; -import com.sxcy.sxcybot.util.JdaUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.Comparator; -import java.util.List; - -@Component -public class RulesListener implements Listener { - - private final RuleService ruleService; - - public RulesListener(RuleService ruleService) { - this.ruleService = ruleService; - } - - @Override - public void proces(MessageReceivedEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle(String.format("List of %s rules:", event.getGuild().getName())); - List<Rule> ruleList = ruleService.findAll(); - ruleList.sort(Comparator.comparing(Rule::getNumber)); - int i = 1; - for (Rule rule : ruleList) { - embedBuilder.addField(String.format("Rule #%s", rule.getNumber()), rule.getDescription(), false); - if (JdaUtil.requiresBuild(embedBuilder, ruleList.size(), i)) { - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - embedBuilder.clear(); - } - i++; - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/listeners/member/StatsListener.java b/src/main/java/com/sxcy/sxcybot/listeners/member/StatsListener.java @@ -1,31 +0,0 @@ -package com.sxcy.sxcybot.listeners.member; - -import com.sxcy.sxcybot.listeners.Listener; -import com.sxcy.sxcybot.services.osrs.StatMessageSender; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.util.Objects; - -@Component -public class StatsListener implements Listener { - - private final StatMessageSender statMessageSender; - - public StatsListener(StatMessageSender statMessageSender) { - this.statMessageSender = statMessageSender; - } - - @Override - public void proces(MessageReceivedEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - event.getChannel().sendTyping().queue(e -> - statMessageSender.sendStatMessage(event, embedBuilder, Objects::nonNull, - f -> embedBuilder.addField(f.name(), - "Level " + f.level() + System.lineSeparator() + - "Rank " + f.rank() + System.lineSeparator() + - "Exp " + f.experience(), true), null - )); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/model/CombatDto.java b/src/main/java/com/sxcy/sxcybot/model/CombatDto.java @@ -1,130 +0,0 @@ -package com.sxcy.sxcybot.model; - -import java.util.List; - -import static com.sxcy.sxcybot.enums.OsrsCombatStat.ATTACK; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.DEFENCE; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.HITPOINTS; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.MAGIC; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.PRAYER; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.RANGED; -import static com.sxcy.sxcybot.enums.OsrsCombatStat.STRENGTH; - -public record CombatDto( - int attackLevel, - int strengthLevel, - int defenceLevel, - int hitpointsLevel, - int magicLevel, - int rangeLevel, - int prayerLevel -) { - - - private CombatDto(Builder builder) { - this(builder.attackLevel, - builder.strengthLevel, - builder.defenceLevel, - builder.hitpointsLevel, - builder.magicLevel, - builder.rangeLevel, - builder.prayerLevel); - } - - public static CombatDto build(List<OsrsStat> osrsStatList) { - CombatDto.Builder builder = CombatDto.Builder.newBuilder(); - for (OsrsStat osrsStat : osrsStatList) { - if (ATTACK.value.equalsIgnoreCase(osrsStat.name())) { - builder.attackLevel(Integer.parseInt(osrsStat.level())); - } - if (STRENGTH.value.equalsIgnoreCase(osrsStat.name())) { - builder.strengthLevel(Integer.parseInt(osrsStat.level())); - } - if (DEFENCE.value.equalsIgnoreCase(osrsStat.name())) { - builder.defenceLevel(Integer.parseInt(osrsStat.level())); - } - if (HITPOINTS.value.equalsIgnoreCase(osrsStat.name())) { - builder.hitpointsLevel(Integer.parseInt(osrsStat.level())); - } - if (MAGIC.value.equalsIgnoreCase(osrsStat.name())) { - builder.magicLevel(Integer.parseInt(osrsStat.level())); - } - if (RANGED.value.equalsIgnoreCase(osrsStat.name())) { - builder.rangeLevel(Integer.parseInt(osrsStat.level())); - } - if (PRAYER.value.equalsIgnoreCase(osrsStat.name())) { - builder.prayerLevel(Integer.parseInt(osrsStat.level())); - } - } - return builder.build(); - } - - public static final class Builder { - private int attackLevel; - private int strengthLevel; - private int defenceLevel; - private int hitpointsLevel; - private int magicLevel; - private int rangeLevel; - private int prayerLevel; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder attackLevel(int val) { - attackLevel = val; - return this; - } - - public Builder strengthLevel(int val) { - strengthLevel = val; - return this; - } - - public Builder defenceLevel(int val) { - defenceLevel = val; - return this; - } - - public Builder hitpointsLevel(int val) { - hitpointsLevel = val; - return this; - } - - public Builder magicLevel(int val) { - magicLevel = val; - return this; - } - - public Builder rangeLevel(int val) { - rangeLevel = val; - return this; - } - - public Builder prayerLevel(int val) { - prayerLevel = val; - return this; - } - - public CombatDto build() { - return new CombatDto(this); - } - } - - @Override - public String toString() { - return "CombatDto{" + - "attackLevel=" + attackLevel + - ", strengthLevel=" + strengthLevel + - ", defenceLevel=" + defenceLevel + - ", hitpointsLevel=" + hitpointsLevel + - ", magicLevel=" + magicLevel + - ", rangeLevel=" + rangeLevel + - ", prayerLevel=" + prayerLevel + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/model/EditListenerDto.java b/src/main/java/com/sxcy/sxcybot/model/EditListenerDto.java @@ -1,93 +0,0 @@ -package com.sxcy.sxcybot.model; - -import com.sxcy.sxcybot.listeners.PrivateListener; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.jetbrains.annotations.NotNull; - -public record EditListenerDto( - @NotNull - PrivateListener addListener, - PrivateListener updateListener, - @NotNull - PrivateListener deleteListener, - @NotNull - MessageReceivedEvent event, - @NotNull - PrivateChannel privateChannel, - @NotNull - String entityName -) { - - - private EditListenerDto(Builder builder) { - this(builder.addListener, - builder.updateListener, - builder.deleteListener, - builder.event, - builder.privateChannel, - builder.entityName); - } - - public static final class Builder { - private @NotNull PrivateListener addListener; - private PrivateListener updateListener; - private @NotNull PrivateListener deleteListener; - private @NotNull MessageReceivedEvent event; - private @NotNull PrivateChannel privateChannel; - private @NotNull String entityName; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder addListener(@NotNull PrivateListener val) { - addListener = val; - return this; - } - - public Builder updateListener(PrivateListener val) { - updateListener = val; - return this; - } - - public Builder deleteListener(@NotNull PrivateListener val) { - deleteListener = val; - return this; - } - - public Builder event(@NotNull MessageReceivedEvent val) { - event = val; - return this; - } - - public Builder privateChannel(@NotNull PrivateChannel val) { - privateChannel = val; - return this; - } - - public Builder entityName(@NotNull String val) { - entityName = val; - return this; - } - - public EditListenerDto build() { - return new EditListenerDto(this); - } - } - - @Override - public String toString() { - return "EditListenerDto{" + - "addListener=" + addListener + - ", updateListener=" + updateListener + - ", deleteListener=" + deleteListener + - ", event=" + event + - ", privateChannel=" + privateChannel + - ", entityName='" + entityName + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/model/HiScoreBuilder.java b/src/main/java/com/sxcy/sxcybot/model/HiScoreBuilder.java @@ -1,11 +0,0 @@ -package com.sxcy.sxcybot.model; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; - -import java.util.List; - -@FunctionalInterface -public interface HiScoreBuilder<T> { - - T accept(String string, List<String> stringList, int i) throws EntityNotFoundException; -} diff --git a/src/main/java/com/sxcy/sxcybot/model/OsrsBossKc.java b/src/main/java/com/sxcy/sxcybot/model/OsrsBossKc.java @@ -1,56 +0,0 @@ -package com.sxcy.sxcybot.model; - -public record OsrsBossKc( - String name, - String rank, - String kc - -) { - - private OsrsBossKc(Builder builder) { - this(builder.name, - builder.rank, - builder.kc); - } - - public static final class Builder { - private String name; - private String rank; - private String kc; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder name(String val) { - name = val; - return this; - } - - public Builder rank(String val) { - rank = val; - return this; - } - - public Builder kc(String val) { - kc = val; - return this; - } - - public OsrsBossKc build() { - return new OsrsBossKc(this); - } - } - - @Override - public String toString() { - return "OsrsBossKc{" + - "name='" + name + '\'' + - ", rank='" + rank + '\'' + - ", kc='" + kc + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/model/OsrsItem.java b/src/main/java/com/sxcy/sxcybot/model/OsrsItem.java @@ -1,64 +0,0 @@ -package com.sxcy.sxcybot.model; - -public record OsrsItem( - String id, - String timestamp, - Integer price, - String volume -) { - - private OsrsItem(Builder builder) { - this(builder.id, - builder.timestamp, - builder.price, - builder.volume); - } - - public static final class Builder { - private String id; - private String timestamp; - private Integer price; - private String volume; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder timestamp(String val) { - timestamp = val; - return this; - } - - public Builder price(Integer val) { - price = val; - return this; - } - - public Builder volume(String val) { - volume = val; - return this; - } - - public OsrsItem build() { - return new OsrsItem(this); - } - } - - @Override - public String toString() { - return "OsrsItem{" + - "id='" + id + '\'' + - ", timestamp='" + timestamp + '\'' + - ", price=" + price + - ", volume='" + volume + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/model/OsrsStat.java b/src/main/java/com/sxcy/sxcybot/model/OsrsStat.java @@ -1,65 +0,0 @@ -package com.sxcy.sxcybot.model; - -public record OsrsStat( - String name, - String experience, - String rank, - String level -) { - - - private OsrsStat(Builder builder) { - this(builder.name, - builder.experience, - builder.rank, - builder.level); - } - - public static final class Builder { - private String name; - private String experience; - private String rank; - private String level; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder name(String val) { - name = val; - return this; - } - - public Builder experience(String val) { - experience = val; - return this; - } - - public Builder rank(String val) { - rank = val; - return this; - } - - public Builder level(String val) { - level = val; - return this; - } - - public OsrsStat build() { - return new OsrsStat(this); - } - } - - @Override - public String toString() { - return "OsrsStat{" + - "name='" + name + '\'' + - ", experience='" + experience + '\'' + - ", rank='" + rank + '\'' + - ", level='" + level + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/ChannelDetailRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/ChannelDetailRepository.java @@ -1,9 +0,0 @@ -package com.sxcy.sxcybot.repository.guild; - -import com.sxcy.sxcybot.repository.guild.dao.ChannelDetail; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface ChannelDetailRepository extends JpaRepository<ChannelDetail, String> { -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/GuildEventDmerRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/GuildEventDmerRepository.java @@ -1,9 +0,0 @@ -package com.sxcy.sxcybot.repository.guild; - -import com.sxcy.sxcybot.repository.guild.dao.GuildEventDmer; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface GuildEventDmerRepository extends JpaRepository<GuildEventDmer, String> { -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/GuildRoleRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/GuildRoleRepository.java @@ -1,18 +0,0 @@ -package com.sxcy.sxcybot.repository.guild; - -import com.sxcy.sxcybot.repository.guild.dao.GuildRole; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; -import java.util.Optional; - -@Repository -public interface GuildRoleRepository extends JpaRepository<GuildRole, String> { - - List<GuildRole> findByElevationLessThanEqual(Integer elevation); - - List<GuildRole> findByElevationGreaterThanEqual(Integer elevation); - - Optional<GuildRole> findByName(String name); -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/PollRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/PollRepository.java @@ -1,13 +0,0 @@ -package com.sxcy.sxcybot.repository.guild; - -import com.sxcy.sxcybot.repository.guild.dao.Poll; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; - -@Repository -public interface PollRepository extends JpaRepository<Poll, String> { - - Optional<Poll> findByMessageId(String messageId); -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/RuleRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/RuleRepository.java @@ -1,14 +0,0 @@ -package com.sxcy.sxcybot.repository.guild; - -import com.sxcy.sxcybot.repository.guild.dao.Rule; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; - -@Repository -public interface RuleRepository extends JpaRepository<Rule, String> { - - Optional<Rule> findByNumber(int number); - -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/UserRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/UserRepository.java @@ -1,16 +0,0 @@ -package com.sxcy.sxcybot.repository.guild; - -import com.sxcy.sxcybot.repository.guild.dao.User; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; -import java.util.Optional; - -@Repository -public interface UserRepository extends JpaRepository<User, String> { - - Optional<User> findByName(String name); - - List<User> findAllByBannedTrue(); -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/dao/ChannelDetail.java b/src/main/java/com/sxcy/sxcybot/repository/guild/dao/ChannelDetail.java @@ -1,158 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; - -@Entity -public class ChannelDetail { - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - private String forumUrl; - private String botUpdateChannel; - private String pvmRoleChannel; - private String pvmRoleGeneral; - private String pvmRoleRaids; - private String pvmRoleWilderness; - - protected ChannelDetail() { - } - - private ChannelDetail(Builder builder) { - setId(builder.id); - setForumUrl(builder.forumUrl); - setBotUpdateChannel(builder.botUpdateChannel); - setPvmRoleChannel(builder.pvmRoleChannel); - setPvmRoleGeneral(builder.pvmRoleGeneral); - setPvmRoleRaids(builder.pvmRoleRaids); - setPvmRoleWilderness(builder.pvmRoleWilderness); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getForumUrl() { - return forumUrl; - } - - public void setForumUrl(String forumUrl) { - this.forumUrl = forumUrl; - } - - public String getBotUpdateChannel() { - return botUpdateChannel; - } - - public void setBotUpdateChannel(String botUpdateChannel) { - this.botUpdateChannel = botUpdateChannel; - } - - public String getPvmRoleChannel() { - return pvmRoleChannel; - } - - public void setPvmRoleChannel(String pvmRoleChannel) { - this.pvmRoleChannel = pvmRoleChannel; - } - - public String getPvmRoleGeneral() { - return pvmRoleGeneral; - } - - public void setPvmRoleGeneral(String pvmRoleGeneral) { - this.pvmRoleGeneral = pvmRoleGeneral; - } - - public String getPvmRoleRaids() { - return pvmRoleRaids; - } - - public void setPvmRoleRaids(String pvmRoleRaids) { - this.pvmRoleRaids = pvmRoleRaids; - } - - public String getPvmRoleWilderness() { - return pvmRoleWilderness; - } - - public void setPvmRoleWilderness(String pvmRoleWilderness) { - this.pvmRoleWilderness = pvmRoleWilderness; - } - - public static final class Builder { - private String id; - private String forumUrl; - private String botUpdateChannel; - private String pvmRoleChannel; - private String pvmRoleGeneral; - private String pvmRoleRaids; - private String pvmRoleWilderness; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder forumUrl(String val) { - forumUrl = val; - return this; - } - - public Builder botUpdateChannel(String val) { - botUpdateChannel = val; - return this; - } - - public Builder pvmRoleChannel(String val) { - pvmRoleChannel = val; - return this; - } - - public Builder pvmRoleGeneral(String val) { - pvmRoleGeneral = val; - return this; - } - - public Builder pvmRoleRaids(String val) { - pvmRoleRaids = val; - return this; - } - - public Builder pvmRoleWilderness(String val) { - pvmRoleWilderness = val; - return this; - } - - public ChannelDetail build() { - return new ChannelDetail(this); - } - } - - @Override - public String toString() { - return "ChannelDetail{" + - "id='" + id + '\'' + - ", forumUrl='" + forumUrl + '\'' + - ", botUpdateChannel='" + botUpdateChannel + '\'' + - ", pvmRoleChannel='" + pvmRoleChannel + '\'' + - ", pvmRoleGeneral='" + pvmRoleGeneral + '\'' + - ", pvmRoleRaids='" + pvmRoleRaids + '\'' + - ", pvmRoleWilderness='" + pvmRoleWilderness + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/dao/Event.java b/src/main/java/com/sxcy/sxcybot/repository/guild/dao/Event.java @@ -1,85 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.dao; - -import java.time.LocalDate; - -public class Event { - - private String name; - private String description; - private LocalDate time; - - protected Event() { - - } - - private Event(Builder builder) { - setName(builder.name); - setDescription(builder.description); - setTime(builder.time); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public LocalDate getTime() { - return time; - } - - public void setTime(LocalDate time) { - this.time = time; - } - - public static final class Builder { - private String name; - private String description; - private LocalDate time; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder name(String val) { - name = val; - return this; - } - - public Builder description(String val) { - description = val; - return this; - } - - public Builder time(LocalDate val) { - time = val; - return this; - } - - public Event build() { - return new Event(this); - } - } - - @Override - public String toString() { - return "Event{" + - "name='" + name + '\'' + - ", description='" + description + '\'' + - ", time=" + time + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/dao/GuildEventDmer.java b/src/main/java/com/sxcy/sxcybot/repository/guild/dao/GuildEventDmer.java @@ -1,75 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; - - -@Entity -public class GuildEventDmer { - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - - private String name; - - private GuildEventDmer(Builder builder) { - setId(builder.id); - setName(builder.name); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - protected GuildEventDmer() { - } - - public static final class Builder { - private String id; - private String name; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder name(String val) { - name = val; - return this; - } - - public GuildEventDmer build() { - return new GuildEventDmer(this); - } - } - - @Override - public String toString() { - return "GuildEventDmer{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/dao/GuildRole.java b/src/main/java/com/sxcy/sxcybot/repository/guild/dao/GuildRole.java @@ -1,109 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; - - -@Entity -public class GuildRole { - - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - private String name; - private Integer orderValue; - private int elevation; - - protected GuildRole() { - } - - private GuildRole(Builder builder) { - setId(builder.id); - setName(builder.name); - setOrderValue(builder.orderValue); - setElevation(builder.elevation); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getOrderValue() { - return orderValue; - } - - public void setOrderValue(Integer orderValue) { - this.orderValue = orderValue; - } - - public int getElevation() { - return elevation; - } - - public void setElevation(int elevation) { - this.elevation = elevation; - } - - public static final class Builder { - private String id; - private String name; - private Integer orderValue; - private int elevation; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder name(String val) { - name = val; - return this; - } - - public Builder orderValue(Integer val) { - orderValue = val; - return this; - } - - public Builder elevation(int val) { - elevation = val; - return this; - } - - public GuildRole build() { - return new GuildRole(this); - } - } - - @Override - public String toString() { - return "GuildRole{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", orderValue=" + orderValue + - ", elevation=" + elevation + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/dao/Poll.java b/src/main/java/com/sxcy/sxcybot/repository/guild/dao/Poll.java @@ -1,118 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.EntityListeners; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import java.time.LocalDateTime; - -@Entity -@EntityListeners(AuditingEntityListener.class) -public class Poll { - - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - - private String messageId; - @CreatedDate - private LocalDateTime createdDate; - @LastModifiedDate - private LocalDateTime lastModifiedDate; - - protected Poll() { - } - - private Poll(Builder builder) { - setId(builder.id); - setMessageId(builder.messageId); - setCreatedDate(builder.createdDate); - setLastModifiedDate(builder.lastModifiedDate); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getMessageId() { - return messageId; - } - - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - public LocalDateTime getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(LocalDateTime createdDate) { - this.createdDate = createdDate; - } - - public LocalDateTime getLastModifiedDate() { - return lastModifiedDate; - } - - public void setLastModifiedDate(LocalDateTime lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } - - public static final class Builder { - private String id; - private String messageId; - private LocalDateTime createdDate; - private LocalDateTime lastModifiedDate; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder messageId(String val) { - messageId = val; - return this; - } - - public Builder createdDate(LocalDateTime val) { - createdDate = val; - return this; - } - - public Builder lastModifiedDate(LocalDateTime val) { - lastModifiedDate = val; - return this; - } - - public Poll build() { - return new Poll(this); - } - } - - @Override - public String toString() { - return "Poll{" + - "id='" + id + '\'' + - ", messageId='" + messageId + '\'' + - ", createdDate=" + createdDate + - ", lastModifiedDate=" + lastModifiedDate + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/dao/Rule.java b/src/main/java/com/sxcy/sxcybot/repository/guild/dao/Rule.java @@ -1,93 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; - -@Entity -public class Rule { - - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - - private int number; - - private String description; - - protected Rule() { - } - - private Rule(Builder builder) { - setId(builder.id); - setNumber(builder.number); - setDescription(builder.description); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public int getNumber() { - return number; - } - - public void setNumber(int number) { - this.number = number; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public static final class Builder { - private String id; - private int number; - private String description; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder number(int val) { - number = val; - return this; - } - - public Builder description(String val) { - description = val; - return this; - } - - public Rule build() { - return new Rule(this); - } - } - - @Override - public String toString() { - return "Rule{" + - "id='" + id + '\'' + - ", number=" + number + - ", description='" + description + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/dao/User.java b/src/main/java/com/sxcy/sxcybot/repository/guild/dao/User.java @@ -1,185 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.EntityListeners; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import java.time.LocalDate; - -@Entity -@EntityListeners(AuditingEntityListener.class) -public class User { - - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - private String name; - private String description; - private boolean banned; - @CreatedDate - private LocalDate createdDate; - private String createdBy; - @LastModifiedDate - private LocalDate lastModifiedDate; - private String lastModifiedBy; - - protected User() { - } - - private User(Builder builder) { - setId(builder.id); - setName(builder.name); - setDescription(builder.description); - setBanned(builder.banned); - setCreatedDate(builder.createdDate); - setCreatedBy(builder.createdBy); - setLastModifiedDate(builder.lastModifiedDate); - setLastModifiedBy(builder.lastModifiedBy); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public boolean isBanned() { - return banned; - } - - public void setBanned(boolean banned) { - this.banned = banned; - } - - public LocalDate getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(LocalDate createdDate) { - this.createdDate = createdDate; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public LocalDate getLastModifiedDate() { - return lastModifiedDate; - } - - public void setLastModifiedDate(LocalDate lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } - - public String getLastModifiedBy() { - return lastModifiedBy; - } - - public void setLastModifiedBy(String lastModifiedBy) { - this.lastModifiedBy = lastModifiedBy; - } - - public static final class Builder { - private String id; - private String name; - private String description; - private boolean banned; - private LocalDate createdDate; - private String createdBy; - private LocalDate lastModifiedDate; - private String lastModifiedBy; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder name(String val) { - name = val; - return this; - } - - public Builder description(String val) { - description = val; - return this; - } - - public Builder banned(boolean val) { - banned = val; - return this; - } - - public Builder createdDate(LocalDate val) { - createdDate = val; - return this; - } - - public Builder createdBy(String val) { - createdBy = val; - return this; - } - - public Builder lastModifiedDate(LocalDate val) { - lastModifiedDate = val; - return this; - } - - public Builder lastModifiedBy(String val) { - lastModifiedBy = val; - return this; - } - - public User build() { - return new User(this); - } - } - - @Override - public String toString() { - return "User{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", description='" + description + '\'' + - ", banned=" + banned + - ", createdDate=" + createdDate + - ", createdBy='" + createdBy + '\'' + - ", lastModifiedDate=" + lastModifiedDate + - ", lastModifiedBy='" + lastModifiedBy + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/PvmKcSnapshotRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/PvmKcSnapshotRepository.java @@ -1,14 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.pvmrole; - -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface PvmKcSnapshotRepository extends JpaRepository<PvmKcSnapshot, String> { - - List<PvmKcSnapshot> findAllByPvmRoleUserId(String PvmRoleUserId); - -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java b/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java @@ -1,13 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.pvmrole; - -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; - -@Repository -public interface PvmRoleUserRepository extends JpaRepository<PvmRoleUser, String> { - - Optional<PvmRoleUser> findByDiscordName(String discordName); -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmKcSnapshot.java b/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmKcSnapshot.java @@ -1,148 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.pvmrole.dao; - -import jakarta.persistence.CascadeType; -import jakarta.persistence.Entity; -import jakarta.persistence.EntityListeners; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.OneToMany; -import org.hibernate.annotations.GenericGenerator; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -@Entity -@EntityListeners(AuditingEntityListener.class) -public class PvmKcSnapshot { - - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - - @ManyToOne - @JoinColumn(name = "pvm_role_user_id") - private PvmRoleUser pvmRoleUser; - - @OneToMany(mappedBy = "pvmKcSnapshot", cascade = CascadeType.ALL, orphanRemoval = true) - private List<PvmUserKc> pvmUserKcList = new ArrayList<>(); - - @CreatedDate - private LocalDateTime createdDate; - @LastModifiedDate - private LocalDateTime lastModifiedDate; - - protected PvmKcSnapshot() { - - } - - private PvmKcSnapshot(Builder builder) { - setId(builder.id); - setPvmRoleUser(builder.pvmRoleUser); - setPvmUserKcList(builder.pvmUserKcList); - setCreatedDate(builder.createdDate); - setLastModifiedDate(builder.lastModifiedDate); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public PvmRoleUser getPvmRoleUser() { - return pvmRoleUser; - } - - public void setPvmRoleUser(PvmRoleUser pvmRoleUser) { - this.pvmRoleUser = pvmRoleUser; - } - - public List<PvmUserKc> getPvmUserKcList() { - return pvmUserKcList; - } - - public void setPvmUserKcList(List<PvmUserKc> pvmUserKcList) { - this.pvmUserKcList = pvmUserKcList; - } - - public LocalDateTime getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(LocalDateTime createdDate) { - this.createdDate = createdDate; - } - - public LocalDateTime getLastModifiedDate() { - return lastModifiedDate; - } - - public void setLastModifiedDate(LocalDateTime lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } - - - public static final class Builder { - private String id; - private PvmRoleUser pvmRoleUser; - private List<PvmUserKc> pvmUserKcList; - private LocalDateTime createdDate; - private LocalDateTime lastModifiedDate; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder pvmRoleUser(PvmRoleUser val) { - pvmRoleUser = val; - return this; - } - - public Builder pvmUserKcList(List<PvmUserKc> val) { - pvmUserKcList = val; - return this; - } - - public Builder createdDate(LocalDateTime val) { - createdDate = val; - return this; - } - - public Builder lastModifiedDate(LocalDateTime val) { - lastModifiedDate = val; - return this; - } - - public PvmKcSnapshot build() { - return new PvmKcSnapshot(this); - } - } - - @Override - public String toString() { - return "PvmKcSnapshot{" + - "id='" + id + '\'' + - ", pvmRoleUser=" + pvmRoleUser + - ", pvmUserKcList=" + pvmUserKcList + - ", createdDate=" + createdDate + - ", lastModifiedDate=" + lastModifiedDate + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java b/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java @@ -1,169 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.pvmrole.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.EntityListeners; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import java.time.LocalDateTime; - -@Entity -@EntityListeners(AuditingEntityListener.class) -public class PvmRoleUser { - - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - private String discordName; - private String rsn; - @CreatedDate - private LocalDateTime createdDate; - private String createdBy; - @LastModifiedDate - private LocalDateTime lastModifiedDate; - private String lastModifiedBy; - - protected PvmRoleUser() { - - } - - private PvmRoleUser(Builder builder) { - setId(builder.id); - setDiscordName(builder.discordName); - setRsn(builder.rsn); - setCreatedDate(builder.createdDate); - setCreatedBy(builder.createdBy); - setLastModifiedDate(builder.lastModifiedDate); - setLastModifiedBy(builder.lastModifiedBy); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getDiscordName() { - return discordName; - } - - public void setDiscordName(String discordName) { - this.discordName = discordName; - } - - public String getRsn() { - return rsn; - } - - public void setRsn(String rsn) { - this.rsn = rsn; - } - - public LocalDateTime getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(LocalDateTime createdDate) { - this.createdDate = createdDate; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public LocalDateTime getLastModifiedDate() { - return lastModifiedDate; - } - - public void setLastModifiedDate(LocalDateTime lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } - - public String getLastModifiedBy() { - return lastModifiedBy; - } - - public void setLastModifiedBy(String lastModifiedBy) { - this.lastModifiedBy = lastModifiedBy; - } - - public static final class Builder { - private String id; - private String discordName; - private String rsn; - private LocalDateTime createdDate; - private String createdBy; - private LocalDateTime lastModifiedDate; - private String lastModifiedBy; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder discordName(String val) { - discordName = val; - return this; - } - - public Builder rsn(String val) { - rsn = val; - return this; - } - - public Builder createdDate(LocalDateTime val) { - createdDate = val; - return this; - } - - public Builder createdBy(String val) { - createdBy = val; - return this; - } - - public Builder lastModifiedDate(LocalDateTime val) { - lastModifiedDate = val; - return this; - } - - public Builder lastModifiedBy(String val) { - lastModifiedBy = val; - return this; - } - - public PvmRoleUser build() { - return new PvmRoleUser(this); - } - } - - @Override - public String toString() { - return "PvmRoleUser{" + - "id='" + id + '\'' + - ", discordName='" + discordName + '\'' + - ", rsn='" + rsn + '\'' + - ", createdDate=" + createdDate + - ", createdBy='" + createdBy + '\'' + - ", lastModifiedDate=" + lastModifiedDate + - ", lastModifiedBy='" + lastModifiedBy + '\'' + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmUserKc.java b/src/main/java/com/sxcy/sxcybot/repository/guild/pvmrole/dao/PvmUserKc.java @@ -1,184 +0,0 @@ -package com.sxcy.sxcybot.repository.guild.pvmrole.dao; - -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; -import jakarta.persistence.Entity; -import jakarta.persistence.EntityListeners; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.OneToOne; -import org.hibernate.annotations.GenericGenerator; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import java.time.LocalDateTime; - -@Entity -@EntityListeners(AuditingEntityListener.class) -public class PvmUserKc { - - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - - @OneToOne - @JoinColumn(name = "pvm_role_user_id") - private PvmRoleUser pvmRoleUser; - - @OneToOne - @JoinColumn(name = "osrs_hiscore_boss_id") - private OsrsHiscoreBoss osrsHiscoreBoss; - - private Integer kc; - - @ManyToOne - @JoinColumn(name = "pvm_kc_snapshot_id") - private PvmKcSnapshot pvmKcSnapshot; - - @CreatedDate - private LocalDateTime createdDate; - @LastModifiedDate - private LocalDateTime lastModifiedDate; - - protected PvmUserKc() { - - } - - private PvmUserKc(Builder builder) { - setId(builder.id); - setPvmRoleUser(builder.pvmRoleUser); - setOsrsHiscoreBoss(builder.osrsHiscoreBoss); - setKc(builder.kc); - setPvmKcSnapshot(builder.pvmKcSnapshot); - setCreatedDate(builder.createdDate); - setLastModifiedDate(builder.lastModifiedDate); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public PvmRoleUser getPvmRoleUser() { - return pvmRoleUser; - } - - public void setPvmRoleUser(PvmRoleUser pvmRoleUser) { - this.pvmRoleUser = pvmRoleUser; - } - - public OsrsHiscoreBoss getOsrsHiscoreBoss() { - return osrsHiscoreBoss; - } - - public void setOsrsHiscoreBoss(OsrsHiscoreBoss osrsHiscoreBoss) { - this.osrsHiscoreBoss = osrsHiscoreBoss; - } - - public Integer getKc() { - return kc; - } - - public void setKc(Integer kc) { - this.kc = kc; - } - - public PvmKcSnapshot getPvmKcSnapshot() { - return pvmKcSnapshot; - } - - public void setPvmKcSnapshot(PvmKcSnapshot pvmKcSnapshot) { - this.pvmKcSnapshot = pvmKcSnapshot; - } - - public LocalDateTime getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(LocalDateTime createdDate) { - this.createdDate = createdDate; - } - - public LocalDateTime getLastModifiedDate() { - return lastModifiedDate; - } - - public void setLastModifiedDate(LocalDateTime lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } - - public static final class Builder { - private String id; - private PvmRoleUser pvmRoleUser; - private OsrsHiscoreBoss osrsHiscoreBoss; - private Integer kc; - private PvmKcSnapshot pvmKcSnapshot; - private LocalDateTime createdDate; - private LocalDateTime lastModifiedDate; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder pvmRoleUser(PvmRoleUser val) { - pvmRoleUser = val; - return this; - } - - public Builder osrsHiscoreBoss(OsrsHiscoreBoss val) { - osrsHiscoreBoss = val; - return this; - } - - public Builder kc(Integer val) { - kc = val; - return this; - } - - public Builder pvmKcSnapshot(PvmKcSnapshot val) { - pvmKcSnapshot = val; - return this; - } - - public Builder createdDate(LocalDateTime val) { - createdDate = val; - return this; - } - - public Builder lastModifiedDate(LocalDateTime val) { - lastModifiedDate = val; - return this; - } - - public PvmUserKc build() { - return new PvmUserKc(this); - } - } - - @Override - public String toString() { - return "PvmUserKc{" + - "id='" + id + '\'' + - ", pvmRoleUser=" + pvmRoleUser + - ", osrsHiscoreBoss=" + osrsHiscoreBoss + - ", kc=" + kc + - ", pvmKcSnapshot=" + pvmKcSnapshot + - ", createdDate=" + createdDate + - ", lastModifiedDate=" + lastModifiedDate + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/osrs/OsrsHiscoreBossRepository.java b/src/main/java/com/sxcy/sxcybot/repository/osrs/OsrsHiscoreBossRepository.java @@ -1,13 +0,0 @@ -package com.sxcy.sxcybot.repository.osrs; - -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; - -@Repository -public interface OsrsHiscoreBossRepository extends JpaRepository<OsrsHiscoreBoss, String> { - - Optional<OsrsHiscoreBoss> findByName(String name); -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/osrs/OsrsHiscoreStatRepository.java b/src/main/java/com/sxcy/sxcybot/repository/osrs/OsrsHiscoreStatRepository.java @@ -1,9 +0,0 @@ -package com.sxcy.sxcybot.repository.osrs; - -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreStat; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface OsrsHiscoreStatRepository extends JpaRepository<OsrsHiscoreStat, String> { -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/osrs/dao/OsrsHiscoreBoss.java b/src/main/java/com/sxcy/sxcybot/repository/osrs/dao/OsrsHiscoreBoss.java @@ -1,126 +0,0 @@ -package com.sxcy.sxcybot.repository.osrs.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; - - -@Entity -public class OsrsHiscoreBoss { - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - private String name; - private int orderValue; - private double multiplier; - private int pvmRole; - - protected OsrsHiscoreBoss() { - - } - - private OsrsHiscoreBoss(Builder builder) { - setId(builder.id); - setName(builder.name); - setOrderValue(builder.orderValue); - setMultiplier(builder.multiplier); - setPvmRole(builder.pvmRole); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getOrderValue() { - return orderValue; - } - - public void setOrderValue(int orderValue) { - this.orderValue = orderValue; - } - - public double getMultiplier() { - return multiplier; - } - - public void setMultiplier(double multiplier) { - this.multiplier = multiplier; - } - - public int getPvmRole() { - return pvmRole; - } - - public void setPvmRole(int pvmRole) { - this.pvmRole = pvmRole; - } - - public static final class Builder { - private String id; - private String name; - private int orderValue; - private double multiplier; - private int pvmRole; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder name(String val) { - name = val; - return this; - } - - public Builder orderValue(int val) { - orderValue = val; - return this; - } - - public Builder multiplier(double val) { - multiplier = val; - return this; - } - - public Builder pvmRole(int val) { - pvmRole = val; - return this; - } - - public OsrsHiscoreBoss build() { - return new OsrsHiscoreBoss(this); - } - } - - @Override - public String toString() { - return "OsrsHiscoreBoss{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", orderValue=" + orderValue + - ", multiplier=" + multiplier + - ", pvmRole=" + pvmRole + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/repository/osrs/dao/OsrsHiscoreStat.java b/src/main/java/com/sxcy/sxcybot/repository/osrs/dao/OsrsHiscoreStat.java @@ -1,93 +0,0 @@ -package com.sxcy.sxcybot.repository.osrs.dao; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import org.hibernate.annotations.GenericGenerator; - - -@Entity -public class OsrsHiscoreStat { - @Id - @GeneratedValue(generator = "uuid") - @GenericGenerator(name = "uuid", strategy = "uuid") - private String id; - private String name; - private int orderValue; - - protected OsrsHiscoreStat() { - - } - - private OsrsHiscoreStat(Builder builder) { - setId(builder.id); - setName(builder.name); - setOrderValue(builder.orderValue); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getOrderValue() { - return orderValue; - } - - public void setOrderValue(int orderValue) { - this.orderValue = orderValue; - } - - - public static final class Builder { - private String id; - private String name; - private int orderValue; - - private Builder() { - } - - public static Builder newBuilder() { - return new Builder(); - } - - public Builder id(String val) { - id = val; - return this; - } - - public Builder name(String val) { - name = val; - return this; - } - - public Builder orderValue(int val) { - orderValue = val; - return this; - } - - public OsrsHiscoreStat build() { - return new OsrsHiscoreStat(this); - } - } - - @Override - public String toString() { - return "OsrsHiscoreStat{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", orderValue=" + orderValue + - '}'; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/CleanupScheduler.java b/src/main/java/com/sxcy/sxcybot/services/CleanupScheduler.java @@ -1,62 +0,0 @@ -package com.sxcy.sxcybot.services; - -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.services.guild.PollService; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmKcSnapshotService; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.Comparator; -import java.util.List; - -@Component -public class CleanupScheduler { - - private static final Logger LOGGER = LoggerFactory.getLogger(CleanupScheduler.class); - private static final int POLL_DAYS_VALID = 60; - private final PvmKcSnapshotService pvmKcSnapshotService; - private final PvmRoleUserService pvmRoleUserService; - private final PollService pollService; - - public CleanupScheduler(PvmKcSnapshotService pvmKcSnapshotService, - PvmRoleUserService pvmRoleUserService, - PollService pollService) { - this.pvmKcSnapshotService = pvmKcSnapshotService; - this.pvmRoleUserService = pvmRoleUserService; - this.pollService = pollService; - } - - @Scheduled(cron = "${db.cleanup.schedule}") - @SuppressWarnings("unused") - public void cleanup() { - cleanupPvmKcSnapshots(); - cleanupPolls(); - } - - private void cleanupPvmKcSnapshots() { - List<PvmKcSnapshot> pvmKcSnapshotList; - for (PvmRoleUser pvmRoleUser : pvmRoleUserService.findAll()) { - pvmKcSnapshotList = pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser); - if (pvmKcSnapshotList.size() > 3) { - pvmKcSnapshotList = pvmKcSnapshotList.stream() - .sorted(Comparator.comparing(PvmKcSnapshot::getCreatedDate).reversed()) - .skip(2) - .toList(); - LOGGER.info("deleted {} from {}", pvmKcSnapshotList.size(), pvmRoleUser.getDiscordName()); - pvmKcSnapshotService.deleteAll(pvmKcSnapshotList); - } - } - } - - private void cleanupPolls() { - pollService.findAll().stream().filter(f -> ChronoUnit.DAYS.between(f.getCreatedDate(), LocalDateTime.now()) > POLL_DAYS_VALID) - .peek(f -> LOGGER.info("removed poll {} from {}", f.getMessageId(), f.getCreatedDate())) - .forEach(pollService::delete); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/OsrsMonitoringService.java b/src/main/java/com/sxcy/sxcybot/services/OsrsMonitoringService.java @@ -1,103 +0,0 @@ -package com.sxcy.sxcybot.services; - -import com.sxcy.sxcybot.client.HiScoreClient; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.model.OsrsBossKc; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; - -@Service -public class OsrsMonitoringService { - - private final Logger LOGGER = LoggerFactory.getLogger("monitor"); - private final HiScoreClient hiScoreClient; - private final PvmRoleUserService pvmRoleUserService; - private final String monitorUserName; - private final String monitorBossName; - private final String monitorBossKc; - - public OsrsMonitoringService(HiScoreClient hiScoreClient, - PvmRoleUserService pvmRoleUserService, - @Value("${monitor.user.name}") String monitorUserName, - @Value("${monitor.boss.name}") String monitorBossName, - @Value("${monitor.boss.kc}") String monitorBossKc) { - this.hiScoreClient = hiScoreClient; - this.pvmRoleUserService = pvmRoleUserService; - this.monitorUserName = monitorUserName; - this.monitorBossName = monitorBossName; - this.monitorBossKc = monitorBossKc; - } - - @Scheduled(cron = "${monitor.schedule}") - @SuppressWarnings("unused") - public void monitor() { - try { - monitorHiscores(); - monitorPvmRoleUserHiscores(null); - } catch (Exception e) { - LOGGER.error(e.getMessage()); - } - - } - - public void monitorPvmRoleUserHiscores(PrivateChannel privateChannel) { - List<PvmRoleUser> unfound = new ArrayList<>(); - for (PvmRoleUser pvmRoleUser : pvmRoleUserService.findAll()) { - try { - hiScoreClient.getHiScoreBossKc(pvmRoleUser.getRsn(), null).orElseThrow(); - } catch (Exception e) { - unfound.add(pvmRoleUser); - } - } - messageUnfoundResults(unfound, privateChannel); - } - - private void messageUnfoundResults(List<PvmRoleUser> unfound, PrivateChannel privateChannel) { - if (privateChannel == null) { - if (!unfound.isEmpty()) { - LOGGER.error("No hiScores found for: {}", unfound.stream().map(PvmRoleUser::getRsn).toList()); - } else { - LOGGER.info("All PvM Role competitors have been found in the hiscores."); - } - } else { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle("PvM competitor check"); - if (!unfound.isEmpty()) { - embedBuilder.setDescription("No hiscores found for following competitors:"); - unfound.forEach(competitor -> - embedBuilder.addField(competitor.getRsn(), String.format("Discord: %s", competitor.getDiscordName()), true)); - } else { - embedBuilder.setDescription("All PvM role competitors have been found in the hiscores."); - } - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - } - } - - public void monitorHiscores() throws EntityNotFoundException { - List<OsrsBossKc> osrsBossKcs = hiScoreClient.getHiScoreBossKc(monitorUserName, null) - .orElseThrow(() -> new EntityNotFoundException(String.format("No hiscores available for %s.", monitorUserName))); - OsrsBossKc wintertodtBossKc = osrsBossKcs.stream() - .filter(f -> f.name().equals(monitorBossName)) - .findAny() - .orElseThrow(() -> new EntityNotFoundException(String.format("No \"%s\" hiscores found.", monitorBossName))); - - if (wintertodtBossKc.kc().equals(monitorBossKc)) { - LOGGER.info(String.format("Hiscores check is OK. (%s has %s kc on %s)", monitorUserName, monitorBossKc, monitorBossName)); - } else { - LOGGER.error(String.format("Hiscores check not OK: %s kc for user %s is not %s, but is %s", - monitorBossName, monitorUserName, monitorBossKc, wintertodtBossKc.kc())); - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/PvMRoleResolver.java b/src/main/java/com/sxcy/sxcybot/services/PvMRoleResolver.java @@ -1,75 +0,0 @@ -package com.sxcy.sxcybot.services; - -import com.sxcy.sxcybot.enums.PvmRole; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.services.guild.ChannelDetailService; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleAssignerService; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleSnapshotComparatorService; -import com.sxcy.sxcybot.services.guild.pvmrole.PvmRoleUserService; -import net.dv8tion.jda.api.entities.PrivateChannel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -@Component -public class PvMRoleResolver { - - private static final Logger LOGGER = LoggerFactory.getLogger(PvMRoleResolver.class); - private final PvmRoleUserService pvmRoleUserService; - private final ChannelDetailService channelDetailService; - private final PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService; - private final PvmRoleAssignerService pvmRoleAssignerService; - - public PvMRoleResolver(PvmRoleUserService pvmRoleUserService, - ChannelDetailService channelDetailService, - PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService, - PvmRoleAssignerService pvmRoleAssignerService) { - this.pvmRoleUserService = pvmRoleUserService; - this.channelDetailService = channelDetailService; - this.pvmRoleSnapshotComparatorService = pvmRoleSnapshotComparatorService; - this.pvmRoleAssignerService = pvmRoleAssignerService; - } - - @Scheduled(cron = "${pvm.role.schedule}") - @SuppressWarnings("unused") - public void resolvePvMRoles() { - LOGGER.info("Running scheduled pvmRoleResolver."); - resolvePvMRoles(true, null); - } - - public void resolvePvMRoles(boolean persist, PrivateChannel privateChannel) { - Map<PvmRole, LinkedHashMap<PvmRoleUser, BigDecimal>> scoreBoard = new HashMap<>(); - for (PvmRole pvmRole : PvmRole.values()) { - if (!pvmRole.equals(PvmRole.UNUSED)) - scoreBoard.put(pvmRole, new LinkedHashMap<>()); - } - channelDetailService.getJda().getGuilds().forEach(guild -> - channelDetailService.findAll().stream().findAny().ifPresent(channelDetail -> - (privateChannel == null ? guild.getTextChannelsByName(channelDetail.getPvmRoleChannel(), true) : List.of(privateChannel)) - .forEach(textChannel -> { - for (PvmRoleUser pvmRoleUser : pvmRoleUserService.findAll()) { - List<PvmKcSnapshot> pvmKcSnapshots = new ArrayList<>(); - try { - pvmKcSnapshots.add(pvmRoleSnapshotComparatorService.takeSnapshot(textChannel, pvmRoleUser, false, persist)); - } catch (EntityNotFoundException e) { - textChannel.sendMessage(e.getMessage()).queue(); - continue; - } - pvmRoleSnapshotComparatorService.updateScoreboard(pvmRoleUser, scoreBoard, persist ? null : pvmKcSnapshots); - } - pvmRoleAssignerService.postScoreboardAndAssignRoles(guild, textChannel, scoreBoard, channelDetail, persist); - }) - ) - ); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/ChannelDetailService.java b/src/main/java/com/sxcy/sxcybot/services/guild/ChannelDetailService.java @@ -1,34 +0,0 @@ -package com.sxcy.sxcybot.services.guild; - -import com.sxcy.sxcybot.repository.guild.ChannelDetailRepository; -import com.sxcy.sxcybot.repository.guild.dao.ChannelDetail; -import net.dv8tion.jda.api.JDA; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class ChannelDetailService { - - private final ChannelDetailRepository channelDetailRepository; - - private JDA jda; - - public JDA getJda() { - return jda; - } - - public void setJda(JDA jda) { - this.jda = jda; - } - - public ChannelDetailService(ChannelDetailRepository channelDetailRepository) { - this.channelDetailRepository = channelDetailRepository; - } - - public List<ChannelDetail> findAll() { - return channelDetailRepository.findAll(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/GuildEventDmerService.java b/src/main/java/com/sxcy/sxcybot/services/guild/GuildEventDmerService.java @@ -1,23 +0,0 @@ -package com.sxcy.sxcybot.services.guild; - -import com.sxcy.sxcybot.repository.guild.GuildEventDmerRepository; -import com.sxcy.sxcybot.repository.guild.dao.GuildEventDmer; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class GuildEventDmerService { - - private final GuildEventDmerRepository guildEventDmerRepository; - - public GuildEventDmerService(GuildEventDmerRepository guildEventDmerRepository) { - this.guildEventDmerRepository = guildEventDmerRepository; - } - - public List<GuildEventDmer> findAll() { - return guildEventDmerRepository.findAll(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/GuildRoleService.java b/src/main/java/com/sxcy/sxcybot/services/guild/GuildRoleService.java @@ -1,45 +0,0 @@ -package com.sxcy.sxcybot.services.guild; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.repository.guild.GuildRoleRepository; -import com.sxcy.sxcybot.repository.guild.dao.GuildRole; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class GuildRoleService { - - private final GuildRoleRepository guildRoleRepository; - - public GuildRoleService(GuildRoleRepository guildRoleRepository) { - this.guildRoleRepository = guildRoleRepository; - } - - public List<GuildRole> findAllByElevationLessThanEqual(int elevation) { - return guildRoleRepository.findByElevationLessThanEqual(elevation); - } - - public List<GuildRole> findAllByElevationGreaterThanEqual(int elevation) { - return guildRoleRepository.findByElevationGreaterThanEqual(elevation); - } - - public GuildRole findByName(String name) throws EntityNotFoundException { - return guildRoleRepository.findByName(name).orElseThrow( - () -> new EntityNotFoundException(String.format("No role found with name %s.", name))); - } - - public GuildRole save(GuildRole guildRole) { - return guildRoleRepository.save(guildRole); - } - - public void delete(GuildRole guildRole) { - guildRoleRepository.delete(guildRole); - } - - public List<GuildRole> findAll() { - return guildRoleRepository.findAll(); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/PollService.java b/src/main/java/com/sxcy/sxcybot/services/guild/PollService.java @@ -1,36 +0,0 @@ -package com.sxcy.sxcybot.services.guild; - -import com.sxcy.sxcybot.repository.guild.PollRepository; -import com.sxcy.sxcybot.repository.guild.dao.Poll; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; -import java.util.Optional; - -@Service -@Transactional -public class PollService { - - private final PollRepository pollRepository; - - public PollService(PollRepository pollRepository) { - this.pollRepository = pollRepository; - } - - public List<Poll> findAll() { - return pollRepository.findAll(); - } - - public Optional<Poll> findByMessageId(String messageId) { - return pollRepository.findByMessageId(messageId); - } - - public Poll save(Poll poll) { - return pollRepository.save(poll); - } - - public void delete(Poll poll) { - pollRepository.delete(poll); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/RuleService.java b/src/main/java/com/sxcy/sxcybot/services/guild/RuleService.java @@ -1,37 +0,0 @@ -package com.sxcy.sxcybot.services.guild; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.repository.guild.RuleRepository; -import com.sxcy.sxcybot.repository.guild.dao.Rule; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class RuleService { - - private final RuleRepository ruleRepository; - - public RuleService(RuleRepository ruleRepository) { - this.ruleRepository = ruleRepository; - } - - public List<Rule> findAll() { - return ruleRepository.findAll(); - } - - public Rule findByNumber(int number) throws EntityNotFoundException { - return ruleRepository.findByNumber(number).orElseThrow( - () -> new EntityNotFoundException(String.format("Rule with number %s not found.", number))); - } - - public Rule save(Rule rule) { - return ruleRepository.save(rule); - } - - public void delete(Rule rule) { - ruleRepository.delete(rule); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/UserService.java b/src/main/java/com/sxcy/sxcybot/services/guild/UserService.java @@ -1,38 +0,0 @@ -package com.sxcy.sxcybot.services.guild; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.repository.guild.UserRepository; -import com.sxcy.sxcybot.repository.guild.dao.User; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class UserService { - - private final UserRepository userRepository; - - public UserService(UserRepository userRepository) { - this.userRepository = userRepository; - } - - public List<User> findAllBanned() { - return userRepository.findAllByBannedTrue(); - } - - public User save(User user) { - return userRepository.save(user); - } - - public void delete(User user) throws EntityNotFoundException { - findByName(user.getName()); - userRepository.delete(user); - } - - public User findByName(String name) throws EntityNotFoundException { - return userRepository.findByName(name).orElseThrow( - () -> new EntityNotFoundException(String.format("No user found with name %s.", name))); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmKcSnapshotService.java b/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmKcSnapshotService.java @@ -1,36 +0,0 @@ -package com.sxcy.sxcybot.services.guild.pvmrole; - -import com.sxcy.sxcybot.repository.guild.pvmrole.PvmKcSnapshotRepository; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class PvmKcSnapshotService { - - private final PvmKcSnapshotRepository pvmKcSnapshotRepository; - - public PvmKcSnapshotService(PvmKcSnapshotRepository pvmKcSnapshotRepository) { - this.pvmKcSnapshotRepository = pvmKcSnapshotRepository; - } - - public List<PvmKcSnapshot> findAll() { - return pvmKcSnapshotRepository.findAll(); - } - - public List<PvmKcSnapshot> findAllByPvmRoleUser(PvmRoleUser pvmRoleUser) { - return pvmKcSnapshotRepository.findAllByPvmRoleUserId(pvmRoleUser.getId()); - } - - public PvmKcSnapshot save(PvmKcSnapshot pvmKcSnapshot) { - return pvmKcSnapshotRepository.save(pvmKcSnapshot); - } - - public void deleteAll(List<PvmKcSnapshot> pvmKcSnapshots) { - pvmKcSnapshotRepository.deleteAll(pvmKcSnapshots); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java b/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java @@ -1,92 +0,0 @@ -package com.sxcy.sxcybot.services.guild.pvmrole; - -import com.sxcy.sxcybot.enums.PvmRole; -import com.sxcy.sxcybot.repository.guild.dao.ChannelDetail; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.MessageChannel; -import net.dv8tion.jda.api.entities.Role; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.awt.Color; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -@Service -@Transactional -public class PvmRoleAssignerService { - - public void postScoreboardAndAssignRoles(Guild guild, MessageChannel textChannel, Map<PvmRole, LinkedHashMap<PvmRoleUser, BigDecimal>> scoreBoard, ChannelDetail channelDetail, boolean persist) { - for (PvmRole pvmRole : scoreBoard.keySet()) { - String rolename = getRolename(pvmRole, channelDetail); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle(String.format("**%s** Scoreboard results:", rolename)); - if (scoreBoard.get(pvmRole).isEmpty()) { - embedBuilder.addField(String.format("No KC gains detected for %s", pvmRole.name().toLowerCase()), "No increase in KC found for participants, role will remain unchanged.", false); - textChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - continue; - } - List<Map.Entry<PvmRoleUser, BigDecimal>> entries = new ArrayList<>(scoreBoard.get(pvmRole).entrySet()); - entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); - scoreBoard.get(pvmRole).clear(); - entries.forEach(f -> scoreBoard.get(pvmRole).put(f.getKey(), f.getValue())); - guild.loadMembers().onSuccess(memberlist -> { - long limit = 5; - int i = 1; - int winningRank = 1; - for (Map.Entry<PvmRoleUser, BigDecimal> entry : scoreBoard.get(pvmRole).entrySet()) { - if (limit-- == 0) break; - Optional<Member> member = memberlist.stream().filter(f -> entry.getKey().getDiscordName().equalsIgnoreCase(f.getUser().getName()) || entry.getKey().getDiscordName().equalsIgnoreCase(f.getNickname())).findFirst(); - if (member.isPresent()) { - embedBuilder.addField(String.format("#%s %s", i, entry.getKey().getRsn()), String.format("%s with a score of %s!", member.get(), entry.getValue()), false); - if (i == winningRank && persist) { - Optional<Role> role = guild.getRoles().stream().filter(f -> rolename.equalsIgnoreCase(f.getName())).findFirst(); - if (role.isPresent()) { - guild.findMembersWithRoles(role.get()) - .onSuccess(oldWinners -> { - if (oldWinners.isEmpty()) { - addRoleToWinner(guild, member.get(), role.get(), textChannel, entry.getKey().getRsn()); - } else { - oldWinners.forEach(f -> guild.removeRoleFromMember(f, role.get()).queue(complete -> - addRoleToWinner(guild, member.get(), role.get(), textChannel, entry.getKey().getRsn()))); - } - }); - } else { - textChannel.sendMessage(String.format("No role %s found in the channel, role could not get assigned.", rolename)).queue(); - } - } - } else { - if (i == winningRank) winningRank++; - embedBuilder.addField(String.format("#%s %s", i, entry.getKey().getRsn()), String.format("%s with a score of %s!", entry.getKey().getDiscordName(), entry.getValue()), false); - textChannel.sendMessage(String.format("No guildmember found for discordname %s. User did not receive any awards.", entry.getKey().getDiscordName())).queue(); - } - i++; - } - textChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - }); - } - } - - private String getRolename(PvmRole pvmRole, ChannelDetail channelDetail) { - return switch (pvmRole) { - case GENERAL -> channelDetail.getPvmRoleGeneral(); - case RAIDS -> channelDetail.getPvmRoleRaids(); - case WILDERNESS -> channelDetail.getPvmRoleWilderness(); - default -> "Something went wrong."; - }; - } - - private void addRoleToWinner(Guild guild, Member member, Role role, MessageChannel textChannel, String rsn) { - guild.addRoleToMember(member, role).queue(ok -> - textChannel.sendMessage(String.format("%s is our new %s!", rsn, role)).queue()); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleSnapshotComparatorService.java b/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleSnapshotComparatorService.java @@ -1,99 +0,0 @@ -package com.sxcy.sxcybot.services.guild.pvmrole; - -import com.sxcy.sxcybot.client.HiScoreClient; -import com.sxcy.sxcybot.enums.PvmRole; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.model.OsrsBossKc; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmUserKc; -import com.sxcy.sxcybot.services.osrs.OsrsHiscoreBossService; -import net.dv8tion.jda.api.entities.MessageChannel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -@Service -@Transactional -public class PvmRoleSnapshotComparatorService { - - private static final Logger LOGGER = LoggerFactory.getLogger(PvmRoleSnapshotComparatorService.class); - private final OsrsHiscoreBossService osrsHiscoreBossService; - private final PvmKcSnapshotService pvmKcSnapshotService; - private final HiScoreClient hiScoreClient; - - public PvmRoleSnapshotComparatorService(OsrsHiscoreBossService osrsHiscoreBossService, - PvmKcSnapshotService pvmKcSnapshotService, - HiScoreClient hiScoreClient) { - this.osrsHiscoreBossService = osrsHiscoreBossService; - this.pvmKcSnapshotService = pvmKcSnapshotService; - this.hiScoreClient = hiScoreClient; - } - - public void updateScoreboard(PvmRoleUser pvmRoleUser, Map<PvmRole, LinkedHashMap<PvmRoleUser, BigDecimal>> scoreBoard, List<PvmKcSnapshot> unpersistedSnapshots) { - boolean persisted = unpersistedSnapshots == null; - List<PvmKcSnapshot> pvmKcSnapshots = pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser); - if (pvmKcSnapshots != null && (pvmKcSnapshots.size() > 1 || (!persisted && pvmKcSnapshots.size() > 0))) { - pvmKcSnapshots = pvmKcSnapshots.stream() - .sorted(Comparator.comparing(PvmKcSnapshot::getCreatedDate) - .reversed()) - .limit(persisted ? 2 : 1) - .toList(); - for (PvmRole pvmRole : scoreBoard.keySet()) { - BigDecimal points1 = calculatePoints(pvmRole, persisted ? pvmKcSnapshots.get(0) : unpersistedSnapshots.get(0)); - BigDecimal points2 = calculatePoints(pvmRole, pvmKcSnapshots.get(persisted ? 1 : 0)); - BigDecimal result = points1.subtract(points2); - if (BigDecimal.ZERO.compareTo(result) < 0) - scoreBoard.get(pvmRole).put(pvmRoleUser, result); - } - } - } - - private BigDecimal calculatePoints(PvmRole pvmRole, PvmKcSnapshot pvmKcSnapshot) { - BigDecimal points = BigDecimal.ZERO; - for (PvmUserKc pvmUserKc : pvmKcSnapshot.getPvmUserKcList().stream().filter(f -> pvmRole.value == f.getOsrsHiscoreBoss().getPvmRole()).toList()) { - points = points.add(BigDecimal.valueOf(pvmUserKc.getOsrsHiscoreBoss().getMultiplier()).multiply(BigDecimal.valueOf(pvmUserKc.getKc()))); - } - return points; - } - - public PvmKcSnapshot takeSnapshot(MessageChannel textChannel, PvmRoleUser pvmRoleUser, boolean notify, boolean persist) throws EntityNotFoundException { - PvmKcSnapshot pvmKcSnapshot = PvmKcSnapshot.Builder.newBuilder() - .pvmRoleUser(pvmRoleUser) - .build(); - List<OsrsBossKc> osrsBossKcList = hiScoreClient.getHiScoreBossKc(pvmRoleUser.getRsn(), textChannel).orElseThrow( - () -> new EntityNotFoundException(String.format("No hiScores found for %s", pvmRoleUser.getRsn())) - ); - List<PvmUserKc> pvmUserKcList = new ArrayList<>(); - for (OsrsBossKc osrsBossKc : osrsBossKcList.stream().filter(r -> Integer.parseInt(r.kc()) > 0).toList()) { - try { - PvmUserKc pvmUserKc = PvmUserKc.Builder.newBuilder() - .pvmRoleUser(pvmRoleUser) - .osrsHiscoreBoss(osrsHiscoreBossService.findByName(osrsBossKc.name())) - .pvmKcSnapshot(pvmKcSnapshot) - .kc(Integer.valueOf(osrsBossKc.kc())) - .build(); - pvmUserKcList.add(pvmUserKc); - } catch (EntityNotFoundException e) { - LOGGER.error(e.getMessage(), e); - } - } - pvmKcSnapshot.setPvmUserKcList(pvmUserKcList); - - if (persist) { - pvmKcSnapshot = pvmKcSnapshotService.save(pvmKcSnapshot); - if (notify) - textChannel.sendMessage(String.format("KC snapshot saved for %s.%n", pvmRoleUser.getRsn())).queue(); - } - - return pvmKcSnapshot; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleUserService.java b/src/main/java/com/sxcy/sxcybot/services/guild/pvmrole/PvmRoleUserService.java @@ -1,39 +0,0 @@ -package com.sxcy.sxcybot.services.guild.pvmrole; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.repository.guild.pvmrole.PvmRoleUserRepository; -import com.sxcy.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; -import org.springframework.stereotype.Service; - -import java.util.List; - -import static com.sxcy.sxcybot.enums.Command.PVMLIST; -import static com.sxcy.sxcybot.util.Constants.Commands.COMMAND_PREFIX; - -@Service -public class PvmRoleUserService { - - private final PvmRoleUserRepository pvmRoleUserRepository; - - public PvmRoleUserService(PvmRoleUserRepository pvmRoleUserRepository) { - this.pvmRoleUserRepository = pvmRoleUserRepository; - } - - public List<PvmRoleUser> findAll() { - return pvmRoleUserRepository.findAll(); - } - - public PvmRoleUser save(PvmRoleUser pvmRoleUser) { - return pvmRoleUserRepository.save(pvmRoleUser); - } - - public PvmRoleUser findByDiscordName(String discordName) throws EntityNotFoundException { - return pvmRoleUserRepository.findByDiscordName(discordName).orElseThrow(() - -> new EntityNotFoundException(String.format("No discord user found with name %s in the PvM competition.%sYou can check all competitors with the \"%s\" command." - , discordName, System.lineSeparator(), COMMAND_PREFIX + PVMLIST.name().toLowerCase()))); - } - - public void delete(PvmRoleUser pvmRoleUser) { - pvmRoleUserRepository.delete(pvmRoleUser); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/osrs/CombatCalculatorService.java b/src/main/java/com/sxcy/sxcybot/services/osrs/CombatCalculatorService.java @@ -1,29 +0,0 @@ -package com.sxcy.sxcybot.services.osrs; - -import com.sxcy.sxcybot.model.CombatDto; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -@Service -@Transactional -public class CombatCalculatorService { - - public double getCombatLevel(CombatDto combatDto) { - double base = 0.25 * (combatDto.defenceLevel() + combatDto.hitpointsLevel() + (combatDto.prayerLevel() / 2)); - - double typeContribution = getMeleeRangeOrMagicCombatLevelContribution(combatDto.attackLevel(), combatDto.strengthLevel(), combatDto.magicLevel(), combatDto.rangeLevel()); - - return BigDecimal.valueOf(base + typeContribution).setScale(3, RoundingMode.HALF_UP).doubleValue(); - } - - private double getMeleeRangeOrMagicCombatLevelContribution(int attackLevel, int strengthLevel, int magicLevel, int rangeLevel) { - double melee = 0.325 * (attackLevel + strengthLevel); - double range = 0.325 * (rangeLevel / 2 + rangeLevel); - double magic = 0.325 * (magicLevel / 2 + magicLevel); - - return Math.max(melee, Math.max(range, magic)); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/osrs/OsrsHiscoreBossService.java b/src/main/java/com/sxcy/sxcybot/services/osrs/OsrsHiscoreBossService.java @@ -1,30 +0,0 @@ -package com.sxcy.sxcybot.services.osrs; - -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.repository.osrs.OsrsHiscoreBossRepository; -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; -import org.springframework.data.domain.Sort; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class OsrsHiscoreBossService { - - private final OsrsHiscoreBossRepository osrsHiscoreBossRepository; - - public OsrsHiscoreBossService(OsrsHiscoreBossRepository osrsHiscoreBossRepository) { - this.osrsHiscoreBossRepository = osrsHiscoreBossRepository; - } - - public List<OsrsHiscoreBoss> findAll() { - return osrsHiscoreBossRepository.findAll(Sort.by("orderValue").ascending()); - } - - public OsrsHiscoreBoss findByName(String name) throws EntityNotFoundException { - return osrsHiscoreBossRepository.findByName(name).orElseThrow( - () -> new EntityNotFoundException(String.format("No hiscoreBoss found with name %s.", name))); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/osrs/OsrsHiscoreStatService.java b/src/main/java/com/sxcy/sxcybot/services/osrs/OsrsHiscoreStatService.java @@ -1,24 +0,0 @@ -package com.sxcy.sxcybot.services.osrs; - -import com.sxcy.sxcybot.repository.osrs.OsrsHiscoreStatRepository; -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreStat; -import org.springframework.data.domain.Sort; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class OsrsHiscoreStatService { - - private final OsrsHiscoreStatRepository osrsHiscoreStatRepository; - - public OsrsHiscoreStatService(OsrsHiscoreStatRepository osrsHiscoreStatRepository) { - this.osrsHiscoreStatRepository = osrsHiscoreStatRepository; - } - - public List<OsrsHiscoreStat> findAll() { - return osrsHiscoreStatRepository.findAll(Sort.by("orderValue").ascending()); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/services/osrs/StatMessageSender.java b/src/main/java/com/sxcy/sxcybot/services/osrs/StatMessageSender.java @@ -1,49 +0,0 @@ -package com.sxcy.sxcybot.services.osrs; - -import com.sxcy.sxcybot.client.HiScoreClient; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import com.sxcy.sxcybot.model.OsrsStat; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.awt.Color; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Predicate; - -@Service -@Transactional -public class StatMessageSender { - - private final HiScoreClient hiScoreClient; - - public StatMessageSender(HiScoreClient hiScoreClient) { - this.hiScoreClient = hiScoreClient; - } - - public void sendStatMessage(MessageReceivedEvent event, EmbedBuilder embedBuilder, - Predicate<OsrsStat> predicate, Consumer<OsrsStat> consumer - , Consumer<List<OsrsStat>> calcCombatLevel) { - String msg = event.getMessage().getContentRaw(); - try { - String player = msg.substring(msg.indexOf(" ")).trim(); - try { - embedBuilder.setColor(Color.RED); - embedBuilder.setTitle(String.format("Stats of %s", player)); - List<OsrsStat> osrsStatList = hiScoreClient.getHiScoreStats(player, event.getChannel()).orElseThrow(() - -> new EntityNotFoundException(String.format("No HiScores found for %s.", player))); - osrsStatList.stream().filter(predicate).forEach(consumer); - if (calcCombatLevel != null) { - calcCombatLevel.accept(osrsStatList); - } - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - } catch (EntityNotFoundException entityNotFoundException) { - event.getChannel().sendMessage(entityNotFoundException.getMessage()).queue(); - } - } catch (StringIndexOutOfBoundsException e) { - event.getChannel().sendMessage("Please enter a player name after the command, separated by space.").queue(); - } - } -} diff --git a/src/main/java/com/sxcy/sxcybot/util/Constants.java b/src/main/java/com/sxcy/sxcybot/util/Constants.java @@ -1,38 +0,0 @@ -package com.sxcy.sxcybot.util; - - -public class Constants { - - private Constants() { - } - - public static final int ADDED_ROLE_ELEVATION = 100; - - public static class Commands { - private Commands() { - } - - public static final String COMMAND_PREFIX = "sb-"; - public static final String BB8 = COMMAND_PREFIX + "8"; - } - - public static class Emoji { - - private Emoji() { - } - - public static final String THUMBS_UP = ":+1:"; - public static final String FLAMES = ":flame:"; - } - - public static class Reaction { - private Reaction() { - } - - public static final String CHECK_MARK = "U+2714"; - public static final String CROSS_MARK = "U+274C"; - public static final String QUESTION_MARK = "U+2753"; - public static final String CHECK_MARK_BUTTON = "U+2705"; - public static final String CROSS_MARK_BUTTON = "U+274E"; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/util/CustomPollFiller.java b/src/main/java/com/sxcy/sxcybot/util/CustomPollFiller.java @@ -1,80 +0,0 @@ -package com.sxcy.sxcybot.util; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.repository.guild.dao.Poll; -import com.sxcy.sxcybot.services.guild.PollService; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.util.Set; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class CustomPollFiller { - - private final EventWaiterUtil eventWaiterUtil; - private final PollService pollService; - private static final String STOP_WORD = "stop"; - - public CustomPollFiller(EventWaiterUtil eventWaiterUtil, - PollService pollService) { - this.eventWaiterUtil = eventWaiterUtil; - this.pollService = pollService; - } - -// private static final String EMOJI_REGEX = "([\\u20a0-\\u32ff\\ud83c\\udc00-\\ud83d\\udeff\\udbb9\\udce5-\\udbb9\\udcee])"; - - public void fillPoll(PrivateChannel privateChannel, MessageReceivedEvent event, EmbedBuilder embedBuilder, Set<String> emojiList) { - EmbedBuilder embeddedOption = new EmbedBuilder(); - embeddedOption.setColor(Color.RED); - embeddedOption.addField("Please enter an option for the poll", "`stop` to finish and create the poll.", false); - privateChannel.sendMessageEmbeds(embeddedOption.build()).queue(); - embeddedOption.clear(); - eventWaiterUtil.waitForPrivateChannelEvent(optionReceiver -> { - if (isReadyToStop(optionReceiver)) { - event.getChannel().sendTyping().queue(typing -> - event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(message -> { - emojiList.forEach(emoji -> message.addReaction(emoji).queue()); - pollService.save(Poll.Builder.newBuilder().messageId(message.getId()).build()); - })); - return; - } - embeddedOption.setColor(Color.RED); - embeddedOption.addField(String.format("Please type in a reaction emoji for _%s_.", optionReceiver.getMessage().getContentRaw()), "", false); - privateChannel.sendMessageEmbeds(embeddedOption.build()).queue(); - embeddedOption.clear(); - eventWaiterUtil.waitForPrivateChannelEvent(emojiReceiver -> { - if (!emojiList.contains(emojiReceiver.getMessage().getContentRaw())) { - if (!isValidEmoji(emojiReceiver.getMessage().getContentRaw())) { - privateChannel.sendMessage(String.format("%s is not a valid emoji, please retry this option.", emojiReceiver.getMessage().getContentRaw())).queue(); - this.fillPoll(privateChannel, event, embedBuilder, emojiList); - return; - } - embedBuilder.addField(String.format("%s %s %s", emojiReceiver.getMessage().getContentRaw(), optionReceiver.getMessage().getContentRaw(), "(0)"), "", true); - emojiList.add(emojiReceiver.getMessage().getContentRaw()); - } else { - privateChannel.sendMessage(String.format("Emoji %s was already picked for another options, please retry this option.", emojiReceiver.getMessage().getContentRaw())).queue(); - } - this.fillPoll(privateChannel, event, embedBuilder, emojiList); - }, event, privateChannel); - }, event, privateChannel); - } - - private boolean isReadyToStop(PrivateMessageReceivedEvent privateMessageReceivedEvent) { - return privateMessageReceivedEvent.getMessage().getContentRaw().equalsIgnoreCase(STOP_WORD); - } - - private boolean isValidEmoji(String emoji) { - /* - TODO fix: - return Pattern.compile(EMOJI_REGEX).matcher(emoji).find(); - */ - return true; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/util/DiscordMemberFinderUtil.java b/src/main/java/com/sxcy/sxcybot/util/DiscordMemberFinderUtil.java @@ -1,50 +0,0 @@ -package com.sxcy.sxcybot.util; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.PrivateChannel; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import org.springframework.stereotype.Component; - -import java.util.Optional; -import java.util.function.Consumer; - -@Component -public class DiscordMemberFinderUtil { - - private final EventWaiterUtil eventWaiterUtil; - - public DiscordMemberFinderUtil(EventWaiterUtil eventWaiterUtil) { - this.eventWaiterUtil = eventWaiterUtil; - } - - public void onMemberFoundVerification(MessageReceivedEvent event, EmbedBuilder embedBuilder, PrivateChannel privateChannel, Consumer<Member> memberConsumer) { - embedBuilder.addField("Type the name of the user.", "Discord username will be looked up first, if no match is found it will search on nickname.", false); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - eventWaiterUtil.waitForPrivateChannelEvent(memberReceiver -> { - String name = memberReceiver.getMessage().getContentRaw(); - event.getGuild().loadMembers().onSuccess(memberList -> { - if (memberList.isEmpty()) { - privateChannel.sendMessage(String.format("User with name %s not found, please try again later.", name)).queue(); - } else { - Optional<Member> member = memberList.stream().filter(f -> name.equalsIgnoreCase(f.getUser().getName()) || name.equalsIgnoreCase(f.getNickname())).findFirst(); - if (member.isPresent()) { - embedBuilder.clearFields(); - embedBuilder.addField("Confirm by typing ``yes or y``.", String.format("Is %s the correct member?", member.get()), false); - privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - eventWaiterUtil.waitForPrivateChannelEvent(memberVerifyReceiver -> { - String verifyMessage = memberVerifyReceiver.getMessage().getContentRaw(); - if ("y".equalsIgnoreCase(verifyMessage) || "yes".equalsIgnoreCase(verifyMessage)) { - memberConsumer.accept(member.get()); - } - embedBuilder.clearFields(); - }, event, privateChannel); - } else { - privateChannel.sendMessage(String.format("User with name %s not found, please try again later.", name)).queue(); - } - } - }); - }, event, privateChannel); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/util/EditListenerUtil.java b/src/main/java/com/sxcy/sxcybot/util/EditListenerUtil.java @@ -1,42 +0,0 @@ -package com.sxcy.sxcybot.util; - -import com.sxcy.sxcybot.listeners.EventWaiterUtil; -import com.sxcy.sxcybot.model.EditListenerDto; -import net.dv8tion.jda.api.EmbedBuilder; -import org.springframework.stereotype.Component; - -import java.awt.Color; - -@Component -public class EditListenerUtil { - - private final EventWaiterUtil eventWaiterUtil; - - public EditListenerUtil(EventWaiterUtil eventWaiterUtil) { - this.eventWaiterUtil = eventWaiterUtil; - } - - public void procesEditEvent(EditListenerDto editListenerDto) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.red); - embedBuilder.setTitle("What do you want to do?"); - embedBuilder.addField("1", String.format("Add a new %s.", editListenerDto.entityName()), false); - embedBuilder.addField("2", String.format("Delete an existing %s.", editListenerDto.entityName()), false); - if (editListenerDto.updateListener() != null) - embedBuilder.addField("3", String.format("Update an existing %s.", editListenerDto.entityName()), false); - editListenerDto.privateChannel().sendMessageEmbeds(embedBuilder.build()).queue(); - eventWaiterUtil.waitForPrivateChannelEvent(commandReceiver -> { - switch (commandReceiver.getMessage().getContentRaw()) { - case "1" -> editListenerDto.addListener().proces(commandReceiver, editListenerDto.event()); - case "2" -> editListenerDto.deleteListener().proces(commandReceiver, editListenerDto.event()); - case "3" -> { - if (editListenerDto.updateListener() != null) - editListenerDto.updateListener().proces(commandReceiver, editListenerDto.event()); - } - default -> - editListenerDto.privateChannel().sendMessage("Unknown command, please try again.").queue(); - } - }, editListenerDto.event(), editListenerDto.privateChannel()); - } - -} diff --git a/src/main/java/com/sxcy/sxcybot/util/JdaUtil.java b/src/main/java/com/sxcy/sxcybot/util/JdaUtil.java @@ -1,37 +0,0 @@ -package com.sxcy.sxcybot.util; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; -import org.springframework.stereotype.Component; - -@Component -public class JdaUtil { - - public static String getName(GenericMessageReactionEvent event) { - if (event.getMember() != null && event.getMember().getNickname() != null) { - return event.getMember().getNickname(); - } else if (event.getUser() != null) { - return event.getUser().getName(); - } - return null; - } - - public static String getName(MessageReceivedEvent event) { - if (event.getMember() != null && event.getMember().getNickname() != null) { - return event.getMember().getNickname(); - } else if (event.getMember() != null) { - return event.getMember().getUser().getName(); - } - return null; - } - - public static User getUser(MessageReceivedEvent event) { - return event.getMember() != null ? event.getMember().getUser() : null; - } - - public static boolean requiresBuild(EmbedBuilder embedBuilder, int size, int count) { - return (embedBuilder.length() > 5000 || embedBuilder.getFields().size() == 25 || size == count); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/util/NumberFormatter.java b/src/main/java/com/sxcy/sxcybot/util/NumberFormatter.java @@ -1,15 +0,0 @@ -package com.sxcy.sxcybot.util; - -import java.text.NumberFormat; -import java.util.Locale; - -public class NumberFormatter { - - public static String format(String numberToFormat) { - return format(Integer.valueOf(numberToFormat)); - } - - public static String format(Integer numberToFormat) { - return NumberFormat.getNumberInstance(Locale.UK).format(numberToFormat); - } -} diff --git a/src/main/java/com/sxcy/sxcybot/util/ReleaseNotesUtil.java b/src/main/java/com/sxcy/sxcybot/util/ReleaseNotesUtil.java @@ -1,65 +0,0 @@ -package com.sxcy.sxcybot.util; - - -import com.sxcy.sxcybot.services.guild.ChannelDetailService; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.JDA; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import java.awt.Color; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; - -@Component -public class ReleaseNotesUtil { - - private static final Logger LOGGER = LoggerFactory.getLogger(ReleaseNotesUtil.class); - private final ChannelDetailService channelDetailService; - - private static final String GITLAB_URL = "https://gitlab.com/WimDupont/sxcybot"; - - public ReleaseNotesUtil(ChannelDetailService channelDetailService) { - this.channelDetailService = channelDetailService; - } - - public void showReleaseNotes(JDA jda) { - Map<String, String> releaseNotes = ReleaseNotesUtil.getReleaseNotes(); - if (!releaseNotes.isEmpty()) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setColor(Color.RED); - embedBuilder.setTitle(String.format("Latest updates %s", LocalDate.now()), GITLAB_URL); - for (Entry<String, String> entry : releaseNotes.entrySet()) { - embedBuilder.addField(entry.getKey(), entry.getValue(), false); - } - - channelDetailService.findAll().stream().findAny() - .ifPresent(detail -> jda.getTextChannelsByName(detail.getBotUpdateChannel(), false).forEach(f -> - f.sendMessageEmbeds(embedBuilder.build()).queue() - )); - } - } - - private static Map<String, String> getReleaseNotes() { - Map<String, String> releaseNotes = new LinkedHashMap<>(); - try { - InputStream in = Optional.ofNullable(ReleaseNotesUtil.class.getResourceAsStream("/releasenotes.csv")) - .orElseThrow(() -> new IOException("File releasenotes.csv not found!")); - Arrays.stream(new String(in.readAllBytes(), StandardCharsets.UTF_8).split("\n")).forEach(line -> { - if (!line.isEmpty()) - releaseNotes.put(line.split(";")[0], line.split(";")[1].trim()); - }); - } catch (IOException e) { - LOGGER.error(e.getMessage(), e); - } - return releaseNotes; - } -} diff --git a/src/main/java/com/sxcy/sxcybot/util/SpringSecurityAuditorAware.java b/src/main/java/com/sxcy/sxcybot/util/SpringSecurityAuditorAware.java @@ -1,21 +0,0 @@ -package com.sxcy.sxcybot.util; - - -import org.springframework.data.domain.AuditorAware; -import org.springframework.stereotype.Component; - -import java.util.Optional; - -@Component -public class SpringSecurityAuditorAware implements AuditorAware<String> { - - /** - * Returns the current auditor of the application. - * - * @return the current auditor - */ - @Override - public Optional<String> getCurrentAuditor() { - return Optional.empty(); - } -} diff --git a/src/main/java/com/wimdupont/sxcybot/SxcyBotApplication.java b/src/main/java/com/wimdupont/sxcybot/SxcyBotApplication.java @@ -0,0 +1,102 @@ +package com.wimdupont.sxcybot; + +import com.wimdupont.sxcybot.enums.Command; +import com.wimdupont.sxcybot.listeners.AdminCommandListener; +import com.wimdupont.sxcybot.listeners.CommandListener; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.GuildMemberEventListener; +import com.wimdupont.sxcybot.listeners.PollReactionListener; +import com.wimdupont.sxcybot.services.PvMRoleResolver; +import com.wimdupont.sxcybot.services.guild.ChannelDetailService; +import com.wimdupont.sxcybot.util.Constants.Commands; +import com.wimdupont.sxcybot.util.ReleaseNotesUtil; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.entities.Activity; +import net.dv8tion.jda.api.requests.GatewayIntent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; + +import javax.security.auth.login.LoginException; +import java.util.Arrays; + +@SpringBootApplication +@EnableScheduling +@ComponentScan +public class SxcyBotApplication implements CommandLineRunner { + + private static final Logger LOGGER = LoggerFactory.getLogger(SxcyBotApplication.class); + private final CommandListener commandListener; + private final AdminCommandListener adminCommandListener; + private final EventWaiterUtil eventWaiterUtil; + private final PollReactionListener pollReactionListener; + private final GuildMemberEventListener guildMemberEventListener; + private final ReleaseNotesUtil releaseNotesUtil; + private final ChannelDetailService channelDetailService; + private final PvMRoleResolver pvMRoleResolver; + private final String token; + + public SxcyBotApplication(CommandListener commandListener, + AdminCommandListener adminCommandListener, + EventWaiterUtil eventWaiterUtil, + PollReactionListener pollReactionListener, + GuildMemberEventListener guildMemberEventListener, + ReleaseNotesUtil releaseNotesUtil, + ChannelDetailService channelDetailService, + PvMRoleResolver pvMRoleResolver, + @Value("${discord.bot.token}") String token) { + this.commandListener = commandListener; + this.adminCommandListener = adminCommandListener; + this.eventWaiterUtil = eventWaiterUtil; + this.pollReactionListener = pollReactionListener; + this.guildMemberEventListener = guildMemberEventListener; + this.releaseNotesUtil = releaseNotesUtil; + this.channelDetailService = channelDetailService; + this.pvMRoleResolver = pvMRoleResolver; + this.token = token; + } + + public static void main(String[] args) { + SpringApplication.run(SxcyBotApplication.class, args); + } + + @Override + public void run(String[] args) throws LoginException { + LOGGER.debug("Jda to be created"); + JDA jda = JDABuilder.createLight(token, + GatewayIntent.GUILD_MESSAGES, + GatewayIntent.DIRECT_MESSAGES, + GatewayIntent.GUILD_MESSAGE_REACTIONS, + GatewayIntent.GUILD_MEMBERS, + GatewayIntent.GUILD_BANS + ) + .addEventListeners(commandListener, adminCommandListener, eventWaiterUtil, guildMemberEventListener, pollReactionListener) + .setActivity(Activity.listening(Commands.COMMAND_PREFIX + Command.HELP.name().toLowerCase())) + .build(); + try { + LOGGER.debug("Awaiting jda " + jda); + jda.awaitReady(); + LOGGER.debug("Jda " + jda + " ready"); + channelDetailService.setJda(jda); + pvMRoleResolver.updatePvMRoleDiscordNames(); + processArgs(jda, args); + } catch (InterruptedException e) { + LOGGER.error(e.getMessage(), e); + } + } + + private void processArgs(JDA jda, String... args) { + if (args.length > 0) { + if (Arrays.stream(args).anyMatch("notes"::equalsIgnoreCase)) + releaseNotesUtil.showReleaseNotes(jda); + if (Arrays.stream(args).anyMatch("snap"::equalsIgnoreCase)) + pvMRoleResolver.resolvePvMRoles(); + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/client/ClientErrorHandler.java b/src/main/java/com/wimdupont/sxcybot/client/ClientErrorHandler.java @@ -0,0 +1,27 @@ +package com.wimdupont.sxcybot.client; + +import net.dv8tion.jda.api.entities.MessageChannel; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.DefaultResponseErrorHandler; + +import java.io.IOException; + +public class ClientErrorHandler extends DefaultResponseErrorHandler { + + private final MessageChannel channel; + + public ClientErrorHandler(MessageChannel channel) { + this.channel = channel; + } + + @Override + public void handleError(ClientHttpResponse response) throws IOException { + String errorMsg = String.format("No results found. (%s)", response.getStatusText()); + if (channel != null) { + channel.sendMessage(errorMsg).queue(); + } else { + throw new RuntimeException(errorMsg); + } + } + +} diff --git a/src/main/java/com/wimdupont/sxcybot/client/GrandExchangeClient.java b/src/main/java/com/wimdupont/sxcybot/client/GrandExchangeClient.java @@ -0,0 +1,43 @@ +package com.wimdupont.sxcybot.client; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.model.OsrsItem; +import com.wimdupont.sxcybot.util.NumberFormatter; +import net.dv8tion.jda.api.entities.MessageChannel; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.time.Duration; +import java.util.Map; + +@Component +public class GrandExchangeClient { + private static final String URL = "https://api.weirdgloop.org/exchange/history/osrs/latest?name=%s&lang=en"; + + private final ObjectMapper objectMapper; + + public GrandExchangeClient(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + @SuppressWarnings("unchecked") + public String getPrice(String itemName, MessageChannel channel) throws EntityNotFoundException { + RestTemplate restTemplate = new RestTemplateBuilder() + .errorHandler(new ClientErrorHandler(channel)) + .setReadTimeout(Duration.ofSeconds(30)) + .build(); + Object result = restTemplate.getForEntity(String.format(URL, itemName), Object.class).getBody(); + if (result != null) { + try { + return NumberFormatter.format(objectMapper + .convertValue(((Map<String, Object>) result).values().iterator().next(), OsrsItem.class).price()); + } catch (IllegalArgumentException e) { + throw new EntityNotFoundException(String.format("Item with name %s not found.", itemName)); + } + } else { + throw new EntityNotFoundException(String.format("Item with name %s not found.", itemName)); + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/client/HiScoreClient.java b/src/main/java/com/wimdupont/sxcybot/client/HiScoreClient.java @@ -0,0 +1,94 @@ +package com.wimdupont.sxcybot.client; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.model.HiScoreBuilder; +import com.wimdupont.sxcybot.model.OsrsBossKc; +import com.wimdupont.sxcybot.model.OsrsStat; +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreStat; +import com.wimdupont.sxcybot.services.osrs.OsrsHiscoreBossService; +import com.wimdupont.sxcybot.services.osrs.OsrsHiscoreStatService; +import com.wimdupont.sxcybot.util.NumberFormatter; +import net.dv8tion.jda.api.entities.MessageChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +@Component +public class HiScoreClient { + + private static final String URL = "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=%s"; + private static final Logger LOGGER = LoggerFactory.getLogger(HiScoreClient.class); + + private static final int STATS_START = 0; + private static final int STATS_END = 23; + private static final int BOSS_START = 38; + private static final int BOSS_END = 88; + + private final OsrsHiscoreBossService osrsHiscoreBossService; + private final OsrsHiscoreStatService osrsHiscoreStatService; + + public HiScoreClient(OsrsHiscoreBossService osrsHiscoreBossService, + OsrsHiscoreStatService osrsHiscoreStatService) { + this.osrsHiscoreBossService = osrsHiscoreBossService; + this.osrsHiscoreStatService = osrsHiscoreStatService; + } + + public Optional<List<OsrsStat>> getHiScoreStats(String playername, MessageChannel channel) { + List<OsrsHiscoreStat> hiscoreStats = osrsHiscoreStatService.findAll(); + return getHiScores(playername, channel, (osrsStat, hiScoreStatValues, i) -> OsrsStat.Builder.newBuilder() + .name(hiscoreStats.stream().filter(f -> f.getOrderValue() == i).findFirst().orElseThrow(() + -> new EntityNotFoundException(String.format("OsrsStatName for order %s not found!", i))) + .getName()) + .rank(NumberFormatter.format(hiScoreStatValues.get(0))) + .level(hiScoreStatValues.get(1)) + .experience(NumberFormatter.format(hiScoreStatValues.get(2))) + .build(), STATS_START, STATS_END); + } + + public Optional<List<OsrsBossKc>> getHiScoreBossKc(String playername, MessageChannel channel) { + List<OsrsHiscoreBoss> hiscoreBosses = osrsHiscoreBossService.findAll(); + return getHiScores(playername, channel, (osrsKc, hiScoreKcValues, i) -> OsrsBossKc.Builder.newBuilder() + .name(hiscoreBosses.stream().filter(f -> f.getOrderValue() == i).findFirst().orElseThrow(() + -> new EntityNotFoundException(String.format("OsrsBoss for order %s not found!", i))) + .getName()) + .rank(hiScoreKcValues.get(0)) + .kc(hiScoreKcValues.get(1)) + .build(), BOSS_START, BOSS_END); + } + + private <T> Optional<List<T>> getHiScores(String playername, MessageChannel channel, HiScoreBuilder<T> hiScoreBuilder, int fromIndex, int toIndex) { + List<T> hiScoreList = new ArrayList<>(); + RestTemplate restTemplate = new RestTemplateBuilder() + .errorHandler(new ClientErrorHandler(channel)) + .setReadTimeout(Duration.ofSeconds(30)) + .build(); + String result = restTemplate.getForObject(String.format(URL, playername), String.class); + if (result != null) { + int i = fromIndex; + List<String> hiScores = Arrays.stream(result.split("\n")).toList(); + try { + for (String osrsHiScoresStats : hiScores.subList(fromIndex, toIndex + 1)) { + List<String> hiScoreStatValues = Arrays.stream(osrsHiScoresStats.split(",")).toList(); + try { + hiScoreList.add(hiScoreBuilder.accept(osrsHiScoresStats, hiScoreStatValues, i)); + } catch (EntityNotFoundException e) { + LOGGER.error(e.getMessage(), e); + } + i++; + } + } catch (RuntimeException e) { + return Optional.empty(); + } + } + return Optional.of(hiScoreList); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/config/AppConfig.java b/src/main/java/com/wimdupont/sxcybot/config/AppConfig.java @@ -0,0 +1,15 @@ +package com.wimdupont.sxcybot.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SuppressWarnings("unused") +public class AppConfig { + + @Bean + public ObjectMapper objectMapper() { + return new ObjectMapper(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/config/PersistenceConfig.java b/src/main/java/com/wimdupont/sxcybot/config/PersistenceConfig.java @@ -0,0 +1,23 @@ +package com.wimdupont.sxcybot.config; + +import com.wimdupont.sxcybot.util.SpringSecurityAuditorAware; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.domain.AuditorAware; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@Configuration +@EnableJpaAuditing(auditorAwareRef = "auditorProvider") +public class PersistenceConfig { + + private final SpringSecurityAuditorAware springSecurityAuditorAware; + + public PersistenceConfig(SpringSecurityAuditorAware springSecurityAuditorAware) { + this.springSecurityAuditorAware = springSecurityAuditorAware; + } + + @Bean + public AuditorAware<String> auditorProvider() { + return springSecurityAuditorAware; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/enums/Command.java b/src/main/java/com/wimdupont/sxcybot/enums/Command.java @@ -0,0 +1,46 @@ +package com.wimdupont.sxcybot.enums; + +public enum Command { + + FORUM("Get forum link - BUMP IT UP!"), + PING("Get time in ms for bot to respond."), + RULE("Show rule by using command with rule number, separated by space."), + RULES("Show list of all the rules."), + // EVENT("Create an event."), + POLL("Start a poll with default options (Accept, Deny, Unsure), separate command by title with space."), + CPOLL("Start a custom poll - choose your own poll options and reaction emoji's, separate command by title with space."), + PVMPOLL("Poll current standings of the PvM Role competition."), + PVMCHECK("Check if PvM competitors can be found."), + HELP("Show all commands with description."), + + + //-----OSRS----- + STATS("Check HiScores for all stats, separate command by playername with space."), + CBSTATS("Check HiScores for combat stats, separate command by playername with space."), + KC("Check HiScores for all kc's, separate command by playername with space."), + PRICE("Check the GE for the latest price of an item, separate command by name of item with space."), + PVMLIST("Show list of PvM Role competitors."), + BOSSLIST("Shows list of all hiscore bosses with their PvM Role point multipliers."); + + public enum Admin { + + EDITRULE("Add/Edit/Delete record of rulelist."), + EDITBANLIST("Add/Edit/Delete record of banlist."), + BANLIST("Show list of banned users."), + ROLE("Add/remove a role to/from a member."), + EDITROLE("Add/Delete record of roles."), + EDITPVM("Add/Edit/Delete record of the PvM Role competition"); + + public final String description; + + Admin(String description) { + this.description = description; + } + } + + public final String description; + + Command(String description) { + this.description = description; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/enums/OsrsCombatStat.java b/src/main/java/com/wimdupont/sxcybot/enums/OsrsCombatStat.java @@ -0,0 +1,17 @@ +package com.wimdupont.sxcybot.enums; + +public enum OsrsCombatStat { + ATTACK("Attack"), + DEFENCE("Defence"), + HITPOINTS("Hitpoints"), + MAGIC("Magic"), + PRAYER("Prayer"), + RANGED("Ranged"), + STRENGTH("Strength"); + + public final String value; + + OsrsCombatStat(String value) { + this.value = value; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/enums/PvmRole.java b/src/main/java/com/wimdupont/sxcybot/enums/PvmRole.java @@ -0,0 +1,14 @@ +package com.wimdupont.sxcybot.enums; + +public enum PvmRole { + UNUSED(0), + GENERAL(1), + RAIDS(2), + WILDERNESS(3); + + public final int value; + + PvmRole(int value) { + this.value = value; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/exceptions/EntityNotFoundException.java b/src/main/java/com/wimdupont/sxcybot/exceptions/EntityNotFoundException.java @@ -0,0 +1,8 @@ +package com.wimdupont.sxcybot.exceptions; + +public class EntityNotFoundException extends Exception { + + public EntityNotFoundException(String msg) { + super(msg); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/exceptions/InsufficientPrivilegesException.java b/src/main/java/com/wimdupont/sxcybot/exceptions/InsufficientPrivilegesException.java @@ -0,0 +1,10 @@ +package com.wimdupont.sxcybot.exceptions; + +import java.util.List; + +public class InsufficientPrivilegesException extends Exception { + + public InsufficientPrivilegesException(List<String> rolelist) { + super(String.format("Only following ranks can execute this command: %s", rolelist)); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/AdminCommandListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/AdminCommandListener.java @@ -0,0 +1,124 @@ +package com.wimdupont.sxcybot.listeners; + +import com.wimdupont.sxcybot.enums.Command; +import com.wimdupont.sxcybot.enums.Command.Admin; +import com.wimdupont.sxcybot.exceptions.InsufficientPrivilegesException; +import com.wimdupont.sxcybot.listeners.admin.BanlistListener; +import com.wimdupont.sxcybot.listeners.admin.EditBanlistListener; +import com.wimdupont.sxcybot.listeners.admin.EditPvmListener; +import com.wimdupont.sxcybot.listeners.admin.EditRoleListener; +import com.wimdupont.sxcybot.listeners.admin.EditRuleListener; +import com.wimdupont.sxcybot.listeners.admin.RoleAssignListener; +import com.wimdupont.sxcybot.repository.guild.dao.GuildRole; +import com.wimdupont.sxcybot.services.guild.GuildRoleService; +import com.wimdupont.sxcybot.util.Constants.Commands; +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.springframework.stereotype.Component; + +import javax.annotation.Nonnull; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Stream; + +@Component +public class AdminCommandListener extends ListenerAdapter { + + private static final int GOD = 0; + private static final int ADMIN_ROLE = 1; + private static final int SUB_ADMIN = 5; + private static final int STAFF_ROLE = 10; + + private final EditRuleListener editRuleListener; + private final EditBanlistListener editBanlistListener; + private final RoleAssignListener roleAssignListener; + private final BanlistListener banlistListener; + private final EditRoleListener editRoleListener; + private final EditPvmListener editPvmListener; + private final GuildRoleService guildRoleService; + + public AdminCommandListener(EditRuleListener editRuleListener, + EditBanlistListener editBanlistListener, + RoleAssignListener roleAssignListener, + BanlistListener banlistListener, + EditRoleListener editRoleListener, + EditPvmListener editPvmListener, + GuildRoleService guildRoleService) { + this.editRuleListener = editRuleListener; + this.editBanlistListener = editBanlistListener; + this.roleAssignListener = roleAssignListener; + this.banlistListener = banlistListener; + this.editRoleListener = editRoleListener; + this.editPvmListener = editPvmListener; + this.guildRoleService = guildRoleService; + } + + @Override + public void onMessageReceived(@Nonnull MessageReceivedEvent event) { + if (event.getChannelType().isGuild()) { + String msg = event.getMessage().getContentRaw().toLowerCase(); + if (msg.startsWith(Commands.COMMAND_PREFIX)) { + Optional<Admin> adminCommand = messageToAdminCommand(msg); + if (adminCommand.isPresent() && event.getMember() != null) { + Stream<Role> roleStream = event.getMember().getRoles().stream(); + try { + switch (adminCommand.get()) { + case EDITRULE -> { + isPrivileged(roleStream, event, ADMIN_ROLE); + editRuleListener.proces(event); + } + case EDITBANLIST -> { + isPrivileged(roleStream, event, ADMIN_ROLE); + editBanlistListener.proces(event); + } + case ROLE -> { + isPrivileged(roleStream, event, SUB_ADMIN); + roleAssignListener.proces(event); + } + case BANLIST -> { + isPrivileged(roleStream, event, STAFF_ROLE); + banlistListener.proces(event); + } + case EDITROLE -> { + isPrivileged(roleStream, event, GOD); + editRoleListener.proces(event); + } + case EDITPVM -> { + isPrivileged(roleStream, event, STAFF_ROLE); + editPvmListener.proces(event); + } + default -> { + } + } + } catch (InsufficientPrivilegesException e) { + event.getChannel().sendMessage(e.getMessage()).queue(); + } + } + } + } + } + + private Optional<Admin> messageToAdminCommand(String msg) { + for (Admin adminCommand : Command.Admin.values()) { + if (msg.split(" ")[0].equals(Commands.COMMAND_PREFIX + adminCommand.name().toLowerCase())) { + return Optional.of(adminCommand); + } + } + return Optional.empty(); + } + + private void isPrivileged(Stream<Role> roleStream, MessageReceivedEvent event, int elevation) throws InsufficientPrivilegesException { + List<GuildRole> guildRoles = guildRoleService.findAllByElevationLessThanEqual(elevation); + if (roleStream.noneMatch(hasPrivilage(event, guildRoles))) + throw new InsufficientPrivilegesException(guildRoles.stream().map(GuildRole::getName).toList()); + } + + private Predicate<Role> hasPrivilage(MessageReceivedEvent event, List<GuildRole> guildRoles) { + return f -> f.hasPermission(Permission.ADMINISTRATOR) + || (event.getMember() != null && event.getMember().isOwner()) + || guildRoles.stream().map(GuildRole::getName).anyMatch(e -> e.equalsIgnoreCase(f.getName())); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/CommandListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/CommandListener.java @@ -0,0 +1,131 @@ +package com.wimdupont.sxcybot.listeners; + +import com.wimdupont.sxcybot.enums.Command; +import com.wimdupont.sxcybot.listeners.member.BB8Listener; +import com.wimdupont.sxcybot.listeners.member.CombatStatsListener; +import com.wimdupont.sxcybot.listeners.member.CustomPollListener; +import com.wimdupont.sxcybot.listeners.member.EventListener; +import com.wimdupont.sxcybot.listeners.member.ForumListener; +import com.wimdupont.sxcybot.listeners.member.HelpListener; +import com.wimdupont.sxcybot.listeners.member.HiscoreBossListener; +import com.wimdupont.sxcybot.listeners.member.KillCountListener; +import com.wimdupont.sxcybot.listeners.member.PingListener; +import com.wimdupont.sxcybot.listeners.member.PollListener; +import com.wimdupont.sxcybot.listeners.member.PriceListener; +import com.wimdupont.sxcybot.listeners.member.PvmListListener; +import com.wimdupont.sxcybot.listeners.member.PvmRoleCheckListener; +import com.wimdupont.sxcybot.listeners.member.PvmRolePollListener; +import com.wimdupont.sxcybot.listeners.member.RuleListener; +import com.wimdupont.sxcybot.listeners.member.RulesListener; +import com.wimdupont.sxcybot.listeners.member.StatsListener; +import com.wimdupont.sxcybot.util.Constants.Commands; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.springframework.stereotype.Component; + +import javax.annotation.Nonnull; +import java.util.Optional; + +@Component +public class CommandListener extends ListenerAdapter { + + private final BB8Listener bb8Listener; + private final RuleListener ruleListener; + private final RulesListener rulesListener; + private final PingListener pingListener; + private final EventListener eventListener; + private final ForumListener forumListener; + private final PollListener pollListener; + private final CustomPollListener customPollListener; + private final HelpListener helpListener; + private final StatsListener statsListener; + private final CombatStatsListener combatStatsListener; + private final PriceListener priceListener; + private final KillCountListener killCountListener; + private final PvmListListener pvmListListener; + private final HiscoreBossListener hiscoreBossListener; + private final PvmRoleCheckListener pvmRoleCheckListener; + private final PvmRolePollListener pvmRolePollListener; + + public CommandListener(BB8Listener bb8Listener, + RuleListener ruleListener, + RulesListener rulesListener, + PingListener pingListener, + EventListener eventListener, + ForumListener forumListener, + PollListener pollListener, + CustomPollListener customPollListener, + HelpListener helpListener, + StatsListener statsListener, + CombatStatsListener combatStatsListener, + PriceListener priceListener, + KillCountListener killCountListener, + PvmListListener pvmListListener, + HiscoreBossListener hiscoreBossListener, + PvmRoleCheckListener pvmRoleCheckListener, + PvmRolePollListener pvmRolePollListener) { + this.bb8Listener = bb8Listener; + this.ruleListener = ruleListener; + this.rulesListener = rulesListener; + this.pingListener = pingListener; + this.eventListener = eventListener; + this.forumListener = forumListener; + this.pollListener = pollListener; + this.customPollListener = customPollListener; + this.helpListener = helpListener; + this.statsListener = statsListener; + this.combatStatsListener = combatStatsListener; + this.priceListener = priceListener; + this.killCountListener = killCountListener; + this.pvmListListener = pvmListListener; + this.hiscoreBossListener = hiscoreBossListener; + this.pvmRoleCheckListener = pvmRoleCheckListener; + this.pvmRolePollListener = pvmRolePollListener; + } + + @Override + public void onMessageReceived(@Nonnull MessageReceivedEvent event) { + if (event.getChannelType().isGuild()) { + String msg = event.getMessage().getContentRaw().toLowerCase(); + if (msg.startsWith(Commands.COMMAND_PREFIX)) { + Optional<Command> command = messageToCommand(msg); + if (command.isPresent()) { + switch (command.get()) { + case RULE -> ruleListener.proces(event); + case RULES -> rulesListener.proces(event); + case PING -> pingListener.proces(event); + +// case EVENT: +// eventListener.proces(event); +// break; + case CBSTATS -> combatStatsListener.proces(event); + case STATS -> statsListener.proces(event); + case PRICE -> priceListener.proces(event); + case FORUM -> forumListener.proces(event); + case POLL -> pollListener.proces(event); + case CPOLL -> customPollListener.proces(event); + case KC -> killCountListener.proces(event); + case PVMLIST -> pvmListListener.proces(event); + case BOSSLIST -> hiscoreBossListener.proces(event); + case PVMPOLL -> pvmRolePollListener.proces(event); + case PVMCHECK -> pvmRoleCheckListener.proces(event); + case HELP -> helpListener.proces(event); + default -> { + } + } + } else if (Commands.BB8.equals(msg)) { + bb8Listener.proces(event); + } + } + } + } + + private Optional<Command> messageToCommand(String msg) { + for (Command command : Command.values()) { + if (msg.split(" ")[0].equals(Commands.COMMAND_PREFIX + command.name().toLowerCase())) { + return Optional.of(command); + } + } + return Optional.empty(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/EventWaiterUtil.java b/src/main/java/com/wimdupont/sxcybot/listeners/EventWaiterUtil.java @@ -0,0 +1,36 @@ +package com.wimdupont.sxcybot.listeners; + +import com.jagrosh.jdautilities.commons.waiter.EventWaiter; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Predicate; + +@Component +public class EventWaiterUtil extends EventWaiter { + + private static final int TIMEOUT = 1; + private static final TimeUnit TIME_UNIT = TimeUnit.MINUTES; + + public void waitForPrivateChannelEvent(Consumer<PrivateMessageReceivedEvent> action, PrivateMessageReceivedEvent event, PrivateChannel privateChannel) { + waitForEvent(PrivateMessageReceivedEvent.class, verifyAuthor(event), action, TIMEOUT, TIME_UNIT, new TimeOutRunner(privateChannel)); + } + + public void waitForPrivateChannelEvent(Consumer<PrivateMessageReceivedEvent> action, MessageReceivedEvent event, PrivateChannel privateChannel) { + waitForEvent(PrivateMessageReceivedEvent.class, verifyAuthor(event), action, TIMEOUT, TIME_UNIT, new TimeOutRunner(privateChannel)); + } + + private Predicate<PrivateMessageReceivedEvent> verifyAuthor(MessageReceivedEvent event) { + return messageReceivedEvent -> messageReceivedEvent.getAuthor().getId().equals(event.getAuthor().getId()); + } + + private Predicate<PrivateMessageReceivedEvent> verifyAuthor(PrivateMessageReceivedEvent event) { + return privateMessageReceivedEvent -> privateMessageReceivedEvent.getAuthor().getId().equals(event.getAuthor().getId()); + } + + +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/GuildMemberEventListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/GuildMemberEventListener.java @@ -0,0 +1,45 @@ +package com.wimdupont.sxcybot.listeners; + +import com.wimdupont.sxcybot.services.guild.GuildEventDmerService; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.Nonnull; +import java.util.Optional; + +@Component +public class GuildMemberEventListener extends ListenerAdapter { + + private static final Logger LOGGER = LoggerFactory.getLogger(GuildMemberEventListener.class); + private final GuildEventDmerService guildEventDmerService; + + public GuildMemberEventListener(GuildEventDmerService guildEventDmerService) { + this.guildEventDmerService = guildEventDmerService; + } + + @Override + public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { + guildEventDmerService.findAll().forEach(guildEventDmer -> + event.getGuild().loadMembers().onSuccess(memberList -> { + if (!memberList.isEmpty()) { + Optional<Member> member = memberList.stream().filter(f -> guildEventDmer.getName().equalsIgnoreCase(f.getUser().getName())).findFirst(); + if (member.isPresent()) { + try { + PrivateChannel privateChannel = member.get().getUser().openPrivateChannel().complete(true); + privateChannel.sendMessage(String.format("**%s** has been removed from channel _%s_", event.getUser().getName(), event.getGuild().getName())).queue(); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } + }) + ); + } +} + diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/Listener.java b/src/main/java/com/wimdupont/sxcybot/listeners/Listener.java @@ -0,0 +1,7 @@ +package com.wimdupont.sxcybot.listeners; + +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; + +public interface Listener { + void proces(MessageReceivedEvent event); +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/PollReactionListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/PollReactionListener.java @@ -0,0 +1,111 @@ +package com.wimdupont.sxcybot.listeners; + +import com.wimdupont.sxcybot.services.guild.PollService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.MessageEmbed.Field; +import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; +import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.springframework.stereotype.Component; + +import javax.annotation.Nonnull; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Component +public class PollReactionListener extends ListenerAdapter { + + private final PollService pollService; + + public PollReactionListener(PollService pollService) { + this.pollService = pollService; + } + + @Override + public void onMessageReactionAdd(@Nonnull MessageReactionAddEvent event) { + if (isPoll(event)) { + event.getChannel().retrieveMessageById(event.getMessageId()).queue(message -> { + if (message.getEmbeds().size() == 1) { + MessageEmbed messageEmbed = message.getEmbeds().get(0); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setTitle(messageEmbed.getTitle()); + embedBuilder.setColor(messageEmbed.getColor()); + embedBuilder.setFooter(String.format("Last voted on %s", LocalDate.now()), event.getGuild().getIconUrl()); + String username = JdaUtil.getName(event).orElse(null); + for (MessageEmbed.Field field : messageEmbed.getFields()) { + List<String> nameSplit = field.getValue() != null ? new ArrayList<>(Arrays.asList(field.getValue().split(System.lineSeparator()))) : null; + if (field.getValue() != null && username != null && nameSplit.remove(username)) { + String value = String.join(System.lineSeparator(), nameSplit); + embedBuilder.addField(field); + embedBuilder.getFields() + .set(messageEmbed.getFields().indexOf(field), + new Field(getFieldNameWithCount(field, value), value, field.isInline())); + } else { + if (field.getName() != null && field.getName().contains(event.getReactionEmote().getEmoji())) { + String value = !field.getValue().contains("‎") + ? field.getValue() + System.lineSeparator() + username : username; + embedBuilder.addField(getFieldNameWithCount(field, value), value, field.isInline()); + } else { + embedBuilder.addField(field); + } + } + } + message.editMessageEmbeds(embedBuilder.build()).queue(); + message.removeReaction(event.getReaction().getReactionEmote().getEmoji(), event.getUser()).queue(); + } + }); + } + } + + public String getFieldNameWithCount(Field field, String updatedValue) { + return field.getName().replaceAll("\\(+\\d+\\)+", String.format("(%s)", getCount(updatedValue))); + } + + private long getCount(String fieldValue) { + if (fieldValue.isEmpty()) { + return 0; + } + return Arrays.stream(fieldValue.split(System.lineSeparator())).count(); + + } +// @Override +// public void onMessageReactionRemove(@Nonnull MessageReactionRemoveEvent event) { +// //event.user is null here! +// if (pollService.findByMessageId(event.getMessageId()).isPresent()) { +// event.getJDA().retrieveUserById(event.getUserId()).queue(user -> { +// if (!user.isBot()) { +// event.getChannel().retrieveMessageById(event.getMessageId()).queue(message -> { +// if (message.getEmbeds().size() == 1) { +// MessageEmbed messageEmbed = message.getEmbeds().get(0); +// EmbedBuilder embedBuilder = new EmbedBuilder(); +// embedBuilder.setTitle(messageEmbed.getTitle()); +// embedBuilder.setColor(messageEmbed.getColor()); +// for (MessageEmbed.Field field : messageEmbed.getFields()) { +// embedBuilder.addField(field); +// if (field.getName() != null && field.getName().contains(event.getReactionEmote().getEmoji())) { +// if (field.getValue() != null) { +// embedBuilder.getFields() +// .set(messageEmbed.getFields().indexOf(field), +// new Field(field.getName(), field.getValue().replace(user.getName(), ""), field.isInline())); +// message.editMessageEmbeds(embedBuilder.build()).queue(); +// } +// } +// } +// message.editMessageEmbeds(embedBuilder.build()).queue(); +// } +// }); +// } +// }); +// } +// } + + private boolean isPoll(GenericMessageReactionEvent event) { + return event.getUser() != null + && !event.getUser().isBot() + && pollService.findByMessageId(event.getMessageId()).isPresent(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/PrivateListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/PrivateListener.java @@ -0,0 +1,9 @@ +package com.wimdupont.sxcybot.listeners; + +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; + +public interface PrivateListener { + + void proces(PrivateMessageReceivedEvent privateEvent, MessageReceivedEvent event); +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/TimeOutRunner.java b/src/main/java/com/wimdupont/sxcybot/listeners/TimeOutRunner.java @@ -0,0 +1,28 @@ +package com.wimdupont.sxcybot.listeners; + +import net.dv8tion.jda.api.entities.MessageChannel; + +public class TimeOutRunner implements Runnable { + + private final MessageChannel messageChannel; + + public TimeOutRunner(MessageChannel messageChannel) { + this.messageChannel = messageChannel; + } + + /** + * When an object implementing interface {@code Runnable} is used + * to create a thread, starting the thread causes the object's + * {@code run} method to be called in that separately executing + * thread. + * <p> + * The general contract of the method {@code run} is that it may + * take any action whatsoever. + * + * @see Thread#run() + */ + @Override + public void run() { + messageChannel.sendMessage("Timed out... Please try again later.").queue(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/BanlistListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/BanlistListener.java @@ -0,0 +1,57 @@ +package com.wimdupont.sxcybot.listeners.admin; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.repository.guild.dao.User; +import com.wimdupont.sxcybot.services.guild.UserService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.List; + + +@Component +public class BanlistListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(BanlistListener.class); + private final UserService userService; + + public BanlistListener(UserService userService) { + this.userService = userService; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle("List of banned users:"); + List<User> bannedList = userService.findAllBanned(); + int i = 1; + for (User user : bannedList) { + embedBuilder.addField(user.getName(), + String.format("%s", user.getDescription()) + System.lineSeparator() + + String.format("||_By: %s - %s | Last edit: %s - %s_||", + user.getCreatedBy(), user.getCreatedDate(), user.getLastModifiedBy(), user.getLastModifiedDate()), + false); + + if (JdaUtil.requiresBuild(embedBuilder, bannedList.size(), i)) { + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clear(); + } + i++; + } + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditBanlistListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditBanlistListener.java @@ -0,0 +1,54 @@ +package com.wimdupont.sxcybot.listeners.admin; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.listeners.admin.banlist.AddBanlistUserListener; +import com.wimdupont.sxcybot.listeners.admin.banlist.DeleteBanlistUserListener; +import com.wimdupont.sxcybot.listeners.admin.banlist.UpdateBanlistUserListener; +import com.wimdupont.sxcybot.model.EditListenerDto; +import com.wimdupont.sxcybot.util.EditListenerUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class EditBanlistListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(EditBanlistListener.class); + private final AddBanlistUserListener addBanlistUserListener; + private final UpdateBanlistUserListener updateBanlistListener; + private final DeleteBanlistUserListener deleteBanlistListener; + private final EditListenerUtil editListenerUtil; + + public EditBanlistListener(AddBanlistUserListener addBanlistUserListener, + UpdateBanlistUserListener updateBanlistListener, + DeleteBanlistUserListener deleteBanlistListener, + EditListenerUtil editListenerUtil) { + this.addBanlistUserListener = addBanlistUserListener; + this.updateBanlistListener = updateBanlistListener; + this.deleteBanlistListener = deleteBanlistListener; + this.editListenerUtil = editListenerUtil; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() + .addListener(addBanlistUserListener) + .updateListener(updateBanlistListener) + .deleteListener(deleteBanlistListener) + .event(event) + .privateChannel(privateChannel) + .entityName("user to banlist") + .build(); + editListenerUtil.procesEditEvent(editListenerDto); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditPvmListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditPvmListener.java @@ -0,0 +1,54 @@ +package com.wimdupont.sxcybot.listeners.admin; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.listeners.admin.pvmrole.AddPvmListener; +import com.wimdupont.sxcybot.listeners.admin.pvmrole.DeletePvmListener; +import com.wimdupont.sxcybot.listeners.admin.pvmrole.UpdatePvmListener; +import com.wimdupont.sxcybot.model.EditListenerDto; +import com.wimdupont.sxcybot.util.EditListenerUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class EditPvmListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(EditPvmListener.class); + private final EditListenerUtil editListenerUtil; + private final AddPvmListener addPvmListener; + private final UpdatePvmListener updatePvmListener; + private final DeletePvmListener deletePvmListener; + + public EditPvmListener(EditListenerUtil editListenerUtil, + AddPvmListener addPvmListener, + UpdatePvmListener updatePvmListener, + DeletePvmListener deletePvmListener) { + this.editListenerUtil = editListenerUtil; + this.addPvmListener = addPvmListener; + this.updatePvmListener = updatePvmListener; + this.deletePvmListener = deletePvmListener; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() + .addListener(addPvmListener) + .updateListener(updatePvmListener) + .deleteListener(deletePvmListener) + .event(event) + .privateChannel(privateChannel) + .entityName("PvM competitor") + .build(); + editListenerUtil.procesEditEvent(editListenerDto); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditRoleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditRoleListener.java @@ -0,0 +1,55 @@ +package com.wimdupont.sxcybot.listeners.admin; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.listeners.admin.role.AddRoleListener; +import com.wimdupont.sxcybot.listeners.admin.role.DeleteRoleListener; +import com.wimdupont.sxcybot.listeners.admin.role.UpdateRoleListener; +import com.wimdupont.sxcybot.model.EditListenerDto; +import com.wimdupont.sxcybot.util.EditListenerUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class EditRoleListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(EditRoleListener.class); + private final AddRoleListener addRoleListener; + private final UpdateRoleListener updateRoleListener; + private final DeleteRoleListener deleteRoleListener; + private final EditListenerUtil editListenerUtil; + + public EditRoleListener(AddRoleListener addRoleListener, + UpdateRoleListener updateRoleListener, + DeleteRoleListener deleteRoleListener, + EditListenerUtil editListenerUtil) { + this.addRoleListener = addRoleListener; + this.updateRoleListener = updateRoleListener; + this.deleteRoleListener = deleteRoleListener; + this.editListenerUtil = editListenerUtil; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() + .addListener(addRoleListener) + .deleteListener(deleteRoleListener) + //TODO why not implemented? +// .updateListener(updateRoleListener) + .event(event) + .privateChannel(privateChannel) + .entityName("role") + .build(); + editListenerUtil.procesEditEvent(editListenerDto); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditRuleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/EditRuleListener.java @@ -0,0 +1,54 @@ +package com.wimdupont.sxcybot.listeners.admin; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.listeners.admin.rule.AddRuleListener; +import com.wimdupont.sxcybot.listeners.admin.rule.DeleteRuleListener; +import com.wimdupont.sxcybot.listeners.admin.rule.UpdateRuleListener; +import com.wimdupont.sxcybot.model.EditListenerDto; +import com.wimdupont.sxcybot.util.EditListenerUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class EditRuleListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(EditRuleListener.class); + private final AddRuleListener addRuleListener; + private final UpdateRuleListener updateRuleListener; + private final DeleteRuleListener deleteRuleListener; + private final EditListenerUtil editListenerUtil; + + public EditRuleListener(AddRuleListener addRuleListener, + UpdateRuleListener updateRuleListener, + DeleteRuleListener deleteRuleListener, + EditListenerUtil editListenerUtil) { + this.addRuleListener = addRuleListener; + this.updateRuleListener = updateRuleListener; + this.deleteRuleListener = deleteRuleListener; + this.editListenerUtil = editListenerUtil; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + EditListenerDto editListenerDto = EditListenerDto.Builder.newBuilder() + .addListener(addRuleListener) + .updateListener(updateRuleListener) + .deleteListener(deleteRuleListener) + .event(event) + .privateChannel(privateChannel) + .entityName("rule") + .build(); + editListenerUtil.procesEditEvent(editListenerDto); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/RoleAssignListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/RoleAssignListener.java @@ -0,0 +1,99 @@ +package com.wimdupont.sxcybot.listeners.admin; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.repository.guild.dao.GuildRole; +import com.wimdupont.sxcybot.services.guild.GuildRoleService; +import com.wimdupont.sxcybot.util.DiscordMemberFinderUtil; +import com.wimdupont.sxcybot.util.Constants; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; + +@Component +public class RoleAssignListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(RoleAssignListener.class); + private final EventWaiterUtil eventWaiterUtil; + private final GuildRoleService guildRoleService; + private final DiscordMemberFinderUtil discordMemberFinderUtil; + + public RoleAssignListener(EventWaiterUtil eventWaiterUtil, + GuildRoleService guildRoleService, + DiscordMemberFinderUtil discordMemberFinderUtil) { + this.eventWaiterUtil = eventWaiterUtil; + this.guildRoleService = guildRoleService; + this.discordMemberFinderUtil = discordMemberFinderUtil; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.RED); + discordMemberFinderUtil.onMemberFoundVerification(event, embedBuilder, privateChannel, member -> { + embedBuilder.clearFields(); + embedBuilder.setTitle("Type the numbers of the roles to add separated by a whitespace. If the member already has any role, it will get removed instead."); + List<GuildRole> rolesToAdd = guildRoleService.findAllByElevationGreaterThanEqual(Constants.ADDED_ROLE_ELEVATION) + .stream().sorted(Comparator.nullsLast(Comparator.comparing(GuildRole::getOrderValue))).toList(); + for (GuildRole guildRole : rolesToAdd) { + embedBuilder.addField(String.valueOf(guildRole.getOrderValue()), String.valueOf(guildRole.getName()), true); + } + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + eventWaiterUtil.waitForPrivateChannelEvent(roleReceiver -> { + String roleMessage = roleReceiver.getMessage().getContentRaw(); +// try { + String[] roleNumbers = roleMessage.split(" "); + embedBuilder.clearFields(); + embedBuilder.setTitle("Role assigner:"); + for (String roleNumber : roleNumbers) { + try { + Optional<GuildRole> discordRole = rolesToAdd.stream().filter(f -> Integer.parseInt(roleNumber) == f.getOrderValue()).findFirst(); + if (discordRole.isPresent()) { + Optional<Role> role = event.getGuild().getRoles().stream().filter(f -> discordRole.get().getName().equalsIgnoreCase(f.getName())).findFirst(); + if (role.isPresent()) { + String action; + if (member.getRoles().contains(role.get())) { + event.getGuild().removeRoleFromMember(member, role.get()).queue(); + action = "removed"; + } else { + event.getGuild().addRoleToMember(member, role.get()).queue(); + action = "assigned"; + } + embedBuilder.addField(String.format("\"%s\" has been succesfully %s.", discordRole.get().getName(), action), "", false); + event.getChannel().sendMessage(String.format("Role \"%s\" has been %s to %s by %s", + role.get().getName(), action, member.getUser(), event.getMember().getUser().getName())).queue(); + } else { + privateChannel.sendMessage("No such role is available in the channel, please contact your channel owner.").queue(); + } + } else { + privateChannel.sendMessage(String.format("%s is not in the suggested list, please try again later.", roleNumber)).queue(); + } + } catch (NumberFormatException e) { + privateChannel.sendMessage(String.format("%s is not a valid number, please try again later.", roleNumber)).queue(); + } + } + if (embedBuilder.getFields().isEmpty()) { + embedBuilder.addField("No roles changed.", "", false); + } + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + }, event, privateChannel); + }); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/AddBanlistUserListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/AddBanlistUserListener.java @@ -0,0 +1,47 @@ +package com.wimdupont.sxcybot.listeners.admin.banlist; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.User; +import com.wimdupont.sxcybot.services.guild.UserService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +@Component +public class AddBanlistUserListener implements PrivateListener { + + private final EventWaiterUtil eventWaiterUtil; + private final UserService userService; + + public AddBanlistUserListener(EventWaiterUtil eventWaiterUtil, + UserService userService) { + this.eventWaiterUtil = eventWaiterUtil; + this.userService = userService; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Name of the user you want to ban?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { + privateChannel.sendMessage("Description?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { + User userToBan = User.Builder.newBuilder() + .name(nameReceiver.getMessage().getContentRaw()) + .description(descriptionReceiver.getMessage().getContentRaw()) + .banned(true) + .createdBy(JdaUtil.getName(event).orElse(null)) + .lastModifiedBy(JdaUtil.getName(event).orElse(null)) + .build(); + User bannedUser = userService.save(userToBan); + privateChannel.sendMessage(String.format("User %s has been succesfully banned.", bannedUser.getName())).queue(); + event.getChannel().sendMessage(String.format("User %s has been banned by %s. (%s)", + bannedUser.getName(), JdaUtil.getUser(event), bannedUser.getDescription() + )).queue(); + }, privateMessageReceivedEvent, privateChannel); + }, privateMessageReceivedEvent, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/DeleteBanlistUserListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/DeleteBanlistUserListener.java @@ -0,0 +1,41 @@ +package com.wimdupont.sxcybot.listeners.admin.banlist; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.User; +import com.wimdupont.sxcybot.services.guild.UserService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +@Component +public class DeleteBanlistUserListener implements PrivateListener { + + private final UserService userService; + private final EventWaiterUtil eventWaiterUtil; + + public DeleteBanlistUserListener(UserService userService, + EventWaiterUtil eventWaiterUtil) { + this.userService = userService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateEvent.getChannel(); + privateChannel.sendMessage("Name of the user you want to delete?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { + try { + User userToDelete = userService.findByName(nameReceiver.getMessage().getContentRaw()); + userService.delete(userToDelete); + privateChannel.sendMessage(String.format("%s succesfully deleted.", userToDelete)).queue(); + event.getChannel().sendMessage(String.format("User %s has been deleted from the banlist by %s", userToDelete, JdaUtil.getUser(event))).queue(); + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, event, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/UpdateBanlistUserListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/banlist/UpdateBanlistUserListener.java @@ -0,0 +1,59 @@ +package com.wimdupont.sxcybot.listeners.admin.banlist; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.User; +import com.wimdupont.sxcybot.services.guild.UserService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class UpdateBanlistUserListener implements PrivateListener { + + private final EventWaiterUtil eventWaiterUtil; + private final UserService userService; + + public UpdateBanlistUserListener(EventWaiterUtil eventWaiterUtil, + UserService userService) { + this.eventWaiterUtil = eventWaiterUtil; + this.userService = userService; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Name of the user you want to update (\"showlist\" to show all names in banlist).").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { + if (nameReceiver.getMessage().getContentRaw().equalsIgnoreCase("showlist")) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle("Banned users:"); + userService.findAllBanned().stream().map(User::getName).toList().forEach(f -> + embedBuilder.addField(f, "", false)); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + this.proces(privateMessageReceivedEvent, event); + return; + } + try { + User userToUpdate = userService.findByName(nameReceiver.getMessage().getContentRaw()); + privateChannel.sendMessage(String.format("Type the new description for the ban of %s.", nameReceiver.getMessage().getContentRaw())).queue(); + eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { + userToUpdate.setDescription(descriptionReceiver.getMessage().getContentRaw()); + userToUpdate.setLastModifiedBy(JdaUtil.getName(event).orElse(null)); + User saved = userService.save(userToUpdate); + privateChannel.sendMessage(saved + " edited.").queue(); + event.getChannel().sendMessage(String.format("Banned user %s has been edited by %s.", saved.getName(), JdaUtil.getUser(event))).queue(); + }, privateMessageReceivedEvent, privateChannel); + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, event, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/AddPvmListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/AddPvmListener.java @@ -0,0 +1,78 @@ +package com.wimdupont.sxcybot.listeners.admin.pvmrole; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleSnapshotComparatorService; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; +import com.wimdupont.sxcybot.util.DiscordMemberFinderUtil; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class AddPvmListener implements PrivateListener { + + private final EventWaiterUtil eventWaiterUtil; + private final DiscordMemberFinderUtil discordMemberFinderUtil; + private final PvmRoleUserService pvmRoleUserService; + private final PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService; + + public AddPvmListener(EventWaiterUtil eventWaiterUtil, + DiscordMemberFinderUtil discordMemberFinderUtil, + PvmRoleUserService pvmRoleUserService, + PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService) { + this.eventWaiterUtil = eventWaiterUtil; + this.discordMemberFinderUtil = discordMemberFinderUtil; + this.pvmRoleUserService = pvmRoleUserService; + this.pvmRoleSnapshotComparatorService = pvmRoleSnapshotComparatorService; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.RED); + embedBuilder.setTitle("Add member for PvM competition"); + discordMemberFinderUtil.onMemberFoundVerification(event, embedBuilder, privateChannel, member -> { + embedBuilder.clearFields(); + embedBuilder.addField("Type the RSN (RuneScape name) of the member.", "", true); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + eventWaiterUtil.waitForPrivateChannelEvent((rsnReceiver) -> { + String creator = JdaUtil.getName(event).orElse(null); + try { + PvmRoleUser pvmRoleUser = pvmRoleUserService.save(PvmRoleUser.Builder.newBuilder() + .discordName(member.getEffectiveName()) + .rsn(rsnReceiver.getMessage().getContentRaw()) + .discordId(member.getUser().getId()) + .createdBy(creator) + .lastModifiedBy(creator) + .build() + ); + event.getChannel().sendMessage(String.format("%s (RSN: %s) has been added to the PvM competition by %s!", + member, pvmRoleUser.getRsn(), creator)).queue(); + privateChannel.sendMessage(String.format("%s (RSN: %s) has been succesfully added!", + member, pvmRoleUser.getRsn())).queue(); + try { + pvmRoleSnapshotComparatorService.takeSnapshot(event.getChannel(), pvmRoleUser, true, true); + } catch (EntityNotFoundException e) { + event.getChannel().sendMessage(e.getMessage()).queue(); + } + } catch (DataIntegrityViolationException e) { + if (e.getRootCause() != null) { + privateChannel.sendMessage(e.getRootCause().getMessage()).queue(); + } else if (e.getMessage() != null) + privateChannel.sendMessage(e.getMessage()).queue(); + privateChannel.sendMessage("Please try updating the existing PvM competitor instead.").queue(); + } + }, event, privateChannel); + }); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/DeletePvmListener.java @@ -0,0 +1,47 @@ +package com.wimdupont.sxcybot.listeners.admin.pvmrole; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmKcSnapshotService; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +@Component +public class DeletePvmListener implements PrivateListener { + + private final PvmRoleUserService pvmRoleUserService; + private final PvmKcSnapshotService pvmKcSnapshotService; + private final EventWaiterUtil eventWaiterUtil; + + public DeletePvmListener(PvmRoleUserService pvmRoleUserService, + PvmKcSnapshotService pvmKcSnapshotService, + EventWaiterUtil eventWaiterUtil) { + this.pvmRoleUserService = pvmRoleUserService; + this.pvmKcSnapshotService = pvmKcSnapshotService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Type the discord name of the user you want to delete.").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(discordNameReceiver -> { + String discordName = discordNameReceiver.getMessage().getContentRaw(); + try { + PvmRoleUser pvmRoleUser = pvmRoleUserService.findByDiscordName(discordName); + pvmKcSnapshotService.deleteAll(pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser)); + pvmRoleUserService.delete(pvmRoleUser); + privateChannel.sendMessage(String.format("%s has been succesfully deleted.", pvmRoleUser)).queue(); + event.getChannel().sendMessage(String.format("PvM competitor %s has been deleted by %s", discordName, JdaUtil.getUser(event))).queue(); + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/pvmrole/UpdatePvmListener.java @@ -0,0 +1,79 @@ +package com.wimdupont.sxcybot.listeners.admin.pvmrole; + +import com.wimdupont.sxcybot.enums.Command; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; +import com.wimdupont.sxcybot.util.Constants.Commands; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class UpdatePvmListener implements PrivateListener { + + private final PvmRoleUserService pvmRoleUserService; + private final EventWaiterUtil eventWaiterUtil; + + public UpdatePvmListener(PvmRoleUserService pvmRoleUserService, + EventWaiterUtil eventWaiterUtil) { + this.pvmRoleUserService = pvmRoleUserService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.RED); + embedBuilder.setTitle("Update user for PvM competition."); + embedBuilder.addField("Type the discord name of the user you want to update.", "", false); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + eventWaiterUtil.waitForPrivateChannelEvent(discordNameReceiver -> { + String discordName = discordNameReceiver.getMessage().getContentRaw(); + try { + PvmRoleUser pvmRoleUserToUpdate = pvmRoleUserService.findByDiscordName(discordName); + embedBuilder.addField("Confirm by typing ``yes or y``.", + String.format("Is " + System.lineSeparator() + "Discord: %s | RSN: %s " + System.lineSeparator() + "the correct member?" + , pvmRoleUserToUpdate.getDiscordName(), pvmRoleUserToUpdate.getRsn()), false); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + eventWaiterUtil.waitForPrivateChannelEvent(memberVerifyReceiver -> { + String verifyMessage = memberVerifyReceiver.getMessage().getContentRaw(); + if ("y".equalsIgnoreCase(verifyMessage) || "yes".equalsIgnoreCase(verifyMessage)) { + embedBuilder.addField("Type the new RSN for the update.", "", false); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + eventWaiterUtil.waitForPrivateChannelEvent(newRsnReceiver -> { + String newRsn = newRsnReceiver.getMessage().getContentRaw(); + pvmRoleUserToUpdate.setRsn(newRsn); + pvmRoleUserToUpdate.setLastModifiedBy(JdaUtil.getName(event).orElse(null)); + try { + PvmRoleUser savedPvmRoleUser = pvmRoleUserService.save(pvmRoleUserToUpdate); + newRsnReceiver.getChannel().sendMessage(savedPvmRoleUser + " edited").queue(); + event.getChannel().sendMessage(String.format("RSN for PvM competitor %s has been changed to %s by %s", + discordName, newRsn, JdaUtil.getUser(event))).queue(); + } catch (DataIntegrityViolationException e) { + if (e.getMessage() != null) + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } else { + privateChannel.sendMessage(String.format("You can check all competitors with the \"%s\" command.", Commands.COMMAND_PREFIX + Command.PVMLIST.name().toLowerCase())).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/role/AddRoleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/role/AddRoleListener.java @@ -0,0 +1,55 @@ +package com.wimdupont.sxcybot.listeners.admin.role; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.GuildRole; +import com.wimdupont.sxcybot.services.guild.GuildRoleService; +import com.wimdupont.sxcybot.util.JdaUtil; +import com.wimdupont.sxcybot.util.Constants; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.util.Comparator; +import java.util.Optional; + +@Component +public class AddRoleListener implements PrivateListener { + + private final GuildRoleService guildRoleService; + private final EventWaiterUtil eventWaiterUtil; + + public AddRoleListener(GuildRoleService guildRoleService, + EventWaiterUtil eventWaiterUtil) { + this.guildRoleService = guildRoleService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Name of the role you want to add?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { + String roleName = nameReceiver.getMessage().getContentRaw(); + Optional<Role> role = event.getGuild().getRoles().stream().filter(f -> roleName.equalsIgnoreCase(f.getName())).findFirst(); + if (role.isPresent()) { + int orderValue = guildRoleService.findAll().stream().filter(f -> f.getOrderValue() != null).max(Comparator.comparing(GuildRole::getOrderValue)).map(GuildRole::getOrderValue).orElse(0) + 1; + GuildRole roleToAdd = GuildRole.Builder.newBuilder() + .name(roleName) + .orderValue(orderValue) + .elevation(Constants.ADDED_ROLE_ELEVATION) + .build(); + GuildRole guildRole = guildRoleService.save(roleToAdd); + privateChannel.sendMessage(String.format("Role %s has been succesfully added.", guildRole.getName())).queue(); + event.getChannel().sendMessage(String.format("Role %s has been added by %s.", + guildRole.getName(), JdaUtil.getUser(event) + )).queue(); + } else { + privateChannel.sendMessage(String.format("Role with name %s is not available in the channel, please contact a channel owner to have it added.", roleName)).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/role/DeleteRoleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/role/DeleteRoleListener.java @@ -0,0 +1,52 @@ +package com.wimdupont.sxcybot.listeners.admin.role; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.GuildRole; +import com.wimdupont.sxcybot.services.guild.GuildRoleService; +import com.wimdupont.sxcybot.util.JdaUtil; +import com.wimdupont.sxcybot.util.Constants; +import com.wimdupont.sxcybot.util.Constants.Commands; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +@Component +public class DeleteRoleListener implements PrivateListener { + + private final GuildRoleService guildRoleService; + private final EventWaiterUtil eventWaiterUtil; + + public DeleteRoleListener(GuildRoleService guildRoleService, + EventWaiterUtil eventWaiterUtil) { + this.guildRoleService = guildRoleService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Name of the role you want to delete?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { + try { + GuildRole guildRole = guildRoleService.findByName(nameReceiver.getMessage().getContentRaw()); + if (guildRole.getElevation() == Constants.ADDED_ROLE_ELEVATION) { + guildRoleService.delete(guildRole); + guildRoleService.findAll().stream().filter(f -> f.getOrderValue() != null && f.getOrderValue() > guildRole.getOrderValue()).toList() + .forEach(role -> { + role.setOrderValue(role.getOrderValue() - 1); + guildRoleService.save(role); + }); + privateChannel.sendMessage(String.format("%s succesfully deleted.", guildRole)).queue(); + event.getChannel().sendMessage(String.format("Role %s has been deleted by %s", guildRole, JdaUtil.getUser(event))).queue(); + } else { + privateChannel.sendMessage(String.format("Only roles that can be added with the %srole command can be deleted.", Commands.COMMAND_PREFIX)).queue(); + } + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, event, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/role/UpdateRoleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/role/UpdateRoleListener.java @@ -0,0 +1,54 @@ +package com.wimdupont.sxcybot.listeners.admin.role; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.GuildRole; +import com.wimdupont.sxcybot.services.guild.GuildRoleService; +import com.wimdupont.sxcybot.util.JdaUtil; +import com.wimdupont.sxcybot.util.Constants; +import com.wimdupont.sxcybot.util.Constants.Commands; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +@Component +public class UpdateRoleListener implements PrivateListener { + + private final GuildRoleService guildRoleService; + private final EventWaiterUtil eventWaiterUtil; + + public UpdateRoleListener(GuildRoleService guildRoleService, + EventWaiterUtil eventWaiterUtil) { + this.guildRoleService = guildRoleService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Type the name of the role you want to update.").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(oldRoleNameReceiver -> { + String roleName = oldRoleNameReceiver.getMessage().getContentRaw(); + privateChannel.sendMessage("Type the new name for the role.").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(newRoleNameReceiver -> { + try { + GuildRole oldRole = guildRoleService.findByName(roleName); + if (oldRole.getElevation() == Constants.ADDED_ROLE_ELEVATION) { + GuildRole guildRoleToUpdate = guildRoleService.findByName(roleName); + guildRoleToUpdate.setName(newRoleNameReceiver.getMessage().getContentRaw()); + + GuildRole guildRole = guildRoleService.save(guildRoleToUpdate); + newRoleNameReceiver.getChannel().sendMessage(guildRole + " edited").queue(); + event.getChannel().sendMessage(String.format("Role %s has been changed to %s by %s", roleName, newRoleNameReceiver.getMessage().getContentRaw(), JdaUtil.getUser(event))).queue(); + } else { + privateChannel.sendMessage(String.format("Only roles that can be added with the %srole command can be updated.", Commands.COMMAND_PREFIX)).queue(); + } + } catch (EntityNotFoundException exc) { + oldRoleNameReceiver.getChannel().sendMessage(exc.getMessage()).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + }, privateMessageReceivedEvent, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/rule/AddRuleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/rule/AddRuleListener.java @@ -0,0 +1,40 @@ +package com.wimdupont.sxcybot.listeners.admin.rule; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.Rule; +import com.wimdupont.sxcybot.services.guild.RuleService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.util.Comparator; + +@Component +public class AddRuleListener implements PrivateListener { + + private final RuleService ruleService; + private final EventWaiterUtil eventWaiterUtil; + + public AddRuleListener(RuleService ruleService, + EventWaiterUtil eventWaiterUtil) { + this.ruleService = ruleService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + privateMessageReceivedEvent.getChannel().sendMessage("Type rule description please").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(e -> { + String msg = e.getMessage().getContentRaw(); + int number = ruleService.findAll().stream().max(Comparator.comparing(Rule::getNumber)).map(Rule::getNumber).orElse(0) + 1; + Rule rule = ruleService.save(Rule.Builder.newBuilder() + .number(number) + .description(msg) + .build()); + e.getChannel().sendMessage(rule + " saved").queue(); + event.getChannel().sendMessage(String.format("Rule #%s has been added by %s.", number, JdaUtil.getUser(event))).queue(); + }, privateMessageReceivedEvent, privateMessageReceivedEvent.getChannel()); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/rule/DeleteRuleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/rule/DeleteRuleListener.java @@ -0,0 +1,51 @@ +package com.wimdupont.sxcybot.listeners.admin.rule; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.Rule; +import com.wimdupont.sxcybot.services.guild.RuleService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + + +@Component +public class DeleteRuleListener implements PrivateListener { + + private final RuleService ruleService; + private final EventWaiterUtil eventWaiterUtil; + + public DeleteRuleListener(RuleService ruleService, + EventWaiterUtil eventWaiterUtil) { + this.ruleService = ruleService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Type the # of the rule you wish to delete please.").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(ruleDeleltionReceiver -> { + try { + int ruleNumber = Integer.parseInt(ruleDeleltionReceiver.getMessage().getContentRaw()); + Rule rule = ruleService.findByNumber(ruleNumber); + ruleService.delete(rule); + ruleService.findAll().stream().filter(f -> f.getNumber() > ruleNumber).toList() + .forEach(ruleToUpdate -> { + ruleToUpdate.setNumber(ruleToUpdate.getNumber() - 1); + ruleService.save(ruleToUpdate); + }); + privateChannel.sendMessage(String.format("%s has been succesfully deleted.", rule)).queue(); + event.getChannel().sendMessage(String.format("Rule %s has been deleted by %s", rule, JdaUtil.getUser(event))).queue(); + } catch (NumberFormatException e) { + privateChannel.sendMessage("Please try again later with a valid rule number.").queue(); + } catch (EntityNotFoundException e) { + privateChannel.sendMessage(e.getMessage()).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/admin/rule/UpdateRuleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/admin/rule/UpdateRuleListener.java @@ -0,0 +1,51 @@ +package com.wimdupont.sxcybot.listeners.admin.rule; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.PrivateListener; +import com.wimdupont.sxcybot.repository.guild.dao.Rule; +import com.wimdupont.sxcybot.services.guild.RuleService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.stereotype.Component; + + +@Component +public class UpdateRuleListener implements PrivateListener { + + private final RuleService ruleService; + private final EventWaiterUtil eventWaiterUtil; + + public UpdateRuleListener(RuleService ruleService, + EventWaiterUtil eventWaiterUtil) { + this.ruleService = ruleService; + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(PrivateMessageReceivedEvent privateMessageReceivedEvent, MessageReceivedEvent event) { + PrivateChannel privateChannel = privateMessageReceivedEvent.getChannel(); + privateChannel.sendMessage("Type the rule number you want to update.").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(ruleNumberReciever -> { + try { + int ruleNumber = Integer.parseInt(ruleNumberReciever.getMessage().getContentRaw()); + privateChannel.sendMessage(String.format("Type the new rule description for rule %s.", ruleNumber)).queue(); + eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { + try { + Rule ruleToUpdate = ruleService.findByNumber(ruleNumber); + ruleToUpdate.setDescription(descriptionReceiver.getMessage().getContentRaw()); + Rule rule = ruleService.save(ruleToUpdate); + descriptionReceiver.getChannel().sendMessage(rule + " edited").queue(); + event.getChannel().sendMessage(String.format("Rule #%s has been edited by %s", ruleNumber, JdaUtil.getUser(event))).queue(); + } catch (EntityNotFoundException exc) { + ruleNumberReciever.getChannel().sendMessage(exc.getMessage()).queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } catch (NumberFormatException exc) { + ruleNumberReciever.getChannel().sendMessage("No valid rule number.").queue(); + } + }, privateMessageReceivedEvent, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/BB8Listener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/BB8Listener.java @@ -0,0 +1,23 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.util.Constants.Emoji; +import net.dv8tion.jda.api.entities.MessageChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.io.InputStream; + +@Component +public class BB8Listener implements Listener { + + private static final String BB8_IMAGE = "/images/bb8.jpg"; + + @Override + public void proces(MessageReceivedEvent event) { + MessageChannel channel = event.getChannel(); + InputStream in = getClass().getResourceAsStream(BB8_IMAGE); + channel.sendMessage("BEEP BOOP! " + Emoji.THUMBS_UP + " " + Emoji.FLAMES) + .addFile(in, "bb8.jpg").queue(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/CombatStatsListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/CombatStatsListener.java @@ -0,0 +1,44 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.model.CombatDto; +import com.wimdupont.sxcybot.model.OsrsStat; +import com.wimdupont.sxcybot.services.osrs.CombatCalculatorService; +import com.wimdupont.sxcybot.services.osrs.StatMessageSender; +import com.wimdupont.sxcybot.enums.OsrsCombatStat; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class CombatStatsListener implements Listener { + + private final StatMessageSender statMessageSender; + private final CombatCalculatorService combatCalculatorService; + + private static final List<String> COMBAT_STAT_LIST = List.of(OsrsCombatStat.ATTACK.value, OsrsCombatStat.STRENGTH.value, OsrsCombatStat.DEFENCE.value, OsrsCombatStat.HITPOINTS.value, OsrsCombatStat.RANGED.value, OsrsCombatStat.PRAYER.value, OsrsCombatStat.MAGIC.value); + + public CombatStatsListener(StatMessageSender statMessageSender, + CombatCalculatorService combatCalculatorService) { + this.statMessageSender = statMessageSender; + this.combatCalculatorService = combatCalculatorService; + } + + @Override + public void proces(MessageReceivedEvent event) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + event.getChannel().sendTyping().queue(e -> + statMessageSender.sendStatMessage(event, embedBuilder, this::isCombatStat, + f -> embedBuilder.addField(f.name(), "Level " + f.level(), true) + , osrsStatList -> embedBuilder.addField("COMBAT", String.valueOf(combatCalculatorService.getCombatLevel(CombatDto.build(osrsStatList))), false) + ) + ); + } + + private boolean isCombatStat(OsrsStat osrsStat) { + return COMBAT_STAT_LIST.contains(osrsStat.name()); + } + +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/CustomPollListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/CustomPollListener.java @@ -0,0 +1,51 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.util.CustomPollFiller; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.LinkedHashSet; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class CustomPollListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomPollListener.class); + private final CustomPollFiller customPollFiller; + + public CustomPollListener(CustomPollFiller customPollFiller) { + this.customPollFiller = customPollFiller; + } + + @Override + public void proces(MessageReceivedEvent event) { + String msg = event.getMessage().getContentRaw(); + try { + String title = msg.substring(msg.indexOf(" ")); + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle(title); + embedBuilder.setFooter("Let the polling begin!", event.getGuild().getIconUrl()); + + customPollFiller.fillPoll(privateChannel, event, embedBuilder, new LinkedHashSet<>()); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } catch (StringIndexOutOfBoundsException e) { + event.getChannel().sendMessage("Please enter a descriptive title for the poll after the command, separated by space.").queue(); + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/EventListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/EventListener.java @@ -0,0 +1,58 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.repository.guild.dao.Event; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class EventListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(EventListener.class); + private final EventWaiterUtil eventWaiterUtil; + + public EventListener(EventWaiterUtil eventWaiterUtil) { + this.eventWaiterUtil = eventWaiterUtil; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (!event.getAuthor().isBot() && event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + privateChannel.sendMessage("Name of the event?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(nameReceiver -> { + privateChannel.sendMessage("Description?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(descriptionReceiver -> { + privateChannel.sendMessage("TimeZone, UTC or PT?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(timeZoneReceiver -> { + privateChannel.sendMessage("Date?").queue(); + eventWaiterUtil.waitForPrivateChannelEvent(dateReceiver -> + finishEventCreation(nameReceiver, descriptionReceiver, timeZoneReceiver, dateReceiver, event), event, privateChannel); + }, event, privateChannel); + }, event, privateChannel); + }, event, privateChannel); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } + + private void finishEventCreation(PrivateMessageReceivedEvent nameReceiver, + PrivateMessageReceivedEvent descriptionReceiver, + PrivateMessageReceivedEvent timeZoneReceiver, + PrivateMessageReceivedEvent dateReceiver, + MessageReceivedEvent event) { + Event createdEvent = Event.Builder.newBuilder() + .name(nameReceiver.getMessage().getContentRaw()) + .description(descriptionReceiver.getMessage().getContentRaw()) + .build(); + event.getChannel().sendMessage("Event created :" + createdEvent).queue(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/ForumListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/ForumListener.java @@ -0,0 +1,31 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.services.guild.ChannelDetailService; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.MessageChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class ForumListener implements Listener { + + private final ChannelDetailService channelDetailService; + + public ForumListener(ChannelDetailService channelDetailService) { + this.channelDetailService = channelDetailService; + } + + @Override + public void proces(MessageReceivedEvent event) { + channelDetailService.findAll().stream().findAny().ifPresent(channelDetail -> { + MessageChannel channel = event.getChannel(); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.RED); + embedBuilder.setTitle("Link to the forum post", channelDetail.getForumUrl()); + channel.sendMessageEmbeds(embedBuilder.build()).queue(); + }); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/HelpListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/HelpListener.java @@ -0,0 +1,35 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.enums.Command; +import com.wimdupont.sxcybot.enums.Command.Admin; +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.util.Constants.Commands; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class HelpListener implements Listener { + + @Override + public void proces(MessageReceivedEvent event) { + event.getChannel().sendTyping().queue(); + EmbedBuilder embedBuilder = new EmbedBuilder(); + + embedBuilder.setColor(Color.red); + embedBuilder.setTitle("List of Commands"); + for (Command command : Command.values()) { + embedBuilder.addField(Commands.COMMAND_PREFIX + command.name().toLowerCase(), command.description, false); + } + EmbedBuilder adminEmbedBuilder = new EmbedBuilder(); + adminEmbedBuilder.setColor(Color.red); + adminEmbedBuilder.setTitle("List of Admin Commands"); + for (Admin admin : Admin.values()) { + adminEmbedBuilder.addField(Commands.COMMAND_PREFIX + admin.name().toLowerCase(), admin.description, false); + } + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + event.getChannel().sendMessageEmbeds(adminEmbedBuilder.build()).queue(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/HiscoreBossListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/HiscoreBossListener.java @@ -0,0 +1,50 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.enums.PvmRole; +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; +import com.wimdupont.sxcybot.services.osrs.OsrsHiscoreBossService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.List; + +@Component +public class HiscoreBossListener implements Listener { + + private final OsrsHiscoreBossService osrsHiscoreBossService; + + public HiscoreBossListener(OsrsHiscoreBossService osrsHiscoreBossService) { + this.osrsHiscoreBossService = osrsHiscoreBossService; + } + + @Override + public void proces(MessageReceivedEvent event) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + List<OsrsHiscoreBoss> hiscoreBossList = osrsHiscoreBossService.findAll(); + for (PvmRole pvmRole : PvmRole.values()) { + int i = 1; + embedBuilder.setTitle(String.format("List of %s bosses:", pvmRole)); + for (OsrsHiscoreBoss osrsHiscoreBoss : hiscoreBossList) { + if (pvmRole.value == osrsHiscoreBoss.getPvmRole()) { + embedBuilder.addField(osrsHiscoreBoss.getName(), + String.format("Multiplier: %s", + osrsHiscoreBoss.getMultiplier()), + true); + if (JdaUtil.requiresBuild(embedBuilder, hiscoreBossList.size(), i)) { + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + } + } + i++; + } + if (embedBuilder.getFields().size() > 0) + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/KillCountListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/KillCountListener.java @@ -0,0 +1,53 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.client.HiScoreClient; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.model.OsrsBossKc; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.List; + +@Component +public class KillCountListener implements Listener { + + private final HiScoreClient hiScoreClient; + + public KillCountListener(HiScoreClient hiScoreClient) { + this.hiScoreClient = hiScoreClient; + } + + @Override + public void proces(MessageReceivedEvent event) { + String msg = event.getMessage().getContentRaw(); + try { + String player = msg.substring(msg.indexOf(" ")).trim(); + List<OsrsBossKc> bossKcList = hiScoreClient.getHiScoreBossKc(player, event.getChannel()).orElseThrow(() + -> new EntityNotFoundException(String.format("No HiScores found for %s.", player))); + + event.getChannel().sendTyping().queue(q -> { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setTitle(String.format("Killcount for %s", player)); + embedBuilder.setColor(Color.RED); + int i = 1; + bossKcList.stream().filter(f -> !"-1".equals(f.kc())).forEach(f -> { + embedBuilder.addField(f.name(), String.format("Kc: %s%sRank: %s", f.kc(), System.lineSeparator(), f.rank()), true); + if (JdaUtil.requiresBuild(embedBuilder, bossKcList.size(), i)) { + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clearFields(); + } + }); + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + }); + + } catch (StringIndexOutOfBoundsException e) { + event.getChannel().sendMessage("Please enter a player name after the command, separated by space.").queue(); + } catch (EntityNotFoundException e) { + event.getChannel().sendMessage(e.getMessage()).queue(); + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/PingListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/PingListener.java @@ -0,0 +1,19 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import net.dv8tion.jda.api.entities.MessageChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +@Component +public class PingListener implements Listener { + + @Override + public void proces(MessageReceivedEvent event) { + MessageChannel channel; + channel = event.getChannel(); + long time = System.currentTimeMillis(); + channel.sendMessage("Pong") + .queue(response -> response.editMessageFormat("Pong: %d ms", System.currentTimeMillis() - time).queue()); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/PollListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/PollListener.java @@ -0,0 +1,66 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.repository.guild.dao.Poll; +import com.wimdupont.sxcybot.services.guild.PollService; +import com.wimdupont.sxcybot.util.Constants.Reaction; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class PollListener implements Listener { + + private final PollService pollService; + + public PollListener(PollService pollService) { + this.pollService = pollService; + } + + @Override + public void proces(MessageReceivedEvent event) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + String msg = event.getMessage().getContentRaw(); + try { + String title = msg.substring(msg.indexOf(" ")); + + embedBuilder.setColor(Color.red); + embedBuilder.setTitle(title); + embedBuilder.addField("✅ Accept (0)", "", true); + embedBuilder.addField("❎ Deny (0)", "", true); + embedBuilder.addField("❓ Unsure (0)", "", true); + embedBuilder.setFooter("Let the polling begin!", event.getGuild().getIconUrl()); + + event.getChannel().sendTyping().queue(typing -> + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(message -> { + message.addReaction(Reaction.CHECK_MARK_BUTTON) + .and(message.addReaction(Reaction.CROSS_MARK_BUTTON)) + .and(message.addReaction(Reaction.QUESTION_MARK)) + .queue(); + pollService.save(Poll.Builder.newBuilder().messageId(message.getId()).build()); + })); + } catch (StringIndexOutOfBoundsException e) { + event.getChannel().sendMessage("Please enter a descriptive title for the poll after the command, separated by space.").queue(); + } + } + +// private Poll createPoll(String messageId) { +// List<PollReaction> pollReactionList = newArrayList(); +// Poll poll = Poll.builder() +// .pollReactions(newArrayList(pollReactionList)) +// .messageId(messageId) +// .build(); +// PollReaction pollReaction = PollReaction.builder() +// .reactionId("reactionId") +// .poll(poll) +// .build(); +// pollReactionList.add(pollReaction); +// poll.setPollReactions(pollReactionList); +// +// return poll; +// +// } +} + diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/PriceListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/PriceListener.java @@ -0,0 +1,43 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.client.GrandExchangeClient; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.Listener; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class PriceListener implements Listener { + + private final GrandExchangeClient grandExchangeClient; + + public PriceListener(GrandExchangeClient grandExchangeClient) { + this.grandExchangeClient = grandExchangeClient; + } + + @Override + public void proces(MessageReceivedEvent event) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + String msg = event.getMessage().getContentRaw(); + try { + String itemName = msg.substring(msg.indexOf(" ")).trim(); + event.getChannel().sendTyping().queue(typing -> { + try { + String result = grandExchangeClient.getPrice(itemName, event.getChannel()); + embedBuilder.setTitle("Price of item"); + embedBuilder.setColor(Color.RED); + embedBuilder.addField(itemName, result, false); + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + } catch (EntityNotFoundException e) { + event.getChannel().sendMessage(e.getMessage()).queue(); + } + }); + } catch (StringIndexOutOfBoundsException e) { + event.getChannel().sendMessage("Please enter an item name after the command, separated by space.").queue(); + } + + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmListListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmListListener.java @@ -0,0 +1,41 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.List; + +@Component +public class PvmListListener implements Listener { + + private final PvmRoleUserService pvmRoleUserService; + + public PvmListListener(PvmRoleUserService pvmRoleUserService) { + this.pvmRoleUserService = pvmRoleUserService; + } + + @Override + public void proces(MessageReceivedEvent event) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle("List of PvM Role competitors:"); + List<PvmRoleUser> pvmRoleUsers = pvmRoleUserService.findAll(); + int i = 1; + for (PvmRoleUser pvmRoleUser : pvmRoleUsers) { + embedBuilder.addField(pvmRoleUser.getDiscordName(), + String.format("RSN: %s", pvmRoleUser.getRsn()), + false); + if (JdaUtil.requiresBuild(embedBuilder, pvmRoleUsers.size(), i)) { + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clear(); + } + i++; + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmRoleCheckListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmRoleCheckListener.java @@ -0,0 +1,33 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.services.OsrsMonitoringService; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class PvmRoleCheckListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(PvmRoleCheckListener.class); + private final OsrsMonitoringService osrsMonitoringService; + + public PvmRoleCheckListener(OsrsMonitoringService osrsMonitoringService) { + this.osrsMonitoringService = osrsMonitoringService; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + osrsMonitoringService.monitorPvmRoleUserHiscores(privateChannel); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmRolePollListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/PvmRolePollListener.java @@ -0,0 +1,33 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.services.PvMRoleResolver; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.exceptions.RateLimitedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class PvmRolePollListener implements Listener { + + private static final Logger LOGGER = LoggerFactory.getLogger(PvmRolePollListener.class); + private final PvMRoleResolver pvMRoleResolver; + + public PvmRolePollListener(PvMRoleResolver pvMRoleResolver) { + this.pvMRoleResolver = pvMRoleResolver; + } + + @Override + public void proces(MessageReceivedEvent event) { + if (event.getMember() != null) { + try { + PrivateChannel privateChannel = event.getMember().getUser().openPrivateChannel().complete(true); + pvMRoleResolver.resolvePvMRoles(false, privateChannel); + } catch (RateLimitedException e) { + LOGGER.error(e.getMessage(), e); + } + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/RuleListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/RuleListener.java @@ -0,0 +1,45 @@ +package com.wimdupont.sxcybot.listeners.member; + + +import com.wimdupont.sxcybot.enums.Command; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.services.guild.RuleService; +import com.wimdupont.sxcybot.util.Constants.Commands; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.MessageChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; + + +@Component +public class RuleListener implements Listener { + + private final RuleService ruleService; + + public RuleListener(RuleService ruleService) { + this.ruleService = ruleService; + } + + @Override + public void proces(MessageReceivedEvent event) { + MessageChannel channel = event.getChannel(); + int ruleNumber; + String description; + try { + ruleNumber = Integer.parseInt(event.getMessage().getContentRaw().substring(Commands.COMMAND_PREFIX.length() + Command.RULE.name().length() + 1)); + description = ruleService.findByNumber(ruleNumber).getDescription(); + } catch (NumberFormatException | EntityNotFoundException e) { + channel.sendMessage(e.getMessage()).queue(); + return; + } + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.RED); + embedBuilder.setTitle("Show rule result"); + embedBuilder.addField(String.format("Rule #%s", ruleNumber), description, false); + channel.sendMessageEmbeds(embedBuilder.build()).queue(); + } + +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/RulesListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/RulesListener.java @@ -0,0 +1,41 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.repository.guild.dao.Rule; +import com.wimdupont.sxcybot.services.guild.RuleService; +import com.wimdupont.sxcybot.util.JdaUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.Comparator; +import java.util.List; + +@Component +public class RulesListener implements Listener { + + private final RuleService ruleService; + + public RulesListener(RuleService ruleService) { + this.ruleService = ruleService; + } + + @Override + public void proces(MessageReceivedEvent event) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle(String.format("List of %s rules:", event.getGuild().getName())); + List<Rule> ruleList = ruleService.findAll(); + ruleList.sort(Comparator.comparing(Rule::getNumber)); + int i = 1; + for (Rule rule : ruleList) { + embedBuilder.addField(String.format("Rule #%s", rule.getNumber()), rule.getDescription(), false); + if (JdaUtil.requiresBuild(embedBuilder, ruleList.size(), i)) { + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + embedBuilder.clear(); + } + i++; + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/listeners/member/StatsListener.java b/src/main/java/com/wimdupont/sxcybot/listeners/member/StatsListener.java @@ -0,0 +1,31 @@ +package com.wimdupont.sxcybot.listeners.member; + +import com.wimdupont.sxcybot.listeners.Listener; +import com.wimdupont.sxcybot.services.osrs.StatMessageSender; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.util.Objects; + +@Component +public class StatsListener implements Listener { + + private final StatMessageSender statMessageSender; + + public StatsListener(StatMessageSender statMessageSender) { + this.statMessageSender = statMessageSender; + } + + @Override + public void proces(MessageReceivedEvent event) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + event.getChannel().sendTyping().queue(e -> + statMessageSender.sendStatMessage(event, embedBuilder, Objects::nonNull, + f -> embedBuilder.addField(f.name(), + "Level " + f.level() + System.lineSeparator() + + "Rank " + f.rank() + System.lineSeparator() + + "Exp " + f.experience(), true), null + )); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/model/CombatDto.java b/src/main/java/com/wimdupont/sxcybot/model/CombatDto.java @@ -0,0 +1,124 @@ +package com.wimdupont.sxcybot.model; + +import com.wimdupont.sxcybot.enums.OsrsCombatStat; + +import java.util.List; + +public record CombatDto( + int attackLevel, + int strengthLevel, + int defenceLevel, + int hitpointsLevel, + int magicLevel, + int rangeLevel, + int prayerLevel +) { + + + private CombatDto(Builder builder) { + this(builder.attackLevel, + builder.strengthLevel, + builder.defenceLevel, + builder.hitpointsLevel, + builder.magicLevel, + builder.rangeLevel, + builder.prayerLevel); + } + + public static CombatDto build(List<OsrsStat> osrsStatList) { + CombatDto.Builder builder = CombatDto.Builder.newBuilder(); + for (OsrsStat osrsStat : osrsStatList) { + if (OsrsCombatStat.ATTACK.value.equalsIgnoreCase(osrsStat.name())) { + builder.attackLevel(Integer.parseInt(osrsStat.level())); + } + if (OsrsCombatStat.STRENGTH.value.equalsIgnoreCase(osrsStat.name())) { + builder.strengthLevel(Integer.parseInt(osrsStat.level())); + } + if (OsrsCombatStat.DEFENCE.value.equalsIgnoreCase(osrsStat.name())) { + builder.defenceLevel(Integer.parseInt(osrsStat.level())); + } + if (OsrsCombatStat.HITPOINTS.value.equalsIgnoreCase(osrsStat.name())) { + builder.hitpointsLevel(Integer.parseInt(osrsStat.level())); + } + if (OsrsCombatStat.MAGIC.value.equalsIgnoreCase(osrsStat.name())) { + builder.magicLevel(Integer.parseInt(osrsStat.level())); + } + if (OsrsCombatStat.RANGED.value.equalsIgnoreCase(osrsStat.name())) { + builder.rangeLevel(Integer.parseInt(osrsStat.level())); + } + if (OsrsCombatStat.PRAYER.value.equalsIgnoreCase(osrsStat.name())) { + builder.prayerLevel(Integer.parseInt(osrsStat.level())); + } + } + return builder.build(); + } + + public static final class Builder { + private int attackLevel; + private int strengthLevel; + private int defenceLevel; + private int hitpointsLevel; + private int magicLevel; + private int rangeLevel; + private int prayerLevel; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder attackLevel(int val) { + attackLevel = val; + return this; + } + + public Builder strengthLevel(int val) { + strengthLevel = val; + return this; + } + + public Builder defenceLevel(int val) { + defenceLevel = val; + return this; + } + + public Builder hitpointsLevel(int val) { + hitpointsLevel = val; + return this; + } + + public Builder magicLevel(int val) { + magicLevel = val; + return this; + } + + public Builder rangeLevel(int val) { + rangeLevel = val; + return this; + } + + public Builder prayerLevel(int val) { + prayerLevel = val; + return this; + } + + public CombatDto build() { + return new CombatDto(this); + } + } + + @Override + public String toString() { + return "CombatDto{" + + "attackLevel=" + attackLevel + + ", strengthLevel=" + strengthLevel + + ", defenceLevel=" + defenceLevel + + ", hitpointsLevel=" + hitpointsLevel + + ", magicLevel=" + magicLevel + + ", rangeLevel=" + rangeLevel + + ", prayerLevel=" + prayerLevel + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/model/EditListenerDto.java b/src/main/java/com/wimdupont/sxcybot/model/EditListenerDto.java @@ -0,0 +1,93 @@ +package com.wimdupont.sxcybot.model; + +import com.wimdupont.sxcybot.listeners.PrivateListener; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.jetbrains.annotations.NotNull; + +public record EditListenerDto( + @NotNull + PrivateListener addListener, + PrivateListener updateListener, + @NotNull + PrivateListener deleteListener, + @NotNull + MessageReceivedEvent event, + @NotNull + PrivateChannel privateChannel, + @NotNull + String entityName +) { + + + private EditListenerDto(Builder builder) { + this(builder.addListener, + builder.updateListener, + builder.deleteListener, + builder.event, + builder.privateChannel, + builder.entityName); + } + + public static final class Builder { + private @NotNull PrivateListener addListener; + private PrivateListener updateListener; + private @NotNull PrivateListener deleteListener; + private @NotNull MessageReceivedEvent event; + private @NotNull PrivateChannel privateChannel; + private @NotNull String entityName; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder addListener(@NotNull PrivateListener val) { + addListener = val; + return this; + } + + public Builder updateListener(PrivateListener val) { + updateListener = val; + return this; + } + + public Builder deleteListener(@NotNull PrivateListener val) { + deleteListener = val; + return this; + } + + public Builder event(@NotNull MessageReceivedEvent val) { + event = val; + return this; + } + + public Builder privateChannel(@NotNull PrivateChannel val) { + privateChannel = val; + return this; + } + + public Builder entityName(@NotNull String val) { + entityName = val; + return this; + } + + public EditListenerDto build() { + return new EditListenerDto(this); + } + } + + @Override + public String toString() { + return "EditListenerDto{" + + "addListener=" + addListener + + ", updateListener=" + updateListener + + ", deleteListener=" + deleteListener + + ", event=" + event + + ", privateChannel=" + privateChannel + + ", entityName='" + entityName + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/model/HiScoreBuilder.java b/src/main/java/com/wimdupont/sxcybot/model/HiScoreBuilder.java @@ -0,0 +1,11 @@ +package com.wimdupont.sxcybot.model; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; + +import java.util.List; + +@FunctionalInterface +public interface HiScoreBuilder<T> { + + T accept(String string, List<String> stringList, int i) throws EntityNotFoundException; +} diff --git a/src/main/java/com/wimdupont/sxcybot/model/OsrsBossKc.java b/src/main/java/com/wimdupont/sxcybot/model/OsrsBossKc.java @@ -0,0 +1,56 @@ +package com.wimdupont.sxcybot.model; + +public record OsrsBossKc( + String name, + String rank, + String kc + +) { + + private OsrsBossKc(Builder builder) { + this(builder.name, + builder.rank, + builder.kc); + } + + public static final class Builder { + private String name; + private String rank; + private String kc; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder name(String val) { + name = val; + return this; + } + + public Builder rank(String val) { + rank = val; + return this; + } + + public Builder kc(String val) { + kc = val; + return this; + } + + public OsrsBossKc build() { + return new OsrsBossKc(this); + } + } + + @Override + public String toString() { + return "OsrsBossKc{" + + "name='" + name + '\'' + + ", rank='" + rank + '\'' + + ", kc='" + kc + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/model/OsrsItem.java b/src/main/java/com/wimdupont/sxcybot/model/OsrsItem.java @@ -0,0 +1,64 @@ +package com.wimdupont.sxcybot.model; + +public record OsrsItem( + String id, + String timestamp, + Integer price, + String volume +) { + + private OsrsItem(Builder builder) { + this(builder.id, + builder.timestamp, + builder.price, + builder.volume); + } + + public static final class Builder { + private String id; + private String timestamp; + private Integer price; + private String volume; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder timestamp(String val) { + timestamp = val; + return this; + } + + public Builder price(Integer val) { + price = val; + return this; + } + + public Builder volume(String val) { + volume = val; + return this; + } + + public OsrsItem build() { + return new OsrsItem(this); + } + } + + @Override + public String toString() { + return "OsrsItem{" + + "id='" + id + '\'' + + ", timestamp='" + timestamp + '\'' + + ", price=" + price + + ", volume='" + volume + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/model/OsrsStat.java b/src/main/java/com/wimdupont/sxcybot/model/OsrsStat.java @@ -0,0 +1,65 @@ +package com.wimdupont.sxcybot.model; + +public record OsrsStat( + String name, + String experience, + String rank, + String level +) { + + + private OsrsStat(Builder builder) { + this(builder.name, + builder.experience, + builder.rank, + builder.level); + } + + public static final class Builder { + private String name; + private String experience; + private String rank; + private String level; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder name(String val) { + name = val; + return this; + } + + public Builder experience(String val) { + experience = val; + return this; + } + + public Builder rank(String val) { + rank = val; + return this; + } + + public Builder level(String val) { + level = val; + return this; + } + + public OsrsStat build() { + return new OsrsStat(this); + } + } + + @Override + public String toString() { + return "OsrsStat{" + + "name='" + name + '\'' + + ", experience='" + experience + '\'' + + ", rank='" + rank + '\'' + + ", level='" + level + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/ChannelDetailRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/ChannelDetailRepository.java @@ -0,0 +1,9 @@ +package com.wimdupont.sxcybot.repository.guild; + +import com.wimdupont.sxcybot.repository.guild.dao.ChannelDetail; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ChannelDetailRepository extends JpaRepository<ChannelDetail, String> { +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/GuildEventDmerRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/GuildEventDmerRepository.java @@ -0,0 +1,9 @@ +package com.wimdupont.sxcybot.repository.guild; + +import com.wimdupont.sxcybot.repository.guild.dao.GuildEventDmer; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface GuildEventDmerRepository extends JpaRepository<GuildEventDmer, String> { +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/GuildRoleRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/GuildRoleRepository.java @@ -0,0 +1,18 @@ +package com.wimdupont.sxcybot.repository.guild; + +import com.wimdupont.sxcybot.repository.guild.dao.GuildRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface GuildRoleRepository extends JpaRepository<GuildRole, String> { + + List<GuildRole> findByElevationLessThanEqual(Integer elevation); + + List<GuildRole> findByElevationGreaterThanEqual(Integer elevation); + + Optional<GuildRole> findByName(String name); +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/PollRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/PollRepository.java @@ -0,0 +1,13 @@ +package com.wimdupont.sxcybot.repository.guild; + +import com.wimdupont.sxcybot.repository.guild.dao.Poll; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface PollRepository extends JpaRepository<Poll, String> { + + Optional<Poll> findByMessageId(String messageId); +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/RuleRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/RuleRepository.java @@ -0,0 +1,14 @@ +package com.wimdupont.sxcybot.repository.guild; + +import com.wimdupont.sxcybot.repository.guild.dao.Rule; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface RuleRepository extends JpaRepository<Rule, String> { + + Optional<Rule> findByNumber(int number); + +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/UserRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/UserRepository.java @@ -0,0 +1,16 @@ +package com.wimdupont.sxcybot.repository.guild; + +import com.wimdupont.sxcybot.repository.guild.dao.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface UserRepository extends JpaRepository<User, String> { + + Optional<User> findByName(String name); + + List<User> findAllByBannedTrue(); +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/ChannelDetail.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/ChannelDetail.java @@ -0,0 +1,158 @@ +package com.wimdupont.sxcybot.repository.guild.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class ChannelDetail { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + private String forumUrl; + private String botUpdateChannel; + private String pvmRoleChannel; + private String pvmRoleGeneral; + private String pvmRoleRaids; + private String pvmRoleWilderness; + + protected ChannelDetail() { + } + + private ChannelDetail(Builder builder) { + setId(builder.id); + setForumUrl(builder.forumUrl); + setBotUpdateChannel(builder.botUpdateChannel); + setPvmRoleChannel(builder.pvmRoleChannel); + setPvmRoleGeneral(builder.pvmRoleGeneral); + setPvmRoleRaids(builder.pvmRoleRaids); + setPvmRoleWilderness(builder.pvmRoleWilderness); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getForumUrl() { + return forumUrl; + } + + public void setForumUrl(String forumUrl) { + this.forumUrl = forumUrl; + } + + public String getBotUpdateChannel() { + return botUpdateChannel; + } + + public void setBotUpdateChannel(String botUpdateChannel) { + this.botUpdateChannel = botUpdateChannel; + } + + public String getPvmRoleChannel() { + return pvmRoleChannel; + } + + public void setPvmRoleChannel(String pvmRoleChannel) { + this.pvmRoleChannel = pvmRoleChannel; + } + + public String getPvmRoleGeneral() { + return pvmRoleGeneral; + } + + public void setPvmRoleGeneral(String pvmRoleGeneral) { + this.pvmRoleGeneral = pvmRoleGeneral; + } + + public String getPvmRoleRaids() { + return pvmRoleRaids; + } + + public void setPvmRoleRaids(String pvmRoleRaids) { + this.pvmRoleRaids = pvmRoleRaids; + } + + public String getPvmRoleWilderness() { + return pvmRoleWilderness; + } + + public void setPvmRoleWilderness(String pvmRoleWilderness) { + this.pvmRoleWilderness = pvmRoleWilderness; + } + + public static final class Builder { + private String id; + private String forumUrl; + private String botUpdateChannel; + private String pvmRoleChannel; + private String pvmRoleGeneral; + private String pvmRoleRaids; + private String pvmRoleWilderness; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder forumUrl(String val) { + forumUrl = val; + return this; + } + + public Builder botUpdateChannel(String val) { + botUpdateChannel = val; + return this; + } + + public Builder pvmRoleChannel(String val) { + pvmRoleChannel = val; + return this; + } + + public Builder pvmRoleGeneral(String val) { + pvmRoleGeneral = val; + return this; + } + + public Builder pvmRoleRaids(String val) { + pvmRoleRaids = val; + return this; + } + + public Builder pvmRoleWilderness(String val) { + pvmRoleWilderness = val; + return this; + } + + public ChannelDetail build() { + return new ChannelDetail(this); + } + } + + @Override + public String toString() { + return "ChannelDetail{" + + "id='" + id + '\'' + + ", forumUrl='" + forumUrl + '\'' + + ", botUpdateChannel='" + botUpdateChannel + '\'' + + ", pvmRoleChannel='" + pvmRoleChannel + '\'' + + ", pvmRoleGeneral='" + pvmRoleGeneral + '\'' + + ", pvmRoleRaids='" + pvmRoleRaids + '\'' + + ", pvmRoleWilderness='" + pvmRoleWilderness + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/Event.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/Event.java @@ -0,0 +1,85 @@ +package com.wimdupont.sxcybot.repository.guild.dao; + +import java.time.LocalDate; + +public class Event { + + private String name; + private String description; + private LocalDate time; + + protected Event() { + + } + + private Event(Builder builder) { + setName(builder.name); + setDescription(builder.description); + setTime(builder.time); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LocalDate getTime() { + return time; + } + + public void setTime(LocalDate time) { + this.time = time; + } + + public static final class Builder { + private String name; + private String description; + private LocalDate time; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder name(String val) { + name = val; + return this; + } + + public Builder description(String val) { + description = val; + return this; + } + + public Builder time(LocalDate val) { + time = val; + return this; + } + + public Event build() { + return new Event(this); + } + } + + @Override + public String toString() { + return "Event{" + + "name='" + name + '\'' + + ", description='" + description + '\'' + + ", time=" + time + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/GuildEventDmer.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/GuildEventDmer.java @@ -0,0 +1,75 @@ +package com.wimdupont.sxcybot.repository.guild.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; + + +@Entity +public class GuildEventDmer { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + + private String name; + + private GuildEventDmer(Builder builder) { + setId(builder.id); + setName(builder.name); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + protected GuildEventDmer() { + } + + public static final class Builder { + private String id; + private String name; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder name(String val) { + name = val; + return this; + } + + public GuildEventDmer build() { + return new GuildEventDmer(this); + } + } + + @Override + public String toString() { + return "GuildEventDmer{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/GuildRole.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/GuildRole.java @@ -0,0 +1,109 @@ +package com.wimdupont.sxcybot.repository.guild.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; + + +@Entity +public class GuildRole { + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + private String name; + private Integer orderValue; + private int elevation; + + protected GuildRole() { + } + + private GuildRole(Builder builder) { + setId(builder.id); + setName(builder.name); + setOrderValue(builder.orderValue); + setElevation(builder.elevation); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getOrderValue() { + return orderValue; + } + + public void setOrderValue(Integer orderValue) { + this.orderValue = orderValue; + } + + public int getElevation() { + return elevation; + } + + public void setElevation(int elevation) { + this.elevation = elevation; + } + + public static final class Builder { + private String id; + private String name; + private Integer orderValue; + private int elevation; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder name(String val) { + name = val; + return this; + } + + public Builder orderValue(Integer val) { + orderValue = val; + return this; + } + + public Builder elevation(int val) { + elevation = val; + return this; + } + + public GuildRole build() { + return new GuildRole(this); + } + } + + @Override + public String toString() { + return "GuildRole{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + ", orderValue=" + orderValue + + ", elevation=" + elevation + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/Poll.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/Poll.java @@ -0,0 +1,118 @@ +package com.wimdupont.sxcybot.repository.guild.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Entity +@EntityListeners(AuditingEntityListener.class) +public class Poll { + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + + private String messageId; + @CreatedDate + private LocalDateTime createdDate; + @LastModifiedDate + private LocalDateTime lastModifiedDate; + + protected Poll() { + } + + private Poll(Builder builder) { + setId(builder.id); + setMessageId(builder.messageId); + setCreatedDate(builder.createdDate); + setLastModifiedDate(builder.lastModifiedDate); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public LocalDateTime getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(LocalDateTime createdDate) { + this.createdDate = createdDate; + } + + public LocalDateTime getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(LocalDateTime lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + public static final class Builder { + private String id; + private String messageId; + private LocalDateTime createdDate; + private LocalDateTime lastModifiedDate; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder messageId(String val) { + messageId = val; + return this; + } + + public Builder createdDate(LocalDateTime val) { + createdDate = val; + return this; + } + + public Builder lastModifiedDate(LocalDateTime val) { + lastModifiedDate = val; + return this; + } + + public Poll build() { + return new Poll(this); + } + } + + @Override + public String toString() { + return "Poll{" + + "id='" + id + '\'' + + ", messageId='" + messageId + '\'' + + ", createdDate=" + createdDate + + ", lastModifiedDate=" + lastModifiedDate + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/Rule.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/Rule.java @@ -0,0 +1,93 @@ +package com.wimdupont.sxcybot.repository.guild.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Rule { + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + + private int number; + + private String description; + + protected Rule() { + } + + private Rule(Builder builder) { + setId(builder.id); + setNumber(builder.number); + setDescription(builder.description); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getNumber() { + return number; + } + + public void setNumber(int number) { + this.number = number; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public static final class Builder { + private String id; + private int number; + private String description; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder number(int val) { + number = val; + return this; + } + + public Builder description(String val) { + description = val; + return this; + } + + public Rule build() { + return new Rule(this); + } + } + + @Override + public String toString() { + return "Rule{" + + "id='" + id + '\'' + + ", number=" + number + + ", description='" + description + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/User.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/dao/User.java @@ -0,0 +1,185 @@ +package com.wimdupont.sxcybot.repository.guild.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDate; + +@Entity +@EntityListeners(AuditingEntityListener.class) +public class User { + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + private String name; + private String description; + private boolean banned; + @CreatedDate + private LocalDate createdDate; + private String createdBy; + @LastModifiedDate + private LocalDate lastModifiedDate; + private String lastModifiedBy; + + protected User() { + } + + private User(Builder builder) { + setId(builder.id); + setName(builder.name); + setDescription(builder.description); + setBanned(builder.banned); + setCreatedDate(builder.createdDate); + setCreatedBy(builder.createdBy); + setLastModifiedDate(builder.lastModifiedDate); + setLastModifiedBy(builder.lastModifiedBy); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isBanned() { + return banned; + } + + public void setBanned(boolean banned) { + this.banned = banned; + } + + public LocalDate getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(LocalDate createdDate) { + this.createdDate = createdDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public LocalDate getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(LocalDate lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public static final class Builder { + private String id; + private String name; + private String description; + private boolean banned; + private LocalDate createdDate; + private String createdBy; + private LocalDate lastModifiedDate; + private String lastModifiedBy; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder name(String val) { + name = val; + return this; + } + + public Builder description(String val) { + description = val; + return this; + } + + public Builder banned(boolean val) { + banned = val; + return this; + } + + public Builder createdDate(LocalDate val) { + createdDate = val; + return this; + } + + public Builder createdBy(String val) { + createdBy = val; + return this; + } + + public Builder lastModifiedDate(LocalDate val) { + lastModifiedDate = val; + return this; + } + + public Builder lastModifiedBy(String val) { + lastModifiedBy = val; + return this; + } + + public User build() { + return new User(this); + } + } + + @Override + public String toString() { + return "User{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + ", description='" + description + '\'' + + ", banned=" + banned + + ", createdDate=" + createdDate + + ", createdBy='" + createdBy + '\'' + + ", lastModifiedDate=" + lastModifiedDate + + ", lastModifiedBy='" + lastModifiedBy + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmKcSnapshotRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmKcSnapshotRepository.java @@ -0,0 +1,14 @@ +package com.wimdupont.sxcybot.repository.guild.pvmrole; + +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface PvmKcSnapshotRepository extends JpaRepository<PvmKcSnapshot, String> { + + List<PvmKcSnapshot> findAllByPvmRoleUserId(String PvmRoleUserId); + +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/PvmRoleUserRepository.java @@ -0,0 +1,14 @@ +package com.wimdupont.sxcybot.repository.guild.pvmrole; + +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface PvmRoleUserRepository extends JpaRepository<PvmRoleUser, String> { + + Optional<PvmRoleUser> findByDiscordName(String discordName); + Optional<PvmRoleUser> findByDiscordId(String discordId); +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmKcSnapshot.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmKcSnapshot.java @@ -0,0 +1,148 @@ +package com.wimdupont.sxcybot.repository.guild.pvmrole.dao; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import org.hibernate.annotations.GenericGenerator; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@EntityListeners(AuditingEntityListener.class) +public class PvmKcSnapshot { + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + + @ManyToOne + @JoinColumn(name = "pvm_role_user_id") + private PvmRoleUser pvmRoleUser; + + @OneToMany(mappedBy = "pvmKcSnapshot", cascade = CascadeType.ALL, orphanRemoval = true) + private List<PvmUserKc> pvmUserKcList = new ArrayList<>(); + + @CreatedDate + private LocalDateTime createdDate; + @LastModifiedDate + private LocalDateTime lastModifiedDate; + + protected PvmKcSnapshot() { + + } + + private PvmKcSnapshot(Builder builder) { + setId(builder.id); + setPvmRoleUser(builder.pvmRoleUser); + setPvmUserKcList(builder.pvmUserKcList); + setCreatedDate(builder.createdDate); + setLastModifiedDate(builder.lastModifiedDate); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public PvmRoleUser getPvmRoleUser() { + return pvmRoleUser; + } + + public void setPvmRoleUser(PvmRoleUser pvmRoleUser) { + this.pvmRoleUser = pvmRoleUser; + } + + public List<PvmUserKc> getPvmUserKcList() { + return pvmUserKcList; + } + + public void setPvmUserKcList(List<PvmUserKc> pvmUserKcList) { + this.pvmUserKcList = pvmUserKcList; + } + + public LocalDateTime getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(LocalDateTime createdDate) { + this.createdDate = createdDate; + } + + public LocalDateTime getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(LocalDateTime lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + + public static final class Builder { + private String id; + private PvmRoleUser pvmRoleUser; + private List<PvmUserKc> pvmUserKcList; + private LocalDateTime createdDate; + private LocalDateTime lastModifiedDate; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder pvmRoleUser(PvmRoleUser val) { + pvmRoleUser = val; + return this; + } + + public Builder pvmUserKcList(List<PvmUserKc> val) { + pvmUserKcList = val; + return this; + } + + public Builder createdDate(LocalDateTime val) { + createdDate = val; + return this; + } + + public Builder lastModifiedDate(LocalDateTime val) { + lastModifiedDate = val; + return this; + } + + public PvmKcSnapshot build() { + return new PvmKcSnapshot(this); + } + } + + @Override + public String toString() { + return "PvmKcSnapshot{" + + "id='" + id + '\'' + + ", pvmRoleUser=" + pvmRoleUser + + ", pvmUserKcList=" + pvmUserKcList + + ", createdDate=" + createdDate + + ", lastModifiedDate=" + lastModifiedDate + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmRoleUser.java @@ -0,0 +1,186 @@ +package com.wimdupont.sxcybot.repository.guild.pvmrole.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Entity +@EntityListeners(AuditingEntityListener.class) +public class PvmRoleUser { + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + private String discordName; + private String rsn; + private String discordId; + @CreatedDate + private LocalDateTime createdDate; + private String createdBy; + @LastModifiedDate + private LocalDateTime lastModifiedDate; + private String lastModifiedBy; + + public String getDiscordId() { + return discordId; + } + + public void setDiscordId(String discordId) { + this.discordId = discordId; + } + + protected PvmRoleUser() { + + } + + private PvmRoleUser(Builder builder) { + setId(builder.id); + setDiscordName(builder.discordName); + setRsn(builder.rsn); + setDiscordId(builder.discordId); + setCreatedDate(builder.createdDate); + setCreatedBy(builder.createdBy); + setLastModifiedDate(builder.lastModifiedDate); + setLastModifiedBy(builder.lastModifiedBy); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDiscordName() { + return discordName; + } + + public void setDiscordName(String discordName) { + this.discordName = discordName; + } + + public String getRsn() { + return rsn; + } + + public void setRsn(String rsn) { + this.rsn = rsn; + } + + public LocalDateTime getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(LocalDateTime createdDate) { + this.createdDate = createdDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public LocalDateTime getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(LocalDateTime lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public static final class Builder { + private String id; + private String discordName; + private String rsn; + private String discordId; + private LocalDateTime createdDate; + private String createdBy; + private LocalDateTime lastModifiedDate; + private String lastModifiedBy; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder discordName(String val) { + discordName = val; + return this; + } + + public Builder rsn(String val) { + rsn = val; + return this; + } + + public Builder discordId(String val) { + discordId = val; + return this; + } + + public Builder createdDate(LocalDateTime val) { + createdDate = val; + return this; + } + + public Builder createdBy(String val) { + createdBy = val; + return this; + } + + public Builder lastModifiedDate(LocalDateTime val) { + lastModifiedDate = val; + return this; + } + + public Builder lastModifiedBy(String val) { + lastModifiedBy = val; + return this; + } + + public PvmRoleUser build() { + return new PvmRoleUser(this); + } + } + + @Override + public String toString() { + return "PvmRoleUser{" + + "id='" + id + '\'' + + ", discordName='" + discordName + '\'' + + ", rsn='" + rsn + '\'' + + ", discordId='" + discordId + '\'' + + ", createdDate=" + createdDate + + ", createdBy='" + createdBy + '\'' + + ", lastModifiedDate=" + lastModifiedDate + + ", lastModifiedBy='" + lastModifiedBy + '\'' + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmUserKc.java b/src/main/java/com/wimdupont/sxcybot/repository/guild/pvmrole/dao/PvmUserKc.java @@ -0,0 +1,184 @@ +package com.wimdupont.sxcybot.repository.guild.pvmrole.dao; + +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToOne; +import org.hibernate.annotations.GenericGenerator; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Entity +@EntityListeners(AuditingEntityListener.class) +public class PvmUserKc { + + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + + @OneToOne + @JoinColumn(name = "pvm_role_user_id") + private PvmRoleUser pvmRoleUser; + + @OneToOne + @JoinColumn(name = "osrs_hiscore_boss_id") + private OsrsHiscoreBoss osrsHiscoreBoss; + + private Integer kc; + + @ManyToOne + @JoinColumn(name = "pvm_kc_snapshot_id") + private PvmKcSnapshot pvmKcSnapshot; + + @CreatedDate + private LocalDateTime createdDate; + @LastModifiedDate + private LocalDateTime lastModifiedDate; + + protected PvmUserKc() { + + } + + private PvmUserKc(Builder builder) { + setId(builder.id); + setPvmRoleUser(builder.pvmRoleUser); + setOsrsHiscoreBoss(builder.osrsHiscoreBoss); + setKc(builder.kc); + setPvmKcSnapshot(builder.pvmKcSnapshot); + setCreatedDate(builder.createdDate); + setLastModifiedDate(builder.lastModifiedDate); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public PvmRoleUser getPvmRoleUser() { + return pvmRoleUser; + } + + public void setPvmRoleUser(PvmRoleUser pvmRoleUser) { + this.pvmRoleUser = pvmRoleUser; + } + + public OsrsHiscoreBoss getOsrsHiscoreBoss() { + return osrsHiscoreBoss; + } + + public void setOsrsHiscoreBoss(OsrsHiscoreBoss osrsHiscoreBoss) { + this.osrsHiscoreBoss = osrsHiscoreBoss; + } + + public Integer getKc() { + return kc; + } + + public void setKc(Integer kc) { + this.kc = kc; + } + + public PvmKcSnapshot getPvmKcSnapshot() { + return pvmKcSnapshot; + } + + public void setPvmKcSnapshot(PvmKcSnapshot pvmKcSnapshot) { + this.pvmKcSnapshot = pvmKcSnapshot; + } + + public LocalDateTime getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(LocalDateTime createdDate) { + this.createdDate = createdDate; + } + + public LocalDateTime getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(LocalDateTime lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + public static final class Builder { + private String id; + private PvmRoleUser pvmRoleUser; + private OsrsHiscoreBoss osrsHiscoreBoss; + private Integer kc; + private PvmKcSnapshot pvmKcSnapshot; + private LocalDateTime createdDate; + private LocalDateTime lastModifiedDate; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder pvmRoleUser(PvmRoleUser val) { + pvmRoleUser = val; + return this; + } + + public Builder osrsHiscoreBoss(OsrsHiscoreBoss val) { + osrsHiscoreBoss = val; + return this; + } + + public Builder kc(Integer val) { + kc = val; + return this; + } + + public Builder pvmKcSnapshot(PvmKcSnapshot val) { + pvmKcSnapshot = val; + return this; + } + + public Builder createdDate(LocalDateTime val) { + createdDate = val; + return this; + } + + public Builder lastModifiedDate(LocalDateTime val) { + lastModifiedDate = val; + return this; + } + + public PvmUserKc build() { + return new PvmUserKc(this); + } + } + + @Override + public String toString() { + return "PvmUserKc{" + + "id='" + id + '\'' + + ", pvmRoleUser=" + pvmRoleUser + + ", osrsHiscoreBoss=" + osrsHiscoreBoss + + ", kc=" + kc + + ", pvmKcSnapshot=" + pvmKcSnapshot + + ", createdDate=" + createdDate + + ", lastModifiedDate=" + lastModifiedDate + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/osrs/OsrsHiscoreBossRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/osrs/OsrsHiscoreBossRepository.java @@ -0,0 +1,13 @@ +package com.wimdupont.sxcybot.repository.osrs; + +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface OsrsHiscoreBossRepository extends JpaRepository<OsrsHiscoreBoss, String> { + + Optional<OsrsHiscoreBoss> findByName(String name); +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/osrs/OsrsHiscoreStatRepository.java b/src/main/java/com/wimdupont/sxcybot/repository/osrs/OsrsHiscoreStatRepository.java @@ -0,0 +1,9 @@ +package com.wimdupont.sxcybot.repository.osrs; + +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreStat; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface OsrsHiscoreStatRepository extends JpaRepository<OsrsHiscoreStat, String> { +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/osrs/dao/OsrsHiscoreBoss.java b/src/main/java/com/wimdupont/sxcybot/repository/osrs/dao/OsrsHiscoreBoss.java @@ -0,0 +1,126 @@ +package com.wimdupont.sxcybot.repository.osrs.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; + + +@Entity +public class OsrsHiscoreBoss { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + private String name; + private int orderValue; + private double multiplier; + private int pvmRole; + + protected OsrsHiscoreBoss() { + + } + + private OsrsHiscoreBoss(Builder builder) { + setId(builder.id); + setName(builder.name); + setOrderValue(builder.orderValue); + setMultiplier(builder.multiplier); + setPvmRole(builder.pvmRole); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getOrderValue() { + return orderValue; + } + + public void setOrderValue(int orderValue) { + this.orderValue = orderValue; + } + + public double getMultiplier() { + return multiplier; + } + + public void setMultiplier(double multiplier) { + this.multiplier = multiplier; + } + + public int getPvmRole() { + return pvmRole; + } + + public void setPvmRole(int pvmRole) { + this.pvmRole = pvmRole; + } + + public static final class Builder { + private String id; + private String name; + private int orderValue; + private double multiplier; + private int pvmRole; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder name(String val) { + name = val; + return this; + } + + public Builder orderValue(int val) { + orderValue = val; + return this; + } + + public Builder multiplier(double val) { + multiplier = val; + return this; + } + + public Builder pvmRole(int val) { + pvmRole = val; + return this; + } + + public OsrsHiscoreBoss build() { + return new OsrsHiscoreBoss(this); + } + } + + @Override + public String toString() { + return "OsrsHiscoreBoss{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + ", orderValue=" + orderValue + + ", multiplier=" + multiplier + + ", pvmRole=" + pvmRole + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/repository/osrs/dao/OsrsHiscoreStat.java b/src/main/java/com/wimdupont/sxcybot/repository/osrs/dao/OsrsHiscoreStat.java @@ -0,0 +1,93 @@ +package com.wimdupont.sxcybot.repository.osrs.dao; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import org.hibernate.annotations.GenericGenerator; + + +@Entity +public class OsrsHiscoreStat { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid") + private String id; + private String name; + private int orderValue; + + protected OsrsHiscoreStat() { + + } + + private OsrsHiscoreStat(Builder builder) { + setId(builder.id); + setName(builder.name); + setOrderValue(builder.orderValue); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getOrderValue() { + return orderValue; + } + + public void setOrderValue(int orderValue) { + this.orderValue = orderValue; + } + + + public static final class Builder { + private String id; + private String name; + private int orderValue; + + private Builder() { + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder id(String val) { + id = val; + return this; + } + + public Builder name(String val) { + name = val; + return this; + } + + public Builder orderValue(int val) { + orderValue = val; + return this; + } + + public OsrsHiscoreStat build() { + return new OsrsHiscoreStat(this); + } + } + + @Override + public String toString() { + return "OsrsHiscoreStat{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + ", orderValue=" + orderValue + + '}'; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/CleanupScheduler.java b/src/main/java/com/wimdupont/sxcybot/services/CleanupScheduler.java @@ -0,0 +1,62 @@ +package com.wimdupont.sxcybot.services; + +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.services.guild.PollService; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmKcSnapshotService; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Comparator; +import java.util.List; + +@Component +public class CleanupScheduler { + + private static final Logger LOGGER = LoggerFactory.getLogger(CleanupScheduler.class); + private static final int POLL_DAYS_VALID = 60; + private final PvmKcSnapshotService pvmKcSnapshotService; + private final PvmRoleUserService pvmRoleUserService; + private final PollService pollService; + + public CleanupScheduler(PvmKcSnapshotService pvmKcSnapshotService, + PvmRoleUserService pvmRoleUserService, + PollService pollService) { + this.pvmKcSnapshotService = pvmKcSnapshotService; + this.pvmRoleUserService = pvmRoleUserService; + this.pollService = pollService; + } + + @Scheduled(cron = "${db.cleanup.schedule}") + @SuppressWarnings("unused") + public void cleanup() { + cleanupPvmKcSnapshots(); + cleanupPolls(); + } + + private void cleanupPvmKcSnapshots() { + List<PvmKcSnapshot> pvmKcSnapshotList; + for (PvmRoleUser pvmRoleUser : pvmRoleUserService.findAll()) { + pvmKcSnapshotList = pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser); + if (pvmKcSnapshotList.size() > 3) { + pvmKcSnapshotList = pvmKcSnapshotList.stream() + .sorted(Comparator.comparing(PvmKcSnapshot::getCreatedDate).reversed()) + .skip(2) + .toList(); + LOGGER.info("deleted {} from {}", pvmKcSnapshotList.size(), pvmRoleUser.getDiscordName()); + pvmKcSnapshotService.deleteAll(pvmKcSnapshotList); + } + } + } + + private void cleanupPolls() { + pollService.findAll().stream().filter(f -> ChronoUnit.DAYS.between(f.getCreatedDate(), LocalDateTime.now()) > POLL_DAYS_VALID) + .peek(f -> LOGGER.info("removed poll {} from {}", f.getMessageId(), f.getCreatedDate())) + .forEach(pollService::delete); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/OsrsMonitoringService.java b/src/main/java/com/wimdupont/sxcybot/services/OsrsMonitoringService.java @@ -0,0 +1,103 @@ +package com.wimdupont.sxcybot.services; + +import com.wimdupont.sxcybot.client.HiScoreClient; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.model.OsrsBossKc; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +@Service +public class OsrsMonitoringService { + + private final Logger LOGGER = LoggerFactory.getLogger("monitor"); + private final HiScoreClient hiScoreClient; + private final PvmRoleUserService pvmRoleUserService; + private final String monitorUserName; + private final String monitorBossName; + private final String monitorBossKc; + + public OsrsMonitoringService(HiScoreClient hiScoreClient, + PvmRoleUserService pvmRoleUserService, + @Value("${monitor.user.name}") String monitorUserName, + @Value("${monitor.boss.name}") String monitorBossName, + @Value("${monitor.boss.kc}") String monitorBossKc) { + this.hiScoreClient = hiScoreClient; + this.pvmRoleUserService = pvmRoleUserService; + this.monitorUserName = monitorUserName; + this.monitorBossName = monitorBossName; + this.monitorBossKc = monitorBossKc; + } + + @Scheduled(cron = "${monitor.schedule}") + @SuppressWarnings("unused") + public void monitor() { + try { + monitorHiscores(); + monitorPvmRoleUserHiscores(null); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + + } + + public void monitorPvmRoleUserHiscores(PrivateChannel privateChannel) { + List<PvmRoleUser> unfound = new ArrayList<>(); + for (PvmRoleUser pvmRoleUser : pvmRoleUserService.findAll()) { + try { + hiScoreClient.getHiScoreBossKc(pvmRoleUser.getRsn(), null).orElseThrow(); + } catch (Exception e) { + unfound.add(pvmRoleUser); + } + } + messageUnfoundResults(unfound, privateChannel); + } + + private void messageUnfoundResults(List<PvmRoleUser> unfound, PrivateChannel privateChannel) { + if (privateChannel == null) { + if (!unfound.isEmpty()) { + LOGGER.error("No hiScores found for: {}", unfound.stream().map(PvmRoleUser::getRsn).toList()); + } else { + LOGGER.info("All PvM Role competitors have been found in the hiscores."); + } + } else { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle("PvM competitor check"); + if (!unfound.isEmpty()) { + embedBuilder.setDescription("No hiscores found for following competitors:"); + unfound.forEach(competitor -> + embedBuilder.addField(competitor.getRsn(), String.format("Discord: %s", competitor.getDiscordName()), true)); + } else { + embedBuilder.setDescription("All PvM role competitors have been found in the hiscores."); + } + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + } + } + + public void monitorHiscores() throws EntityNotFoundException { + List<OsrsBossKc> osrsBossKcs = hiScoreClient.getHiScoreBossKc(monitorUserName, null) + .orElseThrow(() -> new EntityNotFoundException(String.format("No hiscores available for %s.", monitorUserName))); + OsrsBossKc wintertodtBossKc = osrsBossKcs.stream() + .filter(f -> f.name().equals(monitorBossName)) + .findAny() + .orElseThrow(() -> new EntityNotFoundException(String.format("No \"%s\" hiscores found.", monitorBossName))); + + if (wintertodtBossKc.kc().equals(monitorBossKc)) { + LOGGER.info(String.format("Hiscores check is OK. (%s has %s kc on %s)", monitorUserName, monitorBossKc, monitorBossName)); + } else { + LOGGER.error(String.format("Hiscores check not OK: %s kc for user %s is not %s, but is %s", + monitorBossName, monitorUserName, monitorBossKc, wintertodtBossKc.kc())); + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/PvMRoleResolver.java b/src/main/java/com/wimdupont/sxcybot/services/PvMRoleResolver.java @@ -0,0 +1,121 @@ +package com.wimdupont.sxcybot.services; + +import com.wimdupont.sxcybot.enums.PvmRole; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.services.guild.ChannelDetailService; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleAssignerService; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleSnapshotComparatorService; +import com.wimdupont.sxcybot.services.guild.pvmrole.PvmRoleUserService; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.entities.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Component +public class PvMRoleResolver { + + private static final Logger LOGGER = LoggerFactory.getLogger(PvMRoleResolver.class); + private final PvmRoleUserService pvmRoleUserService; + private final ChannelDetailService channelDetailService; + private final PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService; + private final PvmRoleAssignerService pvmRoleAssignerService; + + public PvMRoleResolver(PvmRoleUserService pvmRoleUserService, + ChannelDetailService channelDetailService, + PvmRoleSnapshotComparatorService pvmRoleSnapshotComparatorService, + PvmRoleAssignerService pvmRoleAssignerService) { + this.pvmRoleUserService = pvmRoleUserService; + this.channelDetailService = channelDetailService; + this.pvmRoleSnapshotComparatorService = pvmRoleSnapshotComparatorService; + this.pvmRoleAssignerService = pvmRoleAssignerService; + } + + @Scheduled(cron = "${pvm.role.schedule}") + @SuppressWarnings("unused") + public void resolvePvMRoles() { + LOGGER.info("Running scheduled pvmRoleResolver."); + resolvePvMRoles(true, null); + } + + @Scheduled(cron = "${pvm.role.schedule.discord}") + public void updatePvMRoleDiscordNames() { + LOGGER.info("STARTING - Update discord names of PvmRoleUsers."); + channelDetailService.getJda().getGuilds().forEach(guild -> + guild.loadMembers().onSuccess(members -> { + List<PvmRoleUser> pvmRoleUsers = pvmRoleUserService.findAll(); + LOGGER.debug("Updating discordIds"); + pvmRoleUsers.stream() + .filter(f -> f.getDiscordId() == null) + .forEach(roleUser -> { + roleUser.setDiscordId(members.stream().filter(f -> roleUser.getDiscordName().equals(f.getUser().getName()) + || roleUser.getDiscordName().equals(f.getNickname()) + || roleUser.getDiscordName().equals(f.getEffectiveName())) + .findFirst() + .map(Member::getUser) + .map(User::getId) + .stream().findAny().orElse(null)); + pvmRoleUserService.save(roleUser); + LOGGER.debug("Updated discordId: {}", roleUser); + }); + LOGGER.debug("Updating discordNames"); + pvmRoleUsers.stream() + .filter(f -> f.getDiscordId() != null) + .forEach(roleUser -> { + members.stream() + .map(Member::getUser) + .map(User::getId) + .filter(f -> f.equals(roleUser.getDiscordId())) + .findAny() + .ifPresent(discordId -> { + roleUser.setDiscordName(members.stream() + .filter(f -> f.getUser().getId().equals(discordId)) + .findAny() + .map(Member::getEffectiveName) + .orElse(roleUser.getDiscordName())); + pvmRoleUserService.save(roleUser); + LOGGER.debug("Updated discordName: {}", roleUser); + }); + }); + } + )); + LOGGER.info("FINISHED - Update discord names of PvmRoleUsers."); + } + + public void resolvePvMRoles(boolean persist, PrivateChannel privateChannel) { + Map<PvmRole, LinkedHashMap<PvmRoleUser, BigDecimal>> scoreBoard = new HashMap<>(); + for (PvmRole pvmRole : PvmRole.values()) { + if (!pvmRole.equals(PvmRole.UNUSED)) + scoreBoard.put(pvmRole, new LinkedHashMap<>()); + } + channelDetailService.getJda().getGuilds().forEach(guild -> + channelDetailService.findAll().stream().findAny().ifPresent(channelDetail -> + (privateChannel == null ? guild.getTextChannelsByName(channelDetail.getPvmRoleChannel(), true) : List.of(privateChannel)) + .forEach(textChannel -> { + for (PvmRoleUser pvmRoleUser : pvmRoleUserService.findAll()) { + List<PvmKcSnapshot> pvmKcSnapshots = new ArrayList<>(); + try { + pvmKcSnapshots.add(pvmRoleSnapshotComparatorService.takeSnapshot(textChannel, pvmRoleUser, false, persist)); + } catch (EntityNotFoundException e) { + textChannel.sendMessage(e.getMessage()).queue(); + continue; + } + pvmRoleSnapshotComparatorService.updateScoreboard(pvmRoleUser, scoreBoard, persist ? null : pvmKcSnapshots); + } + pvmRoleAssignerService.postScoreboardAndAssignRoles(guild, textChannel, scoreBoard, channelDetail, persist); + }) + ) + ); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/ChannelDetailService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/ChannelDetailService.java @@ -0,0 +1,34 @@ +package com.wimdupont.sxcybot.services.guild; + +import com.wimdupont.sxcybot.repository.guild.ChannelDetailRepository; +import com.wimdupont.sxcybot.repository.guild.dao.ChannelDetail; +import net.dv8tion.jda.api.JDA; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class ChannelDetailService { + + private final ChannelDetailRepository channelDetailRepository; + + private JDA jda; + + public JDA getJda() { + return jda; + } + + public void setJda(JDA jda) { + this.jda = jda; + } + + public ChannelDetailService(ChannelDetailRepository channelDetailRepository) { + this.channelDetailRepository = channelDetailRepository; + } + + public List<ChannelDetail> findAll() { + return channelDetailRepository.findAll(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/GuildEventDmerService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/GuildEventDmerService.java @@ -0,0 +1,23 @@ +package com.wimdupont.sxcybot.services.guild; + +import com.wimdupont.sxcybot.repository.guild.GuildEventDmerRepository; +import com.wimdupont.sxcybot.repository.guild.dao.GuildEventDmer; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class GuildEventDmerService { + + private final GuildEventDmerRepository guildEventDmerRepository; + + public GuildEventDmerService(GuildEventDmerRepository guildEventDmerRepository) { + this.guildEventDmerRepository = guildEventDmerRepository; + } + + public List<GuildEventDmer> findAll() { + return guildEventDmerRepository.findAll(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/GuildRoleService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/GuildRoleService.java @@ -0,0 +1,45 @@ +package com.wimdupont.sxcybot.services.guild; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.repository.guild.GuildRoleRepository; +import com.wimdupont.sxcybot.repository.guild.dao.GuildRole; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class GuildRoleService { + + private final GuildRoleRepository guildRoleRepository; + + public GuildRoleService(GuildRoleRepository guildRoleRepository) { + this.guildRoleRepository = guildRoleRepository; + } + + public List<GuildRole> findAllByElevationLessThanEqual(int elevation) { + return guildRoleRepository.findByElevationLessThanEqual(elevation); + } + + public List<GuildRole> findAllByElevationGreaterThanEqual(int elevation) { + return guildRoleRepository.findByElevationGreaterThanEqual(elevation); + } + + public GuildRole findByName(String name) throws EntityNotFoundException { + return guildRoleRepository.findByName(name).orElseThrow( + () -> new EntityNotFoundException(String.format("No role found with name %s.", name))); + } + + public GuildRole save(GuildRole guildRole) { + return guildRoleRepository.save(guildRole); + } + + public void delete(GuildRole guildRole) { + guildRoleRepository.delete(guildRole); + } + + public List<GuildRole> findAll() { + return guildRoleRepository.findAll(); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/PollService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/PollService.java @@ -0,0 +1,36 @@ +package com.wimdupont.sxcybot.services.guild; + +import com.wimdupont.sxcybot.repository.guild.PollRepository; +import com.wimdupont.sxcybot.repository.guild.dao.Poll; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +@Service +@Transactional +public class PollService { + + private final PollRepository pollRepository; + + public PollService(PollRepository pollRepository) { + this.pollRepository = pollRepository; + } + + public List<Poll> findAll() { + return pollRepository.findAll(); + } + + public Optional<Poll> findByMessageId(String messageId) { + return pollRepository.findByMessageId(messageId); + } + + public Poll save(Poll poll) { + return pollRepository.save(poll); + } + + public void delete(Poll poll) { + pollRepository.delete(poll); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/RuleService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/RuleService.java @@ -0,0 +1,37 @@ +package com.wimdupont.sxcybot.services.guild; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.repository.guild.RuleRepository; +import com.wimdupont.sxcybot.repository.guild.dao.Rule; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class RuleService { + + private final RuleRepository ruleRepository; + + public RuleService(RuleRepository ruleRepository) { + this.ruleRepository = ruleRepository; + } + + public List<Rule> findAll() { + return ruleRepository.findAll(); + } + + public Rule findByNumber(int number) throws EntityNotFoundException { + return ruleRepository.findByNumber(number).orElseThrow( + () -> new EntityNotFoundException(String.format("Rule with number %s not found.", number))); + } + + public Rule save(Rule rule) { + return ruleRepository.save(rule); + } + + public void delete(Rule rule) { + ruleRepository.delete(rule); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/UserService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/UserService.java @@ -0,0 +1,38 @@ +package com.wimdupont.sxcybot.services.guild; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.repository.guild.UserRepository; +import com.wimdupont.sxcybot.repository.guild.dao.User; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class UserService { + + private final UserRepository userRepository; + + public UserService(UserRepository userRepository) { + this.userRepository = userRepository; + } + + public List<User> findAllBanned() { + return userRepository.findAllByBannedTrue(); + } + + public User save(User user) { + return userRepository.save(user); + } + + public void delete(User user) throws EntityNotFoundException { + findByName(user.getName()); + userRepository.delete(user); + } + + public User findByName(String name) throws EntityNotFoundException { + return userRepository.findByName(name).orElseThrow( + () -> new EntityNotFoundException(String.format("No user found with name %s.", name))); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmKcSnapshotService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmKcSnapshotService.java @@ -0,0 +1,36 @@ +package com.wimdupont.sxcybot.services.guild.pvmrole; + +import com.wimdupont.sxcybot.repository.guild.pvmrole.PvmKcSnapshotRepository; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PvmKcSnapshotService { + + private final PvmKcSnapshotRepository pvmKcSnapshotRepository; + + public PvmKcSnapshotService(PvmKcSnapshotRepository pvmKcSnapshotRepository) { + this.pvmKcSnapshotRepository = pvmKcSnapshotRepository; + } + + public List<PvmKcSnapshot> findAll() { + return pvmKcSnapshotRepository.findAll(); + } + + public List<PvmKcSnapshot> findAllByPvmRoleUser(PvmRoleUser pvmRoleUser) { + return pvmKcSnapshotRepository.findAllByPvmRoleUserId(pvmRoleUser.getId()); + } + + public PvmKcSnapshot save(PvmKcSnapshot pvmKcSnapshot) { + return pvmKcSnapshotRepository.save(pvmKcSnapshot); + } + + public void deleteAll(List<PvmKcSnapshot> pvmKcSnapshots) { + pvmKcSnapshotRepository.deleteAll(pvmKcSnapshots); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleAssignerService.java @@ -0,0 +1,92 @@ +package com.wimdupont.sxcybot.services.guild.pvmrole; + +import com.wimdupont.sxcybot.enums.PvmRole; +import com.wimdupont.sxcybot.repository.guild.dao.ChannelDetail; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.MessageChannel; +import net.dv8tion.jda.api.entities.Role; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.awt.Color; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +@Transactional +public class PvmRoleAssignerService { + + public void postScoreboardAndAssignRoles(Guild guild, MessageChannel textChannel, Map<PvmRole, LinkedHashMap<PvmRoleUser, BigDecimal>> scoreBoard, ChannelDetail channelDetail, boolean persist) { + for (PvmRole pvmRole : scoreBoard.keySet()) { + String rolename = getRolename(pvmRole, channelDetail); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle(String.format("**%s** Scoreboard results:", rolename)); + if (scoreBoard.get(pvmRole).isEmpty()) { + embedBuilder.addField(String.format("No KC gains detected for %s", pvmRole.name().toLowerCase()), "No increase in KC found for participants, role will remain unchanged.", false); + textChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + continue; + } + List<Map.Entry<PvmRoleUser, BigDecimal>> entries = new ArrayList<>(scoreBoard.get(pvmRole).entrySet()); + entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); + scoreBoard.get(pvmRole).clear(); + entries.forEach(f -> scoreBoard.get(pvmRole).put(f.getKey(), f.getValue())); + guild.loadMembers().onSuccess(memberlist -> { + long limit = 5; + int i = 1; + int winningRank = 1; + for (Map.Entry<PvmRoleUser, BigDecimal> entry : scoreBoard.get(pvmRole).entrySet()) { + if (limit-- == 0) break; + Optional<Member> member = memberlist.stream().filter(f -> f.getUser().getId().equals(entry.getKey().getDiscordId())).findAny(); + if (member.isPresent()) { + embedBuilder.addField(String.format("#%s %s", i, entry.getKey().getRsn()), String.format("%s with a score of %s!", member.get(), entry.getValue()), false); + if (i == winningRank && persist) { + Optional<Role> role = guild.getRoles().stream().filter(f -> rolename.equalsIgnoreCase(f.getName())).findFirst(); + if (role.isPresent()) { + guild.findMembersWithRoles(role.get()) + .onSuccess(oldWinners -> { + if (oldWinners.isEmpty()) { + addRoleToWinner(guild, member.get(), role.get(), textChannel, entry.getKey().getRsn()); + } else { + oldWinners.forEach(f -> guild.removeRoleFromMember(f, role.get()).queue(complete -> + addRoleToWinner(guild, member.get(), role.get(), textChannel, entry.getKey().getRsn()))); + } + }); + } else { + textChannel.sendMessage(String.format("No role %s found in the channel, role could not get assigned.", rolename)).queue(); + } + } + } else { + if (i == winningRank) winningRank++; + embedBuilder.addField(String.format("#%s %s", i, entry.getKey().getRsn()), String.format("%s with a score of %s!", entry.getKey().getDiscordName(), entry.getValue()), false); + textChannel.sendMessage(String.format("No guildmember found for discordname %s. User did not receive any awards.", entry.getKey().getDiscordName())).queue(); + } + i++; + } + textChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + }); + } + } + + private String getRolename(PvmRole pvmRole, ChannelDetail channelDetail) { + return switch (pvmRole) { + case GENERAL -> channelDetail.getPvmRoleGeneral(); + case RAIDS -> channelDetail.getPvmRoleRaids(); + case WILDERNESS -> channelDetail.getPvmRoleWilderness(); + default -> "Something went wrong."; + }; + } + + private void addRoleToWinner(Guild guild, Member member, Role role, MessageChannel textChannel, String rsn) { + guild.addRoleToMember(member, role).queue(ok -> + textChannel.sendMessage(String.format("%s is our new %s!", rsn, role)).queue()); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleSnapshotComparatorService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleSnapshotComparatorService.java @@ -0,0 +1,99 @@ +package com.wimdupont.sxcybot.services.guild.pvmrole; + +import com.wimdupont.sxcybot.client.HiScoreClient; +import com.wimdupont.sxcybot.enums.PvmRole; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.model.OsrsBossKc; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmKcSnapshot; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmUserKc; +import com.wimdupont.sxcybot.services.osrs.OsrsHiscoreBossService; +import net.dv8tion.jda.api.entities.MessageChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Service +@Transactional +public class PvmRoleSnapshotComparatorService { + + private static final Logger LOGGER = LoggerFactory.getLogger(PvmRoleSnapshotComparatorService.class); + private final OsrsHiscoreBossService osrsHiscoreBossService; + private final PvmKcSnapshotService pvmKcSnapshotService; + private final HiScoreClient hiScoreClient; + + public PvmRoleSnapshotComparatorService(OsrsHiscoreBossService osrsHiscoreBossService, + PvmKcSnapshotService pvmKcSnapshotService, + HiScoreClient hiScoreClient) { + this.osrsHiscoreBossService = osrsHiscoreBossService; + this.pvmKcSnapshotService = pvmKcSnapshotService; + this.hiScoreClient = hiScoreClient; + } + + public void updateScoreboard(PvmRoleUser pvmRoleUser, Map<PvmRole, LinkedHashMap<PvmRoleUser, BigDecimal>> scoreBoard, List<PvmKcSnapshot> unpersistedSnapshots) { + boolean persisted = unpersistedSnapshots == null; + List<PvmKcSnapshot> pvmKcSnapshots = pvmKcSnapshotService.findAllByPvmRoleUser(pvmRoleUser); + if (pvmKcSnapshots != null && (pvmKcSnapshots.size() > 1 || (!persisted && pvmKcSnapshots.size() > 0))) { + pvmKcSnapshots = pvmKcSnapshots.stream() + .sorted(Comparator.comparing(PvmKcSnapshot::getCreatedDate) + .reversed()) + .limit(persisted ? 2 : 1) + .toList(); + for (PvmRole pvmRole : scoreBoard.keySet()) { + BigDecimal points1 = calculatePoints(pvmRole, persisted ? pvmKcSnapshots.get(0) : unpersistedSnapshots.get(0)); + BigDecimal points2 = calculatePoints(pvmRole, pvmKcSnapshots.get(persisted ? 1 : 0)); + BigDecimal result = points1.subtract(points2); + if (BigDecimal.ZERO.compareTo(result) < 0) + scoreBoard.get(pvmRole).put(pvmRoleUser, result); + } + } + } + + private BigDecimal calculatePoints(PvmRole pvmRole, PvmKcSnapshot pvmKcSnapshot) { + BigDecimal points = BigDecimal.ZERO; + for (PvmUserKc pvmUserKc : pvmKcSnapshot.getPvmUserKcList().stream().filter(f -> pvmRole.value == f.getOsrsHiscoreBoss().getPvmRole()).toList()) { + points = points.add(BigDecimal.valueOf(pvmUserKc.getOsrsHiscoreBoss().getMultiplier()).multiply(BigDecimal.valueOf(pvmUserKc.getKc()))); + } + return points; + } + + public PvmKcSnapshot takeSnapshot(MessageChannel textChannel, PvmRoleUser pvmRoleUser, boolean notify, boolean persist) throws EntityNotFoundException { + PvmKcSnapshot pvmKcSnapshot = PvmKcSnapshot.Builder.newBuilder() + .pvmRoleUser(pvmRoleUser) + .build(); + List<OsrsBossKc> osrsBossKcList = hiScoreClient.getHiScoreBossKc(pvmRoleUser.getRsn(), textChannel).orElseThrow( + () -> new EntityNotFoundException(String.format("No hiScores found for %s", pvmRoleUser.getRsn())) + ); + List<PvmUserKc> pvmUserKcList = new ArrayList<>(); + for (OsrsBossKc osrsBossKc : osrsBossKcList.stream().filter(r -> Integer.parseInt(r.kc()) > 0).toList()) { + try { + PvmUserKc pvmUserKc = PvmUserKc.Builder.newBuilder() + .pvmRoleUser(pvmRoleUser) + .osrsHiscoreBoss(osrsHiscoreBossService.findByName(osrsBossKc.name())) + .pvmKcSnapshot(pvmKcSnapshot) + .kc(Integer.valueOf(osrsBossKc.kc())) + .build(); + pvmUserKcList.add(pvmUserKc); + } catch (EntityNotFoundException e) { + LOGGER.error(e.getMessage(), e); + } + } + pvmKcSnapshot.setPvmUserKcList(pvmUserKcList); + + if (persist) { + pvmKcSnapshot = pvmKcSnapshotService.save(pvmKcSnapshot); + if (notify) + textChannel.sendMessage(String.format("KC snapshot saved for %s.%n", pvmRoleUser.getRsn())).queue(); + } + + return pvmKcSnapshot; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleUserService.java b/src/main/java/com/wimdupont/sxcybot/services/guild/pvmrole/PvmRoleUserService.java @@ -0,0 +1,39 @@ +package com.wimdupont.sxcybot.services.guild.pvmrole; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.repository.guild.pvmrole.PvmRoleUserRepository; +import com.wimdupont.sxcybot.repository.guild.pvmrole.dao.PvmRoleUser; +import org.springframework.stereotype.Service; + +import java.util.List; + +import static com.wimdupont.sxcybot.enums.Command.PVMLIST; +import static com.wimdupont.sxcybot.util.Constants.Commands.COMMAND_PREFIX; + +@Service +public class PvmRoleUserService { + + private final PvmRoleUserRepository pvmRoleUserRepository; + + public PvmRoleUserService(PvmRoleUserRepository pvmRoleUserRepository) { + this.pvmRoleUserRepository = pvmRoleUserRepository; + } + + public List<PvmRoleUser> findAll() { + return pvmRoleUserRepository.findAll(); + } + + public PvmRoleUser save(PvmRoleUser pvmRoleUser) { + return pvmRoleUserRepository.save(pvmRoleUser); + } + + public PvmRoleUser findByDiscordName(String discordName) throws EntityNotFoundException { + return pvmRoleUserRepository.findByDiscordName(discordName).orElseThrow(() + -> new EntityNotFoundException(String.format("No discord user found with name %s in the PvM competition.%sYou can check all competitors with the \"%s\" command." + , discordName, System.lineSeparator(), COMMAND_PREFIX + PVMLIST.name().toLowerCase()))); + } + + public void delete(PvmRoleUser pvmRoleUser) { + pvmRoleUserRepository.delete(pvmRoleUser); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/osrs/CombatCalculatorService.java b/src/main/java/com/wimdupont/sxcybot/services/osrs/CombatCalculatorService.java @@ -0,0 +1,29 @@ +package com.wimdupont.sxcybot.services.osrs; + +import com.wimdupont.sxcybot.model.CombatDto; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +@Service +@Transactional +public class CombatCalculatorService { + + public double getCombatLevel(CombatDto combatDto) { + double base = 0.25 * (combatDto.defenceLevel() + combatDto.hitpointsLevel() + (combatDto.prayerLevel() / 2)); + + double typeContribution = getMeleeRangeOrMagicCombatLevelContribution(combatDto.attackLevel(), combatDto.strengthLevel(), combatDto.magicLevel(), combatDto.rangeLevel()); + + return BigDecimal.valueOf(base + typeContribution).setScale(3, RoundingMode.HALF_UP).doubleValue(); + } + + private double getMeleeRangeOrMagicCombatLevelContribution(int attackLevel, int strengthLevel, int magicLevel, int rangeLevel) { + double melee = 0.325 * (attackLevel + strengthLevel); + double range = 0.325 * (rangeLevel / 2 + rangeLevel); + double magic = 0.325 * (magicLevel / 2 + magicLevel); + + return Math.max(melee, Math.max(range, magic)); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/osrs/OsrsHiscoreBossService.java b/src/main/java/com/wimdupont/sxcybot/services/osrs/OsrsHiscoreBossService.java @@ -0,0 +1,30 @@ +package com.wimdupont.sxcybot.services.osrs; + +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.repository.osrs.OsrsHiscoreBossRepository; +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class OsrsHiscoreBossService { + + private final OsrsHiscoreBossRepository osrsHiscoreBossRepository; + + public OsrsHiscoreBossService(OsrsHiscoreBossRepository osrsHiscoreBossRepository) { + this.osrsHiscoreBossRepository = osrsHiscoreBossRepository; + } + + public List<OsrsHiscoreBoss> findAll() { + return osrsHiscoreBossRepository.findAll(Sort.by("orderValue").ascending()); + } + + public OsrsHiscoreBoss findByName(String name) throws EntityNotFoundException { + return osrsHiscoreBossRepository.findByName(name).orElseThrow( + () -> new EntityNotFoundException(String.format("No hiscoreBoss found with name %s.", name))); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/osrs/OsrsHiscoreStatService.java b/src/main/java/com/wimdupont/sxcybot/services/osrs/OsrsHiscoreStatService.java @@ -0,0 +1,24 @@ +package com.wimdupont.sxcybot.services.osrs; + +import com.wimdupont.sxcybot.repository.osrs.OsrsHiscoreStatRepository; +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreStat; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class OsrsHiscoreStatService { + + private final OsrsHiscoreStatRepository osrsHiscoreStatRepository; + + public OsrsHiscoreStatService(OsrsHiscoreStatRepository osrsHiscoreStatRepository) { + this.osrsHiscoreStatRepository = osrsHiscoreStatRepository; + } + + public List<OsrsHiscoreStat> findAll() { + return osrsHiscoreStatRepository.findAll(Sort.by("orderValue").ascending()); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/services/osrs/StatMessageSender.java b/src/main/java/com/wimdupont/sxcybot/services/osrs/StatMessageSender.java @@ -0,0 +1,49 @@ +package com.wimdupont.sxcybot.services.osrs; + +import com.wimdupont.sxcybot.client.HiScoreClient; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import com.wimdupont.sxcybot.model.OsrsStat; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.awt.Color; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Predicate; + +@Service +@Transactional +public class StatMessageSender { + + private final HiScoreClient hiScoreClient; + + public StatMessageSender(HiScoreClient hiScoreClient) { + this.hiScoreClient = hiScoreClient; + } + + public void sendStatMessage(MessageReceivedEvent event, EmbedBuilder embedBuilder, + Predicate<OsrsStat> predicate, Consumer<OsrsStat> consumer + , Consumer<List<OsrsStat>> calcCombatLevel) { + String msg = event.getMessage().getContentRaw(); + try { + String player = msg.substring(msg.indexOf(" ")).trim(); + try { + embedBuilder.setColor(Color.RED); + embedBuilder.setTitle(String.format("Stats of %s", player)); + List<OsrsStat> osrsStatList = hiScoreClient.getHiScoreStats(player, event.getChannel()).orElseThrow(() + -> new EntityNotFoundException(String.format("No HiScores found for %s.", player))); + osrsStatList.stream().filter(predicate).forEach(consumer); + if (calcCombatLevel != null) { + calcCombatLevel.accept(osrsStatList); + } + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + } catch (EntityNotFoundException entityNotFoundException) { + event.getChannel().sendMessage(entityNotFoundException.getMessage()).queue(); + } + } catch (StringIndexOutOfBoundsException e) { + event.getChannel().sendMessage("Please enter a player name after the command, separated by space.").queue(); + } + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/Constants.java b/src/main/java/com/wimdupont/sxcybot/util/Constants.java @@ -0,0 +1,38 @@ +package com.wimdupont.sxcybot.util; + + +public class Constants { + + private Constants() { + } + + public static final int ADDED_ROLE_ELEVATION = 100; + + public static class Commands { + private Commands() { + } + + public static final String COMMAND_PREFIX = "sb-"; + public static final String BB8 = COMMAND_PREFIX + "8"; + } + + public static class Emoji { + + private Emoji() { + } + + public static final String THUMBS_UP = ":+1:"; + public static final String FLAMES = ":flame:"; + } + + public static class Reaction { + private Reaction() { + } + + public static final String CHECK_MARK = "U+2714"; + public static final String CROSS_MARK = "U+274C"; + public static final String QUESTION_MARK = "U+2753"; + public static final String CHECK_MARK_BUTTON = "U+2705"; + public static final String CROSS_MARK_BUTTON = "U+274E"; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/CustomPollFiller.java b/src/main/java/com/wimdupont/sxcybot/util/CustomPollFiller.java @@ -0,0 +1,80 @@ +package com.wimdupont.sxcybot.util; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.repository.guild.dao.Poll; +import com.wimdupont.sxcybot.services.guild.PollService; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.util.Set; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class CustomPollFiller { + + private final EventWaiterUtil eventWaiterUtil; + private final PollService pollService; + private static final String STOP_WORD = "stop"; + + public CustomPollFiller(EventWaiterUtil eventWaiterUtil, + PollService pollService) { + this.eventWaiterUtil = eventWaiterUtil; + this.pollService = pollService; + } + +// private static final String EMOJI_REGEX = "([\\u20a0-\\u32ff\\ud83c\\udc00-\\ud83d\\udeff\\udbb9\\udce5-\\udbb9\\udcee])"; + + public void fillPoll(PrivateChannel privateChannel, MessageReceivedEvent event, EmbedBuilder embedBuilder, Set<String> emojiList) { + EmbedBuilder embeddedOption = new EmbedBuilder(); + embeddedOption.setColor(Color.RED); + embeddedOption.addField("Please enter an option for the poll", "`stop` to finish and create the poll.", false); + privateChannel.sendMessageEmbeds(embeddedOption.build()).queue(); + embeddedOption.clear(); + eventWaiterUtil.waitForPrivateChannelEvent(optionReceiver -> { + if (isReadyToStop(optionReceiver)) { + event.getChannel().sendTyping().queue(typing -> + event.getChannel().sendMessageEmbeds(embedBuilder.build()).queue(message -> { + emojiList.forEach(emoji -> message.addReaction(emoji).queue()); + pollService.save(Poll.Builder.newBuilder().messageId(message.getId()).build()); + })); + return; + } + embeddedOption.setColor(Color.RED); + embeddedOption.addField(String.format("Please type in a reaction emoji for _%s_.", optionReceiver.getMessage().getContentRaw()), "", false); + privateChannel.sendMessageEmbeds(embeddedOption.build()).queue(); + embeddedOption.clear(); + eventWaiterUtil.waitForPrivateChannelEvent(emojiReceiver -> { + if (!emojiList.contains(emojiReceiver.getMessage().getContentRaw())) { + if (!isValidEmoji(emojiReceiver.getMessage().getContentRaw())) { + privateChannel.sendMessage(String.format("%s is not a valid emoji, please retry this option.", emojiReceiver.getMessage().getContentRaw())).queue(); + this.fillPoll(privateChannel, event, embedBuilder, emojiList); + return; + } + embedBuilder.addField(String.format("%s %s %s", emojiReceiver.getMessage().getContentRaw(), optionReceiver.getMessage().getContentRaw(), "(0)"), "", true); + emojiList.add(emojiReceiver.getMessage().getContentRaw()); + } else { + privateChannel.sendMessage(String.format("Emoji %s was already picked for another options, please retry this option.", emojiReceiver.getMessage().getContentRaw())).queue(); + } + this.fillPoll(privateChannel, event, embedBuilder, emojiList); + }, event, privateChannel); + }, event, privateChannel); + } + + private boolean isReadyToStop(PrivateMessageReceivedEvent privateMessageReceivedEvent) { + return privateMessageReceivedEvent.getMessage().getContentRaw().equalsIgnoreCase(STOP_WORD); + } + + private boolean isValidEmoji(String emoji) { + /* + TODO fix: + return Pattern.compile(EMOJI_REGEX).matcher(emoji).find(); + */ + return true; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/DiscordMemberFinderUtil.java b/src/main/java/com/wimdupont/sxcybot/util/DiscordMemberFinderUtil.java @@ -0,0 +1,50 @@ +package com.wimdupont.sxcybot.util; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.PrivateChannel; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import org.springframework.stereotype.Component; + +import java.util.Optional; +import java.util.function.Consumer; + +@Component +public class DiscordMemberFinderUtil { + + private final EventWaiterUtil eventWaiterUtil; + + public DiscordMemberFinderUtil(EventWaiterUtil eventWaiterUtil) { + this.eventWaiterUtil = eventWaiterUtil; + } + + public void onMemberFoundVerification(MessageReceivedEvent event, EmbedBuilder embedBuilder, PrivateChannel privateChannel, Consumer<Member> memberConsumer) { + embedBuilder.addField("Type the name of the user.", "Discord username will be looked up first, if no match is found it will search on nickname.", false); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + eventWaiterUtil.waitForPrivateChannelEvent(memberReceiver -> { + String name = memberReceiver.getMessage().getContentRaw(); + event.getGuild().loadMembers().onSuccess(memberList -> { + if (memberList.isEmpty()) { + privateChannel.sendMessage(String.format("User with name %s not found, please try again later.", name)).queue(); + } else { + Optional<Member> member = memberList.stream().filter(f -> name.equalsIgnoreCase(f.getUser().getName()) || name.equalsIgnoreCase(f.getNickname())).findFirst(); + if (member.isPresent()) { + embedBuilder.clearFields(); + embedBuilder.addField("Confirm by typing ``yes or y``.", String.format("Is %s the correct member?", member.get()), false); + privateChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + eventWaiterUtil.waitForPrivateChannelEvent(memberVerifyReceiver -> { + String verifyMessage = memberVerifyReceiver.getMessage().getContentRaw(); + if ("y".equalsIgnoreCase(verifyMessage) || "yes".equalsIgnoreCase(verifyMessage)) { + memberConsumer.accept(member.get()); + } + embedBuilder.clearFields(); + }, event, privateChannel); + } else { + privateChannel.sendMessage(String.format("User with name %s not found, please try again later.", name)).queue(); + } + } + }); + }, event, privateChannel); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/EditListenerUtil.java b/src/main/java/com/wimdupont/sxcybot/util/EditListenerUtil.java @@ -0,0 +1,42 @@ +package com.wimdupont.sxcybot.util; + +import com.wimdupont.sxcybot.listeners.EventWaiterUtil; +import com.wimdupont.sxcybot.model.EditListenerDto; +import net.dv8tion.jda.api.EmbedBuilder; +import org.springframework.stereotype.Component; + +import java.awt.Color; + +@Component +public class EditListenerUtil { + + private final EventWaiterUtil eventWaiterUtil; + + public EditListenerUtil(EventWaiterUtil eventWaiterUtil) { + this.eventWaiterUtil = eventWaiterUtil; + } + + public void procesEditEvent(EditListenerDto editListenerDto) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.red); + embedBuilder.setTitle("What do you want to do?"); + embedBuilder.addField("1", String.format("Add a new %s.", editListenerDto.entityName()), false); + embedBuilder.addField("2", String.format("Delete an existing %s.", editListenerDto.entityName()), false); + if (editListenerDto.updateListener() != null) + embedBuilder.addField("3", String.format("Update an existing %s.", editListenerDto.entityName()), false); + editListenerDto.privateChannel().sendMessageEmbeds(embedBuilder.build()).queue(); + eventWaiterUtil.waitForPrivateChannelEvent(commandReceiver -> { + switch (commandReceiver.getMessage().getContentRaw()) { + case "1" -> editListenerDto.addListener().proces(commandReceiver, editListenerDto.event()); + case "2" -> editListenerDto.deleteListener().proces(commandReceiver, editListenerDto.event()); + case "3" -> { + if (editListenerDto.updateListener() != null) + editListenerDto.updateListener().proces(commandReceiver, editListenerDto.event()); + } + default -> + editListenerDto.privateChannel().sendMessage("Unknown command, please try again.").queue(); + } + }, editListenerDto.event(), editListenerDto.privateChannel()); + } + +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/JdaUtil.java b/src/main/java/com/wimdupont/sxcybot/util/JdaUtil.java @@ -0,0 +1,37 @@ +package com.wimdupont.sxcybot.util; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +@Component +public class JdaUtil { + + public static Optional<String> getName(GenericMessageReactionEvent event) { + var nickName = Optional.ofNullable(event.getMember()) + .map(Member::getNickname); + return nickName.isPresent() ? nickName : Optional.ofNullable(event.getUser()) + .map(User::getName); + } + + public static Optional<String> getName(MessageReceivedEvent event) { + var nickName = Optional.ofNullable(event.getMember()) + .map(Member::getNickname); + return nickName.isPresent() ? nickName : Optional.ofNullable(event.getMember()) + .map(Member::getUser) + .map(User::getName); + } + + public static User getUser(MessageReceivedEvent event) { + return event.getMember() != null ? event.getMember().getUser() : null; + } + + public static boolean requiresBuild(EmbedBuilder embedBuilder, int size, int count) { + return (embedBuilder.length() > 5000 || embedBuilder.getFields().size() == 25 || size == count); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/NumberFormatter.java b/src/main/java/com/wimdupont/sxcybot/util/NumberFormatter.java @@ -0,0 +1,15 @@ +package com.wimdupont.sxcybot.util; + +import java.text.NumberFormat; +import java.util.Locale; + +public class NumberFormatter { + + public static String format(String numberToFormat) { + return format(Integer.valueOf(numberToFormat)); + } + + public static String format(Integer numberToFormat) { + return NumberFormat.getNumberInstance(Locale.UK).format(numberToFormat); + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/ReleaseNotesUtil.java b/src/main/java/com/wimdupont/sxcybot/util/ReleaseNotesUtil.java @@ -0,0 +1,65 @@ +package com.wimdupont.sxcybot.util; + + +import com.wimdupont.sxcybot.services.guild.ChannelDetailService; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.JDA; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.awt.Color; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +@Component +public class ReleaseNotesUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(ReleaseNotesUtil.class); + private final ChannelDetailService channelDetailService; + + private static final String GITLAB_URL = "https://gitlab.com/WimDupont/sxcybot"; + + public ReleaseNotesUtil(ChannelDetailService channelDetailService) { + this.channelDetailService = channelDetailService; + } + + public void showReleaseNotes(JDA jda) { + Map<String, String> releaseNotes = ReleaseNotesUtil.getReleaseNotes(); + if (!releaseNotes.isEmpty()) { + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(Color.RED); + embedBuilder.setTitle(String.format("Latest updates %s", LocalDate.now()), GITLAB_URL); + for (Entry<String, String> entry : releaseNotes.entrySet()) { + embedBuilder.addField(entry.getKey(), entry.getValue(), false); + } + + channelDetailService.findAll().stream().findAny() + .ifPresent(detail -> jda.getTextChannelsByName(detail.getBotUpdateChannel(), false).forEach(f -> + f.sendMessageEmbeds(embedBuilder.build()).queue() + )); + } + } + + private static Map<String, String> getReleaseNotes() { + Map<String, String> releaseNotes = new LinkedHashMap<>(); + try { + InputStream in = Optional.ofNullable(ReleaseNotesUtil.class.getResourceAsStream("/releasenotes.csv")) + .orElseThrow(() -> new IOException("File releasenotes.csv not found!")); + Arrays.stream(new String(in.readAllBytes(), StandardCharsets.UTF_8).split("\n")).forEach(line -> { + if (!line.isEmpty()) + releaseNotes.put(line.split(";")[0], line.split(";")[1].trim()); + }); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); + } + return releaseNotes; + } +} diff --git a/src/main/java/com/wimdupont/sxcybot/util/SpringSecurityAuditorAware.java b/src/main/java/com/wimdupont/sxcybot/util/SpringSecurityAuditorAware.java @@ -0,0 +1,21 @@ +package com.wimdupont.sxcybot.util; + + +import org.springframework.data.domain.AuditorAware; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +@Component +public class SpringSecurityAuditorAware implements AuditorAware<String> { + + /** + * Returns the current auditor of the application. + * + * @return the current auditor + */ + @Override + public Optional<String> getCurrentAuditor() { + return Optional.empty(); + } +} diff --git a/src/main/resources/db/migration/V1_11__add_discordid_to_pvmrole_user.sql b/src/main/resources/db/migration/V1_11__add_discordid_to_pvmrole_user.sql @@ -0,0 +1 @@ +ALTER TABLE pvm_role_user ADD COLUMN IF NOT EXISTS discord_id VARCHAR(30); diff --git a/src/main/resources/releasenotes.csv b/src/main/resources/releasenotes.csv @@ -1,2 +1,2 @@ -Renamed sb-pvmcheck command to sb-pvmpoll;This command shows the current hiscores of the PvM Role competition through DM. -Added new sb-pvmcheck command;This command checks for competitors that cannot be found in the hiscores. +Discord names of PvM Competitors are now updated daily;Discord ID's are now saved alongside discord names for PvM competitors. These ID's are used to update the saved discord names to prevent issues in case of name changes. Names will probably be removed in the future to do all searches based on these ID's. +Improved sb-pvmlist readability;Removed the hidden texts containing auditing info to make it more readable. diff --git a/src/test/java/com/sxcy/sxcybot/SxcyBotApplicationTests.java b/src/test/java/com/sxcy/sxcybot/SxcyBotApplicationTests.java @@ -1,17 +0,0 @@ -package com.sxcy.sxcybot; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; - -@Disabled -@SpringBootTest -@ActiveProfiles("dev") -public class SxcyBotApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/src/test/java/com/sxcy/sxcybot/client/GrandExchangeClientTest.java b/src/test/java/com/sxcy/sxcybot/client/GrandExchangeClientTest.java @@ -1,49 +0,0 @@ -package com.sxcy.sxcybot.client; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.sxcy.sxcybot.exceptions.EntityNotFoundException; -import net.dv8tion.jda.api.entities.MessageChannel; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@ExtendWith(SpringExtension.class) -class GrandExchangeClientTest { - - private GrandExchangeClient grandExchangeClient; - - @MockBean - private MessageChannel messageChannel; - - @BeforeEach - void setup() { - grandExchangeClient = new GrandExchangeClient(new ObjectMapper()); - } - - @Test - void getPrice() throws EntityNotFoundException { - String itemName = "tinderbox"; - String result = grandExchangeClient.getPrice(itemName, messageChannel); - System.out.println(result); - - assertNotNull(result); - assertTrue(Integer.parseInt(result) > 0); - } - - @Test - void getPriceInvalidItem() { - String itemName = "invalidItem"; - EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> - grandExchangeClient.getPrice(itemName, messageChannel)); - - assertEquals(String.format("Item with name %s not found.", itemName), exception.getMessage()); - } - -} diff --git a/src/test/java/com/sxcy/sxcybot/client/HiScoreClientTest.java b/src/test/java/com/sxcy/sxcybot/client/HiScoreClientTest.java @@ -1,112 +0,0 @@ -package com.sxcy.sxcybot.client; - -import com.sxcy.sxcybot.model.OsrsBossKc; -import com.sxcy.sxcybot.model.OsrsStat; -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; -import com.sxcy.sxcybot.repository.osrs.dao.OsrsHiscoreStat; -import com.sxcy.sxcybot.services.osrs.OsrsHiscoreBossService; -import com.sxcy.sxcybot.services.osrs.OsrsHiscoreStatService; -import net.dv8tion.jda.api.entities.MessageChannel; -import net.dv8tion.jda.api.requests.restaction.MessageAction; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.BDDMockito.given; - -@ExtendWith(SpringExtension.class) -class HiScoreClientTest { - - @MockBean - private OsrsHiscoreBossService osrsHiscoreBossService; - @MockBean - private OsrsHiscoreStatService osrsHiscoreStatService; - @MockBean - private MessageChannel messageChannel; - @MockBean - private MessageAction messageAction; - - private HiScoreClient hiScoreClient; - - @BeforeEach - void setup() { - hiScoreClient = new HiScoreClient(osrsHiscoreBossService, osrsHiscoreStatService); - } - - @Test - void getHiScoreStatsValid() { - String playerName = "Zxxy"; - List<OsrsHiscoreStat> osrsHiscoreStats = List.of(OsrsHiscoreStat.Builder.newBuilder() - .name("Overall") - .orderValue(0) - .build(), - OsrsHiscoreStat.Builder.newBuilder() - .name("Construction") - .orderValue(23) - .build()); - given(osrsHiscoreStatService.findAll()).willReturn(osrsHiscoreStats); - - Optional<List<OsrsStat>> result = hiScoreClient.getHiScoreStats(playerName, messageChannel); - - assertFalse(result.isEmpty()); - assertEquals(2, result.get().size()); - - assertEquals("Overall", result.get().get(0).name()); - assertTrue(1939 <= Integer.parseInt(result.get().get(0).level())); - - assertEquals("Construction", result.get().get(1).name()); - assertTrue(90 <= Integer.parseInt(result.get().get(1).level())); - } - - @Test - void getHiscoreStatsNonExistingPlayer() { - String playerName = "007thisplayershouldneverexist007"; - given(messageChannel.sendMessage("No results found. ()")).willReturn(messageAction); - Optional<List<OsrsStat>> result = hiScoreClient.getHiScoreStats(playerName, messageChannel); - - assertTrue(result.isEmpty()); - } - - @Test - void getHiscoreBossKcValidKbdKc() { - String playerName = "Zxxy"; - List<OsrsHiscoreBoss> hiscoreBosses = List.of(OsrsHiscoreBoss.Builder.newBuilder() - .name("KBD") - .orderValue(60) - .build(), - OsrsHiscoreBoss.Builder.newBuilder() - .name("Wintertodt") - .orderValue(86) - .build() - ); - - given(osrsHiscoreBossService.findAll()).willReturn(hiscoreBosses); - Optional<List<OsrsBossKc>> result = hiScoreClient.getHiScoreBossKc(playerName, messageChannel); - - assertFalse(result.isEmpty()); - assertEquals(2, result.get().size()); - - assertEquals("KBD", result.get().get(0).name()); - assertTrue(723 <= Integer.parseInt(result.get().get(0).kc())); - - assertEquals("Wintertodt", result.get().get(1).name()); - assertTrue(87 <= Integer.parseInt(result.get().get(1).kc())); - } - - @Test - void getHiscoreBossKcNonExistingPlayer() { - String playerName = "007thisplayershouldneverexist007"; - given(messageChannel.sendMessage("No results found. ()")).willReturn(messageAction); - Optional<List<OsrsBossKc>> result = hiScoreClient.getHiScoreBossKc(playerName, messageChannel); - - assertTrue(result.isEmpty()); - } -} diff --git a/src/test/java/com/wimdupont/sxcybot/SxcyBotApplicationTests.java b/src/test/java/com/wimdupont/sxcybot/SxcyBotApplicationTests.java @@ -0,0 +1,17 @@ +package com.wimdupont.sxcybot; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +@Disabled +@SpringBootTest +@ActiveProfiles("dev") +public class SxcyBotApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/src/test/java/com/wimdupont/sxcybot/client/GrandExchangeClientTest.java b/src/test/java/com/wimdupont/sxcybot/client/GrandExchangeClientTest.java @@ -0,0 +1,49 @@ +package com.wimdupont.sxcybot.client; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.wimdupont.sxcybot.exceptions.EntityNotFoundException; +import net.dv8tion.jda.api.entities.MessageChannel; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(SpringExtension.class) +class GrandExchangeClientTest { + + private GrandExchangeClient grandExchangeClient; + + @MockBean + private MessageChannel messageChannel; + + @BeforeEach + void setup() { + grandExchangeClient = new GrandExchangeClient(new ObjectMapper()); + } + + @Test + void getPrice() throws EntityNotFoundException { + String itemName = "tinderbox"; + String result = grandExchangeClient.getPrice(itemName, messageChannel); + System.out.println(result); + + assertNotNull(result); + assertTrue(Integer.parseInt(result) > 0); + } + + @Test + void getPriceInvalidItem() { + String itemName = "invalidItem"; + EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> + grandExchangeClient.getPrice(itemName, messageChannel)); + + assertEquals(String.format("Item with name %s not found.", itemName), exception.getMessage()); + } + +} diff --git a/src/test/java/com/wimdupont/sxcybot/client/HiScoreClientTest.java b/src/test/java/com/wimdupont/sxcybot/client/HiScoreClientTest.java @@ -0,0 +1,112 @@ +package com.wimdupont.sxcybot.client; + +import com.wimdupont.sxcybot.model.OsrsBossKc; +import com.wimdupont.sxcybot.model.OsrsStat; +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreBoss; +import com.wimdupont.sxcybot.repository.osrs.dao.OsrsHiscoreStat; +import com.wimdupont.sxcybot.services.osrs.OsrsHiscoreBossService; +import com.wimdupont.sxcybot.services.osrs.OsrsHiscoreStatService; +import net.dv8tion.jda.api.entities.MessageChannel; +import net.dv8tion.jda.api.requests.restaction.MessageAction; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.BDDMockito.given; + +@ExtendWith(SpringExtension.class) +class HiScoreClientTest { + + @MockBean + private OsrsHiscoreBossService osrsHiscoreBossService; + @MockBean + private OsrsHiscoreStatService osrsHiscoreStatService; + @MockBean + private MessageChannel messageChannel; + @MockBean + private MessageAction messageAction; + + private HiScoreClient hiScoreClient; + + @BeforeEach + void setup() { + hiScoreClient = new HiScoreClient(osrsHiscoreBossService, osrsHiscoreStatService); + } + + @Test + void getHiScoreStatsValid() { + String playerName = "Zxxy"; + List<OsrsHiscoreStat> osrsHiscoreStats = List.of(OsrsHiscoreStat.Builder.newBuilder() + .name("Overall") + .orderValue(0) + .build(), + OsrsHiscoreStat.Builder.newBuilder() + .name("Construction") + .orderValue(23) + .build()); + given(osrsHiscoreStatService.findAll()).willReturn(osrsHiscoreStats); + + Optional<List<OsrsStat>> result = hiScoreClient.getHiScoreStats(playerName, messageChannel); + + assertFalse(result.isEmpty()); + assertEquals(2, result.get().size()); + + assertEquals("Overall", result.get().get(0).name()); + assertTrue(1939 <= Integer.parseInt(result.get().get(0).level())); + + assertEquals("Construction", result.get().get(1).name()); + assertTrue(90 <= Integer.parseInt(result.get().get(1).level())); + } + + @Test + void getHiscoreStatsNonExistingPlayer() { + String playerName = "007thisplayershouldneverexist007"; + given(messageChannel.sendMessage("No results found. ()")).willReturn(messageAction); + Optional<List<OsrsStat>> result = hiScoreClient.getHiScoreStats(playerName, messageChannel); + + assertTrue(result.isEmpty()); + } + + @Test + void getHiscoreBossKcValidKbdKc() { + String playerName = "Zxxy"; + List<OsrsHiscoreBoss> hiscoreBosses = List.of(OsrsHiscoreBoss.Builder.newBuilder() + .name("KBD") + .orderValue(60) + .build(), + OsrsHiscoreBoss.Builder.newBuilder() + .name("Wintertodt") + .orderValue(86) + .build() + ); + + given(osrsHiscoreBossService.findAll()).willReturn(hiscoreBosses); + Optional<List<OsrsBossKc>> result = hiScoreClient.getHiScoreBossKc(playerName, messageChannel); + + assertFalse(result.isEmpty()); + assertEquals(2, result.get().size()); + + assertEquals("KBD", result.get().get(0).name()); + assertTrue(723 <= Integer.parseInt(result.get().get(0).kc())); + + assertEquals("Wintertodt", result.get().get(1).name()); + assertTrue(87 <= Integer.parseInt(result.get().get(1).kc())); + } + + @Test + void getHiscoreBossKcNonExistingPlayer() { + String playerName = "007thisplayershouldneverexist007"; + given(messageChannel.sendMessage("No results found. ()")).willReturn(messageAction); + Optional<List<OsrsBossKc>> result = hiScoreClient.getHiScoreBossKc(playerName, messageChannel); + + assertTrue(result.isEmpty()); + } +}