Skip to content

Commit

Permalink
feat: compact discord webhooks (#2007)
Browse files Browse the repository at this point in the history
![CleanShot 2023-12-09 at 18 39
06@2x](https://github.com/opentibiabr/canary/assets/223760/218eba3b-beca-4454-9880-20641c0c3b79)

---------

Co-authored-by: Elson Costa <[email protected]>
Co-authored-by: GitHub Actions <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Dec 31, 2023
1 parent a082e9d commit 1f5b87c
Show file tree
Hide file tree
Showing 26 changed files with 106 additions and 59 deletions.
1 change: 1 addition & 0 deletions config.lua.dist
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ location = "South America"
-- The URL layout is https://discord.com/api/webhooks/:id/:token
-- Leave empty if you wish to disable.
discordWebhookURL = ""
discordSendFooter = true

-- Vip System (Get more info in: https://github.com/opentibiabr/canary/pull/1063)
-- NOTE: set vipSystemEnabled to true to enable the vip system functionalities (this overrides premium checks)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,7 @@ function playerDeath.onDeath(player, corpse, killer, mostDamageKiller, unjustifi
)
local resultId = db.storeQuery("SELECT `player_id` FROM `player_deaths` WHERE `player_id` = " .. playerGuid)
-- Start Webhook Player Death
local playerName = player:getName()
local playerLevel = player:getLevel()
local killerLink = string.gsub(killerName, "%s+", "+")
local playerLink = string.gsub(playerName, "%s+", "+")
local serverURL = getConfigInfo("url")
if killer and killer:isPlayer() then
Webhook.sendMessage(playerName .. " just got killed!", "**[" .. playerName .. "](" .. serverURL .. "/?characters/" .. playerLink .. ")** got killed at level " .. playerLevel .. " by **[" .. killerName .. "](" .. serverURL .. "/?characters/" .. killerLink .. ")**", WEBHOOK_COLOR_OFFLINE, announcementChannels["player-kills"])
else
Webhook.sendMessage(playerName .. " has just died!", "**[" .. playerName .. "](" .. serverURL .. "/?characters/" .. playerLink .. ")** died at level " .. playerLevel .. " by " .. killerName, WEBHOOK_COLOR_WARNING, announcementChannels["player-kills"])
end
Webhook.sendMessage(":skull_crossbones: " .. player:getMarkdownLink() .. " has died. Killed at level _" .. player:getLevel() .. "_ by **" .. killerName .. "**.", announcementChannels["player-kills"])
-- End Webhook Player Death

local deathRecords = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ local function ServerSaveWarning(time)
local remainingTime = tonumber(time) - 60000
if configManager.getBoolean(configKeys.GLOBAL_SERVER_SAVE_NOTIFY_MESSAGE) then
local message = "Server is saving game in " .. (remainingTime / 60000) .. " minute(s). Please logout."
Webhook.sendMessage("Server save", message, WEBHOOK_COLOR_WARNING)
Webhook.sendMessage(":floppy_disk: " .. message, announcementChannels["serverAnnouncements"])
Game.broadcastMessage(message, MESSAGE_GAME_HIGHLIGHT)
end
-- if greater than one minute, schedule another warning
Expand All @@ -36,7 +36,7 @@ function serverSaveEvent.onTime(interval)
local remainingTime = configManager.getNumber(configKeys.GLOBAL_SERVER_SAVE_NOTIFY_DURATION) * 60000
if configManager.getBoolean(configKeys.GLOBAL_SERVER_SAVE_NOTIFY_MESSAGE) then
local message = "Server is saving game in " .. (remainingTime / 60000) .. " minute(s). Please logout."
Webhook.sendMessage("Server save", message, WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage(":floppy_disk: " .. message, announcementChannels["serverAnnouncements"])
Game.broadcastMessage(message, MESSAGE_GAME_HIGHLIGHT)
end
addEvent(ServerSaveWarning, 60000, remainingTime) -- Schedule next event in 1 minute(60000)
Expand Down
2 changes: 1 addition & 1 deletion data-otservbr-global/scripts/globalevents/spawn/rashid.lua
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ local positionByDay = {
}

local function rashidwebhook(message) -- New local function that runs on delay to send webhook message.
Webhook.sendMessage("[Rashid] ", message, WEBHOOK_COLOR_ONLINE) --Sends webhook message
Webhook.sendMessage(":man_wearing_turban: " .. message, announcementChannels["serverAnnouncements"])
end

local rashid = GlobalEvent("rashid")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ local gates = {
}

local function Furywebhook(message) -- New local function that runs on delay to send webhook message.
Webhook.sendMessage("[Fury Gates] ", message, WEBHOOK_COLOR_ONLINE) --Sends webhook message
Webhook.sendMessage(":fire: " .. message, announcementChannels["serverAnnouncements"])
end

-- FURY GATES MAP LOAD
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ local config = {
}

local function Nightmarewebhook(message) -- New local function that runs on delay to send webhook message.
Webhook.sendMessage("[Nightmare Isle] ", message, WEBHOOK_COLOR_ONLINE) --Sends webhook message
Webhook.sendMessage(":thought_balloon: " .. message, announcementChannels["serverAnnouncements"])
end

local NightmareIsle = GlobalEvent("NightmareIsle")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ local config = {
}

local function yasirwebhook(message) -- New local function that runs on delay to send webhook message.
Webhook.sendMessage("[Yasir] ", message, WEBHOOK_COLOR_ONLINE) --Sends webhook message
Webhook.sendMessage(":man_wearing_turban_tone4: " .. message, announcementChannels["serverAnnouncements"])
end

local yasirEnabled = true
Expand Down
21 changes: 21 additions & 0 deletions data/events/scripts/player.lua
Original file line number Diff line number Diff line change
Expand Up @@ -662,3 +662,24 @@ function Player:onChangeZone(zone)
end

function Player:onInventoryUpdate(item, slot, equip) end

function Player:getURL()
local playerLink = string.gsub(self:getName(), "%s+", "+")
local serverURL = configManager.getString(configKeys.URL)
return serverURL .. "/characters/" .. playerLink
end

function Player:getMarkdownLink()
local vocation = self:vocationAbbrev()
local emoji = ":school_satchel:"
if self:isKnight() then
emoji = ":crossed_swords:"
elseif self:isPaladin() then
emoji = ":bow_and_arrow:"
elseif self:isDruid() then
emoji = ":herb:"
elseif self:isSorcerer() then
emoji = ":crystal_ball:"
end
return "**[" .. self:getName() .. "](" .. self:getURL() .. ")** " .. emoji .. " [_" .. vocation .. "_]"
end
2 changes: 1 addition & 1 deletion data/scripts/discord_webhook/discord_webhook.lua
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ announcementChannels = {
local message = blablabla
local title = test
Webhook.sendMessage(title, message, WEBHOOK_COLOR_WARNING,
Webhook.sendMessage(title, message, WEBHOOK_COLOR_YELLOW,
announcementChannels["serverAnnouncements"])
Dev Comment: This lib can be used to add special webhook channels
Expand Down
2 changes: 1 addition & 1 deletion data/scripts/talkactions/gm/ban.lua
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function ban.onSay(player, words, param)
if target then
local text = target:getName() .. " has been banned"
player:sendTextMessage(MESSAGE_ADMINISTRADOR, text)
Webhook.sendMessage("Player Banned", text .. " reason: " .. reason .. ". (by: " .. player:getName() .. ")", WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage("Player Banned", text .. " reason: " .. reason .. ". (by: " .. player:getName() .. ")", WEBHOOK_COLOR_YELLOW, announcementChannels["serverAnnouncements"])
target:remove()
else
player:sendTextMessage(MESSAGE_ADMINISTRADOR, name .. " has been banned.")
Expand Down
2 changes: 1 addition & 1 deletion data/scripts/talkactions/gm/kick.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function kick.onSay(player, words, param)
return true
end

Webhook.sendMessage("Player Kicked", target:getName() .. " has been kicked by " .. player:getName(), WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage("Player Kicked", target:getName() .. " has been kicked by " .. player:getName(), WEBHOOK_COLOR_YELLOW, announcementChannels["serverAnnouncements"])
target:remove()
return true
end
Expand Down
2 changes: 1 addition & 1 deletion data/scripts/talkactions/gm/push_town.lua
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function pushTown.onSay(player, words, param)
targetPlayer:getPosition():sendMagicEffect(CONST_ME_HOLYAREA)
local text = "Player " .. targetPlayer:getName() .. " has been teleported to temple by " .. player:getName() .. "."
logger.info("[pushTown.onSay] - {}", text)
Webhook.sendMessage("Player Teleported", text, WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage("Player Teleported", text, WEBHOOK_COLOR_YELLOW, announcementChannels["serverAnnouncements"])
end
return true
end
Expand Down
2 changes: 1 addition & 1 deletion data/scripts/talkactions/gm/unban.lua
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function unban.onSay(player, words, param)
Result.free(resultId)
local text = param .. " has been unbanned."
player:sendTextMessage(MESSAGE_ADMINISTRADOR, text)
Webhook.sendMessage("Player Unbanned", text .. " (by: " .. player:getName() .. ")", WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage("Player Unbanned", text .. " (by: " .. player:getName() .. ")", WEBHOOK_COLOR_YELLOW, announcementChannels["serverAnnouncements"])
return true
end

Expand Down
6 changes: 2 additions & 4 deletions data/scripts/talkactions/god/close_server.lua
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function closeServer.onSay(player, words, param)

if param == "shutdown" then
Game.setGameState(GAME_STATE_SHUTDOWN)
Webhook.sendMessage("Server Shutdown", "Server was shutdown by: " .. player:getName(), WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage(":red_circle: Server was shutdown by: **" .. player:getName() .. "**", announcementChannels["serverAnnouncements"])
elseif param == "save" then
if configManager.getBoolean(configKeys.GLOBAL_SERVER_SAVE_CLEAN_MAP) then
cleanMap()
Expand All @@ -17,15 +17,13 @@ function closeServer.onSay(player, words, param)
if configManager.getBoolean(configKeys.GLOBAL_SERVER_SAVE_SHUTDOWN) then
Game.setGameState(GAME_STATE_SHUTDOWN, true)
end
-- Updating daily reward next server save.
UpdateDailyRewardGlobalStorage(DailyReward.storages.lastServerSave, os.time())
elseif param == "maintainance" then
Game.setGameState(GAME_STATE_MAINTAIN)
player:sendTextMessage(MESSAGE_ADMINISTRADOR, "Server is set to maintenance mode.")
else
Game.setGameState(GAME_STATE_CLOSED)
player:sendTextMessage(MESSAGE_ADMINISTRADOR, "Server is now closed.")
Webhook.sendMessage("Server Closed", "Server was closed by: " .. player:getName(), WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage(":yellow_square: Server was closed by: **" .. player:getName() .. "**", announcementChannels["serverAnnouncements"])
end
return true
end
Expand Down
2 changes: 1 addition & 1 deletion data/scripts/talkactions/god/open_server.lua
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function openServer.onSay(player, words, param)

Game.setGameState(GAME_STATE_NORMAL)
player:sendTextMessage(MESSAGE_ADMINISTRADOR, "Server is now open.")
Webhook.sendMessage("Server Open", "Server was opened by: " .. player:getName(), WEBHOOK_COLOR_WARNING, announcementChannels["serverAnnouncements"])
Webhook.sendMessage(":green_circle: Server was opened by: **" .. player:getName() .. "**", announcementChannels["serverAnnouncements"])
return true
end

Expand Down
4 changes: 2 additions & 2 deletions src/canary_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ int CanaryServer::run() {
if (g_configManager().getBoolean(TOGGLE_MAINTAIN_MODE, __FUNCTION__)) {
g_game().setGameState(GAME_STATE_CLOSED);
g_logger().warn("Initialized in maintain mode!");
g_webhook().sendMessage("Server is now online", "The server is now online. Access is currently restricted to administrators only.", WEBHOOK_COLOR_ONLINE);
g_webhook().sendMessage(":yellow_square: Server is now **online** _(access restricted to staff)_");
} else {
g_game().setGameState(GAME_STATE_NORMAL);
g_webhook().sendMessage("Server is now online", "Server has successfully started.", WEBHOOK_COLOR_ONLINE);
g_webhook().sendMessage(":green_circle: Server is now **online**");
}

loaderStatus = LoaderStatus::LOADED;
Expand Down
1 change: 1 addition & 0 deletions src/config/config_definitions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ enum ConfigKey_t : uint16_t {
DEPOT_BOXES,
DISABLE_LEGACY_RAIDS,
DISABLE_MONSTER_ARMOR,
DISCORD_SEND_FOOTER,
DISCORD_WEBHOOK_DELAY_MS,
DISCORD_WEBHOOK_URL,
EMOTE_SPELLS,
Expand Down
1 change: 1 addition & 0 deletions src/config/configmanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ bool ConfigManager::load() {
loadStringConfig(L, WORLD_TYPE, "worldType", "pvp");
loadStringConfig(L, STORE_IMAGES_URL, "coinImagesURL", "");
loadStringConfig(L, DISCORD_WEBHOOK_URL, "discordWebhookURL", "");
loadBoolConfig(L, DISCORD_SEND_FOOTER, "discordSendFooter", true);
loadStringConfig(L, SAVE_INTERVAL_TYPE, "saveIntervalType", "");
loadStringConfig(L, GLOBAL_SERVER_SAVE_TIME, "globalServerSaveTime", "06:00");
loadStringConfig(L, DATA_DIRECTORY, "dataPackDirectory", "data-otservbr-global");
Expand Down
2 changes: 1 addition & 1 deletion src/creatures/players/player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2112,8 +2112,8 @@ void Player::onThink(uint32_t interval) {
triggerMomentum();
auto playerTile = getTile();
const bool vipStaysOnline = isVip() && g_configManager().getBoolean(VIP_STAY_ONLINE, __FUNCTION__);
idleTime += interval;
if (playerTile && !playerTile->hasFlag(TILESTATE_NOLOGOUT) && !isAccessPlayer() && !isExerciseTraining() && !vipStaysOnline) {
idleTime += interval;
const int32_t kickAfterMinutes = g_configManager().getNumber(KICK_AFTER_MINUTES, __FUNCTION__);
if (idleTime > (kickAfterMinutes * 60000) + 60000) {
removePlayer(true);
Expand Down
13 changes: 10 additions & 3 deletions src/game/game.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7590,7 +7590,7 @@ void Game::dieSafely(std::string errorMsg /* = "" */) {
}

void Game::shutdown() {
g_webhook().sendMessage("Server is shutting down", "Shutting down...", WEBHOOK_COLOR_OFFLINE);
g_webhook().sendMessage(":red_circle: Server is shutting down...");

g_logger().info("Shutting down...");
map.spawnsMonster.clear();
Expand Down Expand Up @@ -9182,6 +9182,11 @@ void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, con
return;
}

if (player->isUIExhausted()) {
player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED);
return;
}

if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) {
player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE);
return;
Expand All @@ -9195,8 +9200,8 @@ void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, con

const auto mType = g_monsters().getMonsterTypeByRaceId(static_cast<uint16_t>(monsterRaceId), itemId == ITEM_PODIUM_OF_VIGOUR);
if (!mType) {
player->sendCancelMessage(RETURNVALUE_CONTACTADMINISTRATOR);
g_logger().error("[{}] player {} is trying to add invalid monster to podium {}", __FUNCTION__, player->getName(), item->getName());
player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE);
g_logger().debug("[{}] player {} is trying to add invalid monster to podium {}", __FUNCTION__, player->getName(), item->getName());
return;
}

Expand Down Expand Up @@ -9242,6 +9247,8 @@ void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, con
for (const auto &spectator : Spectators().find<Player>(pos, true)) {
spectator->getPlayer()->sendUpdateTileItem(tile, pos, item);
}

player->updateUIExhausted();
}

void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) {
Expand Down
8 changes: 4 additions & 4 deletions src/game/game_definitions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ enum HighscoreType_t : uint8_t {
};

enum Webhook_Colors_t : uint32_t {
WEBHOOK_COLOR_ONLINE = 0x00FF00,
WEBHOOK_COLOR_OFFLINE = 0xFF0000,
WEBHOOK_COLOR_WARNING = 0xFFFF00,
WEBHOOK_COLOR_RAID = 0x0000FF
WEBHOOK_COLOR_GREEN = 0x00FF00,
WEBHOOK_COLOR_RED = 0xFF0000,
WEBHOOK_COLOR_YELLOW = 0xFFFF00,
WEBHOOK_COLOR_BLUE = 0x0000FF
};

// Structs
Expand Down
2 changes: 1 addition & 1 deletion src/lua/creature/raids.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ bool AnnounceEvent::configureRaidEvent(const pugi::xml_node &eventNode) {

bool AnnounceEvent::executeEvent() {
g_game().broadcastMessage(message, messageType);
g_webhook().sendMessage("Incoming raid!", message, WEBHOOK_COLOR_RAID);
g_webhook().sendMessage(fmt::format(":space_invader: {}", message));
return true;
}

Expand Down
8 changes: 4 additions & 4 deletions src/lua/functions/core/game/lua_enums.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1239,10 +1239,10 @@ void LuaEnums::initForgeEnums(lua_State* L) {

// Webhook default colors
void LuaEnums::initWebhookEnums(lua_State* L) {
registerEnum(L, WEBHOOK_COLOR_ONLINE);
registerEnum(L, WEBHOOK_COLOR_OFFLINE);
registerEnum(L, WEBHOOK_COLOR_WARNING);
registerEnum(L, WEBHOOK_COLOR_RAID);
registerEnum(L, WEBHOOK_COLOR_GREEN);
registerEnum(L, WEBHOOK_COLOR_RED);
registerEnum(L, WEBHOOK_COLOR_YELLOW);
registerEnum(L, WEBHOOK_COLOR_BLUE);
}

void LuaEnums::initBosstiaryEnums(lua_State* L) {
Expand Down
14 changes: 10 additions & 4 deletions src/lua/functions/core/network/webhook_functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,19 @@
#include "server/network/webhook/webhook.hpp"

int WebhookFunctions::luaWebhookSendMessage(lua_State* L) {
// Webhook.sendMessage(title, message, color, url = "WEBHOOK_DISCORD_URL")
// Webhook.sendMessage(title, message, color, url = "WEBHOOK_DISCORD_URL") |
// Webhook.sendMessage(message, url = "WEBHOOK_DISCORD_URL")
std::string title = getString(L, 1);
std::string message = getString(L, 2);
uint32_t color = getNumber<uint32_t>(L, 3, 0);
std::string url = getString(L, 4);

g_webhook().sendMessage(title, message, color, url);
std::string url = getString(L, -1);
if (url == title) {
g_webhook().sendMessage(title);
} else if (url == message) {
g_webhook().sendMessage(title, url);
} else {
g_webhook().sendMessage(title, message, color, url);
}
lua_pushnil(L);

return 1;
Expand Down
Loading

0 comments on commit 1f5b87c

Please sign in to comment.