diff --git a/src/modules/PlayerbotV2/BOT_BRIDGE.md b/src/modules/PlayerbotV2/BOT_BRIDGE.md index ab8c5c1d31..b5021d14e1 100644 --- a/src/modules/PlayerbotV2/BOT_BRIDGE.md +++ b/src/modules/PlayerbotV2/BOT_BRIDGE.md @@ -40,6 +40,7 @@ Every bot event has: `id`, `t` (UTC time), `type`, `bot`, `guid`, `class`, `race | `chat_in` | a player whispers a bot, talks in its party or raid, or says something to it in /say (the same lines `Playerbot.ChatModel` answers, with its switches and limits) | `channel`, `from`, `from_is_bot`, `locale` (his game client's language, `ruRU`, `enUS`...: answer a Russian client in Russian when his line shows no language of its own), `doing` (what the bot is busy with right now, in words: "doing a quest", "fighting Defias Thug", "on the way to a vendor to sell junk", "following you"; left out when the bot logic says nothing a player would tell), `group_order` and `group` (1 and the other bots' names: a party or raid order the bot commands don't know, "all go to the bank and wait"; every bot named takes the action this answer picks, when it is one a group can take: moving, stopping, fighting, emotes, orders, signing a charter), `text`, `prompt` (a description of the bot and how to answer, the one the built-in chat model uses), `weather` (the zone's: clear, rain, snow, ...), `time_of_day` (morning, afternoon, evening, night), `swearing` (1 when the realm allows everyday bad language, `Playerbot.Bridge.Swearing`), `social` (from a player: the bot's guild and his, the guild charter he carries with its signatures and whether this bot signed it or can, and what the bot would do with his group invite, in words) | | `moment` | a bot grouped with a real player would say a line on its own in party (it looted something, gained a level, the group wiped or killed a boss, came to a new zone, a ready check, it died or was brought back, it joined the group). Only while a program answers chat and `Moments` is on; the bots' usual chance and cooldowns (`Playerbot.Chatter.*`, `PartyBanter`) decide when, at most `MomentsPerMinute` (6) for the server. Answer it like a `chat_in` (`reply_to` = its `id`; it goes to party; an empty `say` means the bot says nothing). Without a program, or past the limit, the bot says its fixed line as before | `what` (`loot`, `quest`, `kill`, `player_kill`, `level_up`, `greet`, `ready_check`, `wipe`, `rezzed`, `died`, `boss_kill`, `new_zone`, and `need` / `offer`: an owned bot near its owner whose bags are full or gear nearly broken says so, and one that carries an upgrade or a quest item for him offers it, at most one per owner every 5 minutes), `detail` (what happened, in plain words), `example` (the fixed line the bot would have said, an idea; missing for `new_zone`), `to` (the player it is said to: the bot's owner when he is in the group), `to_is_owner`, `can` (with actions on, checked for `to`), `weather`, `time_of_day`, `swearing` | | `talk` | world bots chat with each other in /say (the gatherings outside the city gates and the street chats inside the capitals, `Playerbot.World.Gathering.*`): the bot's next line. Only while a program answers chat and `Talk` is on, at most `Gathering.ChatModelPerMinute` (4) a minute, and not while two players' lines wait for an answer. Answer it like a `chat_in` (`reply_to` = its `id`, `say` the line); the next bot's `talk` carries it. No answer within 25 s ends that talk | `channel` (say), `scene` (who the bot is, where, with whom, what about), `talk` (the lines so far, `Name: line` each; empty: start the talk), `weather`, `time_of_day`, `swearing`. With `channel` `general` or `trade` it is a world bot's post there (WTS, WTB, LFM, a question; at most `MomentsPerMinute` a minute, the bots' usual suggestion cooldowns decide when) or another bot's answer to one (two posts in five, at most 2 a minute): answer with that `channel`. An item's or quest's name in a post becomes its link; a post that leaves the name out is the bot's fixed line instead. A player who then whispers the bot gets `your_post` in his `chat_in` (its post of the last 15 minutes). A `talk` whose scene says a player walks past is a bot that just waved at him: one short /say line to him, or an empty `say`. `locale`: the language most real players on that map play in (else the realm's): write the line in it | +| `raid_line` | the raid leader bot reacts to a mistake in a raid with a real player (stood in the bad stuff, a cast nobody kicked, a broken crowd control, an extra pull, the wipe, the kill), or another bot answers after a wipe (`Playerbot.Raid.Banter`, see BOT_COMMANDS.md). Only while a program answers chat, and not while two players' lines wait. Answer it like a `chat_in` (`reply_to` = its `id`, `say` one short line, empty = the fixed line). **It has a deadline**: an answer that comes later than `wait_ms` after the event is dropped and the bot says `example` instead, so answer fast (a small model, a few words) | `what` (`stood_in_bad`, `missed_kick`, `broke_cc`, `extra_pull`, `wipe`, `boss_down`), `detail` (what happened, in plain words), `example` (the fixed line), `mood` (`mild` teasing or `harsh` freak-out, in good fun: game mistakes only, never about the person, never a slur), `role` (`raid leader` or `raider`), `channel` (`raid` or `party`), `locale` (the group's players' language: write the line in it), `delay_ms`, `wait_ms`, `swearing` | | `stuck` | a bot tried to reach a place for over 30 s without moving and dropped the goal | `detail` | | `quest_fail` | a bot dropped a quest that it can never finish or turn in | `detail` | | `spell_fail` | the server refused the same spell `SpellFailCount` times in a minute | `spell_id`, `spell`, `reason` (a server cast-result number; 1000 and up are the bot's own checks) | @@ -71,7 +72,7 @@ Files are written on their own thread. If the disk can't keep up, the oldest lin ``` - `reply_to` answers one `chat_in`. The answer goes on the same channel (a whisper goes back to the sender) unless `channel` says otherwise. - There's one answer per event, and an answer older than `ReplyMaxAgeSec` (60) isn't said. + There's one answer per event, and an answer older than `ReplyMaxAgeSec` (60) isn't said (a `raid_line` answer: older than its `wait_ms`). - Without `reply_to`, the line is one the bot says on its own. `bot` must be a bot's name (never a real player). `channel` can be `say` (the default), `yell`, `party`, `raid`, or `whisper` with `to`. A bot says at most one of these every `BotLineGapMs` (8 s). - `delay_ms` (optional, 0 to 10000) is how long the bot waits before the text shows: the time a person needs to type it. Send the diff --git a/src/modules/PlayerbotV2/BOT_COMMANDS.md b/src/modules/PlayerbotV2/BOT_COMMANDS.md index bc866013e2..78b0ea4fd2 100644 --- a/src/modules/PlayerbotV2/BOT_COMMANDS.md +++ b/src/modules/PlayerbotV2/BOT_COMMANDS.md @@ -332,6 +332,15 @@ World bots are ambient characters with no owner (`Playerbot.World.Enable = 1` sp walks past; it only invites other bots. A player invites the bot himself (or whispers `invite` to it). 1 = the old way (invites players within 30 yards). - Companion banter (`PartyBanter`): a short lowercase line now and then on ready check, wipe, rez, death, boss kill; never in a group over 15 or with `Playerbot.Chatter.Enabled = 0`. +- **Raid leader banter** (`Playerbot.Raid.Banter`: 0 off, 1 mild (default), 2 harsh): in a group with a real player, one bot + leads the raid's chat (the group leader if that is a bot, else an assistant bot, else the first bot) and reacts to mistakes: + standing in fire or another bad area, a cast nobody kicked, a broken crowd control (named when the server saw who hit it), an + extra pull. After a wipe one or two other bots answer (blame, excuses, "my bad"), and the kill gets a "gg". Mild teases, harsh + is a leader who freaks out at every mishap. Game mistakes only, never about the person, never a slur. Rate limited (one line + every 20 s, 10 s on harsh; the same mistake once in 45 s; the same raider once in 90 s). In a party of 15 or fewer with + `PartyBanter` on, the wipe and kill lines are the companions' own. No model needed; with the bot bridge answering chat, the + program may say it in the bot's own words, and a line not back within 2.5 s is the fixed line instead. Russian clients get + Russian. - Hostile-faction world bots can be placed near you (`Playerbot.World.FriendlyPct` and the per-zone `*FriendlyPct` keys, all 100 = none by default); lower them to get them (they fight on a PvP realm). @@ -365,6 +374,8 @@ Defaults are those of `conf/playerbot.conf.dist`. Behaviour switches are read wh | `Playerbot.Pve.Coordinator.Enable` | 1 | | `Playerbot.Raid.Enable` | 1 | | `Playerbot.Raid.BossWarnings` | 1 | +| `Playerbot.Raid.Callouts` | 1 | +| `Playerbot.Raid.Banter` | 1 (0 off, 1 mild, 2 harsh) | | `Playerbot.Behavior.DungeonFlow` / `DungeonAutopilot` / `DungeonLoot` | 1 / 1 / 1 | | `Playerbot.Behavior.PullRecover` / `WipeReleaseWait` / `ReadyCheckInfo` | 1 / 1 / 1 | | `Playerbot.TankThreatMultiplier` | 3.0 | diff --git a/src/modules/PlayerbotV2/Bot/BotBridge.cpp b/src/modules/PlayerbotV2/Bot/BotBridge.cpp index 2218769fce..e5fa2307f3 100644 --- a/src/modules/PlayerbotV2/Bot/BotBridge.cpp +++ b/src/modules/PlayerbotV2/Bot/BotBridge.cpp @@ -131,7 +131,10 @@ uint32 g_bad_lines = 0; uint32 g_last_bad_warn_ms = 0; struct ChatAsk { BotId bot = 0; std::string sender; ObjectGuid sender_guid; bool sender_is_bot = false; std::string channel; uint32 asked_ms = 0; uint64 talk_key = 0; // a bot-to-bot talk line (AskTalk), kept for TakeTalk - std::vector group; }; // a group order (AskGroupOrder): the other bots that take the answer's action too + std::vector group; // a group order (AskGroupOrder): the other bots that take the answer's action too + uint32 deadline_ms = 0; }; // a raid line (AskRaidLine): an answer at or after this time is dropped (the fixed line was said) +// Raid lines the program answered in time (AskRaidLine / RaidLineAnswered), by event id. +std::unordered_set g_raid_answered; // The group's part of a group order: each other bot runs the answer's action a moment after the first (HandleGroupFollowups). struct GroupFollowup { BotId bot = 0; ChatAsk ask; Reply reply; uint32 read_ms = 0, due_ms = 0; }; std::vector g_group_followups; @@ -1786,6 +1789,13 @@ void HandleReplies(ConfigReader::BridgeConfig const& cfg, uint32 now_ms) continue; } ask = it->second; + if (ask.deadline_ms && int32(now_ms - ask.deadline_ms) >= 0) + { + // A raid line that came too late: the caller said its fixed line at the deadline. + TC_LOG_INFO("playerbot.v2", "[bridge] raid line {} came {} ms late, dropped", r.reply_to, now_ms - ask.deadline_ms); + g_chat.erase(it); + continue; + } bot = ask.bot; if (Player* p = FindBot(bot)) bot_name = p->GetName(); @@ -1841,6 +1851,12 @@ void HandleReplies(ConfigReader::BridgeConfig const& cfg, uint32 now_ms) to = ask.sender; } } + if (!text.empty() && ask.deadline_ms) + { + if (g_raid_answered.size() > 512) + g_raid_answered.clear(); + g_raid_answered.insert(r.reply_to); + } if (!text.empty()) { g_last_line_ms[bot] = now_ms; @@ -2539,6 +2555,60 @@ bool BotBridge::AskTalk(Player* bot, std::string const& scene, std::string const return true; } +uint64 BotBridge::AskRaidLine(Player* bot, std::string const& what, std::string const& detail, std::string const& example, + std::string const& mood, std::string const& role, uint32 delay_ms, uint32 wait_ms) +{ + if (!ChatOn() || !bot || !bot->GetGroup()) + return 0; + uint32 const now_ms = GameTime::GetGameTimeMS(); + // Players come first: while two of their lines wait for an answer, the fixed line is said. + std::size_t waiting = 0; + for (auto const& kv : g_chat) + if (!kv.second.talk_key && !kv.second.deadline_ms && !kv.second.sender_is_bot && !kv.second.sender.empty() && + now_ms - kv.second.asked_ms < 20000) + ++waiting; + if (waiting >= 2) + return 0; + Group const* group = bot->GetGroup(); + std::string const channel = group->isRaidGroup() ? "raid" : "party"; + // The language most of the group's real players read (one line goes to all of them). + std::array count{}; + for (GroupReference const& ref : group->GetMembers()) + if (Player const* m = ref.GetSource(); m && m->GetSession() && !Services::Registry().has(m->GetGUID().GetCounter())) + if (LocaleConstant const l = m->GetSession()->GetSessionDbcLocale(); l < TOTAL_LOCALES) + ++count[l]; + std::size_t best = 0; + for (std::size_t l = 0; l < count.size(); ++l) + if (count[l] > count[best]) + best = l; + Event e; + e.type = "raid_line"; + FillBot(e, bot, 0); + e.fields.emplace_back("what", what); + e.fields.emplace_back("detail", detail); + e.fields.emplace_back("example", example); + e.fields.emplace_back("mood", mood); + e.fields.emplace_back("role", role); + e.fields.emplace_back("channel", channel); + e.fields.emplace_back("locale", best < TOTAL_LOCALES ? localeNames[best] : "enUS"); + e.numbers.emplace_back("delay_ms", delay_ms); + e.numbers.emplace_back("wait_ms", wait_ms); + if (Services::Config().bridge().swearing) + e.numbers.emplace_back("swearing", 1); + Write(e); + if (g_chat.size() > 2048) + g_chat.clear(); + ChatAsk ask{ bot->GetGUID().GetCounter(), std::string(), ObjectGuid::Empty, true, channel, now_ms }; + ask.deadline_ms = now_ms + wait_ms; + g_chat[e.id] = std::move(ask); + return e.id; +} + +bool BotBridge::RaidLineAnswered(uint64 id) +{ + return id && g_raid_answered.erase(id) > 0; +} + bool BotBridge::QueueGreet(BotId bot, ObjectGuid player) { if (!bot || player.IsEmpty() || !g_talk_on.load(std::memory_order_relaxed)) diff --git a/src/modules/PlayerbotV2/Bot/BotBridge.h b/src/modules/PlayerbotV2/Bot/BotBridge.h index a4d370417a..7ec257ae96 100644 --- a/src/modules/PlayerbotV2/Bot/BotBridge.h +++ b/src/modules/PlayerbotV2/Bot/BotBridge.h @@ -75,6 +75,15 @@ public: // add a short /say line to him (a greeting, a word about his mount). Counted with the talk (Gathering.ChatModelPerMinute). static bool QueueGreet(BotId bot, ObjectGuid player); + // World thread (Raid/RaidBanter.h). With a program answering chat, asks it for `bot`'s raid chat line about something that just + // happened in the fight: `what` a word (wipe, stood_in_bad ...), `detail` in plain words, `example` the fixed line, `mood` mild or + // harsh, `role` "raid leader" or "raider", `delay_ms` when the line should show. A line that comes back later than wait_ms after + // the ask is dropped, so the caller can say `example` itself at that time when RaidLineAnswered(id) is still false. 0: not asked. + static uint64 AskRaidLine(Player* bot, std::string const& what, std::string const& detail, std::string const& example, + std::string const& mood, std::string const& role, uint32 delay_ms, uint32 wait_ms); + // True once when the program answered ask `id` in time (the answer is forgotten then). + static bool RaidLineAnswered(uint64 id); + // Any thread (the bot worker's channel suggestions, BotTextMgr Suggest). With Talk on, a world bot's post in General (channel 1) // or Trade (2) is written by the program from `detail` (what it is about, in words); `link_name` / `link`: an item or quest whose // name in the line becomes its link; `example` the fixed line, said when the model leaves the name out. Now and then another diff --git a/src/modules/PlayerbotV2/Bot/Raid/README.md b/src/modules/PlayerbotV2/Bot/Raid/README.md index 22e275b565..8ce3ce6ae8 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/README.md +++ b/src/modules/PlayerbotV2/Bot/Raid/README.md @@ -27,6 +27,10 @@ Port of Karrz's raid10-revamp ike3 raid logic (Karrz1/wow-1.12, src/game/PlayerB - `RaidCallouts.h`: bots say their new decision in raid chat like players ("Living Bomb on me, running out", "taunting Flamegor", "Polymorph on X, don't break it", "spread out"), from the change-only decision log at the end of `Brain::Update`. No model; rate limited per bot and per raid; Russian readers get the catalog lines. `Playerbot.Raid.Callouts` (default 1). +- `RaidBanter.h`: a raid leader bot who reacts to mistakes (stood in the bad stuff, missed kick, broken cc, extra pull) and bots + that blame and excuse themselves after a wipe; `SpotMishaps` / `TrackPull` / `EndQuietPulls` in RaidBrain.cpp find them. + Fixed lines with a mild and a harsh set, rate limited by `BanterGate`; with the bridge on, a `raid_line` event asks the program + first and the fixed line is said when its answer is not back in `kModelWaitMs` (2.5 s). `Playerbot.Raid.Banter` (0 / 1 / 2). - `BossTactics.h`: the player's own plan per boss in plain words (`tactics Lucifron: adds first, no aoe, no fear, tank here`), kept per account and boss (OwnerRegistry, migration 0039). While that boss fights: kill order (`PublishTargets` takes the boss or the adds off the DPS candidates), `no_aoe`, `cc_deny` (left out of the crowd-control election and added to the snapshot's deny), and the diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidBanter.h b/src/modules/PlayerbotV2/Bot/Raid/RaidBanter.h new file mode 100644 index 0000000000..34f7bdcbde --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidBanter.h @@ -0,0 +1,238 @@ +// RaidBanter - a raid leader who reacts to mistakes, and bots that argue after a wipe, the way a real raid's chat reads. +// +// One bot of the raid is its leader (the group's leader when that is a bot, else an assistant bot, else the first bot): it calls out +// a raider standing in the bad stuff, a cast nobody kicked, a crowd control somebody broke, an extra pull, the wipe and the kill. After +// a wipe one or two other bots answer: blame, excuses, "my bad". Game mistakes only, in good fun: never about the person behind the +// character, never a slur (the lines here are fixed; a model's line goes through the program's filter, and the program never sees a +// player's own persona text for these). +// +// Playerbot.Raid.Banter 0 off, 1 mild (teasing, the default), 2 harsh (a leader who freaks out at every mishap) +// +// No model needed: every line has a fixed form here, translated per reader where it leaves the server (the Russian catalog). With the bot +// bridge answering chat, the program may write the line in the bot's own words; when its line is not back in time (kModelWaitMs), the +// fixed line is said instead, so a raid never waits for a slow model. +// +// Pure: the vocabulary, the lines, the rate limits (unit tested in tests/game/ClassicBossWarnings.cpp). RaidBrain.cpp spots the +// mishaps and sends. + +#pragma once + +#include +#include +#include +#include +#include + +namespace Playerbot::Raid { + +enum class BanterLevel : uint8_t { Off = 0, Mild = 1, Harsh = 2 }; + +enum class Mishap : uint8_t +{ + StoodInBad = 0, // a raider stays inside a hazard circle (fire, a void zone, a bomb's blast) and gets hurt + MissedKick, // a cast the raid kicks first (RaidRules::interruptFirst) went off + BrokeCc, // a long crowd control broke early under someone's damage + ExtraPull, // a new pack joined a running fight (not the boss's own summons) + Wipe, // the raid is lost + BossDown, // the boss died + Count +}; + +// How long the program has to write a line before the fixed one is said. +constexpr uint32_t kModelWaitMs = 2500; + +namespace BanterDetail { + +struct Lines { char const* mild[3]; char const* harsh[3]; }; + +// `{}` is the name the line is about (a raider, a spell; for the kill, the raider who died first, if anyone did). Lower case, short, +// no pronoun that needs a gender. +inline Lines const& LeaderLines(Mishap m, bool named) +{ + static Lines const kBad = { { "{}, out of the bad stuff pls", "{} you're standing in it", "{} move, that hurts" }, + { "{} GET OUT OF IT", "{} why are you standing in that again", "{} MOVE. it's not a buff" } }; + static Lines const kKick = { { "who's on kicks? {} went off", "kick {} next time pls", "{} got through, kickers wake up" }, + { "NOBODY KICKED {}??", "{} went off AGAIN. kick it", "are the kickers asleep? {} went off" } }; + static Lines const kCc = { { "{} broke the cc, watch your target", "careful {}, that was cc'd", "{} broke it, check the marks" }, + { "{} STOP BREAKING MY CC", "{} broke cc again. target. the. skull", "who broke it? oh it's {} again" } }; + static Lines const kCcAnon = { { "cc broke, watch your targets", "someone broke the cc, check the marks", "cc's gone, tanks pick it up" }, + { "WHO BROKE THE CC", "cc broke AGAIN. target the skull", "who's hitting the cc'd one. stop" } }; + static Lines const kPull = { { "extra pull, adds on {}, tanks grab them", "adds on {}, pick them up", "we've got company, adds on {}" }, + { "WHO PULLED THAT. adds on {}", "{} has adds, tanks GRAB THEM", "extra pull again?? adds on {}" } }; + static Lines const kPullAnon = { { "extra pull, tanks grab the adds", "we've got company, tanks pick them up", "adds incoming, tanks" }, + { "WHO PULLED THAT", "extra pull AGAIN, tanks grab them", "adds. why are there adds" } }; + static Lines const kWipe = { { "wipe, it happens. run back and rebuff", "ok that's a wipe, run back, we got this", + "wipe. {} went first, let's go again" }, + { "WIPE. {} died first. again", "that was a mess. run back and stay out of the bad stuff", + "{} died first, everyone run back. AGAIN" } }; + static Lines const kDown = { { "gg, nice one everyone", "gg, clean kill", "gg, rez {} and let's move on" }, + { "FINALLY. gg", "gg. see, not that hard", "gg. {}, we'll talk about dying later" } }; + switch (m) + { + case Mishap::StoodInBad: return kBad; + case Mishap::MissedKick: return kKick; + case Mishap::BrokeCc: return named ? kCc : kCcAnon; + case Mishap::ExtraPull: return named ? kPull : kPullAnon; + case Mishap::Wipe: return kWipe; + default: return kDown; + } +} + +inline std::string Fill(char const* tmpl, std::string const& name) +{ + std::string out(tmpl); + if (size_t const at = out.find("{}"); at != std::string::npos) + out.replace(at, 2, name); + return out; +} + +inline bool HasSlot(char const* tmpl) { return std::string(tmpl).find("{}") != std::string::npos; } + +} // namespace BanterDetail + +// The raid leader's line for a mishap. `name` is the raider (or the spell, for MissedKick) it is about, may be empty (the lines without +// a name are taken then). `pick` chooses among the lines (a random number). Off: empty. +inline std::string LeaderLine(Mishap m, BanterLevel level, std::string const& name, uint32_t pick) +{ + if (level == BanterLevel::Off || m >= Mishap::Count) + return {}; + BanterDetail::Lines const& lines = BanterDetail::LeaderLines(m, !name.empty()); + char const* const* set = level == BanterLevel::Harsh ? lines.harsh : lines.mild; + // A line with a name slot needs a name; without one, the first line with no slot (or nothing). + for (uint32_t i = 0; i < 3; ++i) + { + char const* tmpl = set[(pick + i) % 3]; + if (!name.empty() || !BanterDetail::HasSlot(tmpl)) + return BanterDetail::Fill(tmpl, name); + } + return {}; +} + +// After a wipe: what one other bot says (an excuse, a blame, an apology). `blame` is the raider who died first (may be empty), `self` +// whether the speaking bot is that raider. Harsh adds a bit of bite. Never about the person, only the fight. +inline std::string WipeReply(BanterLevel level, std::string const& blame, bool self, uint32_t pick) +{ + if (level == BanterLevel::Off) + return {}; + if (self) + { + static char const* const kSelf[] = { "my bad", "sorry, my bad", "lag, i swear", "i was rooted ok" }; + return kSelf[pick % std::size(kSelf)]; + } + static char const* const kMild[] = { "healers?", "lag", "who had the bomb", "rip", "one more go", "{} pulled aggro i think", + "that was {} lol" }; + static char const* const kHarsh[] = { "that was {}'s fault", "{} pulled aggro AGAIN", "healers??", "can we get {} out of the fire next time", + "lag. definitely lag", "who had the bomb. be honest" }; + char const* const* set = level == BanterLevel::Harsh ? kHarsh : kMild; + size_t const n = level == BanterLevel::Harsh ? std::size(kHarsh) : std::size(kMild); + for (size_t i = 0; i < n; ++i) + { + char const* tmpl = set[(pick + i) % n]; + if (!blame.empty() || !BanterDetail::HasSlot(tmpl)) + return BanterDetail::Fill(tmpl, blame); + } + return {}; +} + +// What the program is told happened, in plain words (it writes its own line from this when the bridge is on). +inline std::string MishapDetail(Mishap m, std::string const& name, std::string const& boss) +{ + std::string const at = boss.empty() ? std::string() : " (fighting " + boss + ")"; + switch (m) + { + case Mishap::StoodInBad: return name + " keeps standing in a damaging area" + at; + case Mishap::MissedKick: return "nobody interrupted the enemy cast " + name + at; + case Mishap::BrokeCc: return (name.empty() ? std::string("someone") : name) + " broke a crowd-controlled enemy early" + at; + case Mishap::ExtraPull: return "an extra pack of enemies was pulled into the fight" + (name.empty() ? std::string() : ", they attack " + name) + at; + case Mishap::Wipe: return "the raid just wiped" + at + (name.empty() ? std::string() : "; " + name + " died first"); + default: return "the raid just killed the boss" + (boss.empty() ? std::string() : " " + boss) + + (name.empty() ? std::string() : "; " + name + " died during the fight"); + } +} + +inline char const* MishapWord(Mishap m) +{ + static char const* const kWords[] = { "stood_in_bad", "missed_kick", "broke_cc", "extra_pull", "wipe", "boss_down" }; + return m < Mishap::Count ? kWords[size_t(m)] : "mishap"; +} + +// How often the leader may react, so it reads like a person and not a log: +// * one line per raid every kLeaderGapMs (mild) or kLeaderGapHarshMs (harsh); +// * the same kind of mishap once per kSameKindMs; the same raider named for the same kind once per kSameNameMs; +// * a wipe and a kill always get their line (they end the fight), at most once per kFightEndMs. +class BanterGate +{ +public: + static constexpr uint32_t kLeaderGapMs = 20000; + static constexpr uint32_t kLeaderGapHarshMs = 10000; + static constexpr uint32_t kSameKindMs = 45000; + static constexpr uint32_t kSameNameMs = 90000; + static constexpr uint32_t kFightEndMs = 30000; + + bool Allow(uint64_t group, Mishap m, std::string const& name, BanterLevel level, uint32_t now) + { + if (level == BanterLevel::Off || m >= Mishap::Count) + return false; + State& s = groups_[group]; + size_t const k = size_t(m); + bool const end = m == Mishap::Wipe || m == Mishap::BossDown; + if (end) + { + if (s.end && now - s.end < kFightEndMs) + return false; + } + else + { + uint32_t const gap = level == BanterLevel::Harsh ? kLeaderGapHarshMs : kLeaderGapMs; + if (s.last && now - s.last < gap) + return false; + if (s.kind[k] && now - s.kind[k] < kSameKindMs) + return false; + if (!name.empty()) + if (auto it = s.named.find(std::to_string(k) + ":" + name); it != s.named.end() && now - it->second < kSameNameMs) + return false; + } + uint32_t const stamp = now ? now : 1u; + s.last = stamp; + s.kind[k] = stamp; + if (end) + s.end = stamp; + if (!name.empty()) + { + if (s.named.size() > 64) + s.named.clear(); + s.named[std::to_string(k) + ":" + name] = stamp; + } + return true; + } + + void Prune(uint32_t now) + { + for (auto it = groups_.begin(); it != groups_.end();) + it = now - it->second.last >= kSameNameMs ? groups_.erase(it) : std::next(it); + } + + size_t Tracked() const { return groups_.size(); } + +private: + struct State + { + uint32_t last = 0, end = 0; + uint32_t kind[size_t(Mishap::Count)] = {}; + std::unordered_map named; + }; + std::unordered_map groups_; +}; + +// Reads Playerbot.Raid.Banter (0 / 1 / 2, anything higher is harsh). +inline BanterLevel BanterLevelFromConfig(int value) +{ + return value <= 0 ? BanterLevel::Off : value == 1 ? BanterLevel::Mild : BanterLevel::Harsh; +} + +inline char const* BanterLevelWord(BanterLevel l) +{ + return l == BanterLevel::Harsh ? "harsh" : l == BanterLevel::Mild ? "mild" : "off"; +} + +} // namespace Playerbot::Raid diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp index 38669b804e..b465a05885 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp @@ -10,7 +10,9 @@ #include "Api/BotLanguage.h" #include "DispelWorth.h" #include "RaidBrainInternal.h" +#include "RaidBanter.h" #include "RaidCallouts.h" +#include "../BotBridge.h" #include "RaidEncounters.h" #include "RaidGeometry.h" #include "RaidReadiness.h" @@ -4153,6 +4155,237 @@ Brain& GetBrain() namespace { +// --------------------------------------------------------------------------- +// Raid banter (RaidBanter.h): the raid leader bot reacts to mistakes, bots argue a little after a wipe. +// --------------------------------------------------------------------------- + +BanterLevel BanterNow() { return BanterLevelFromConfig(Services::Config().raid_banter()); } + +bool GroupHasHuman(Group const* group) +{ + for (GroupReference const& ref : group->GetMembers()) + if (Player const* m = ref.GetSource(); m && !Services::Lifecycle().is_bot(m->GetGUID().GetCounter())) + return true; + return false; +} + +// `from` speaks in the group's chat: raid chat in a raid group, the sub-group's party chat otherwise; each reader reads it in his +// language (BotLanguage, the Russian catalog). +void SayInGroupChat(Player* from, Group* group, std::string const& text) +{ + bool const raid = group->isRaidGroup(); + bool const leader = group->IsLeader(from->GetGUID()); + ChatMsg const type = raid ? (leader ? CHAT_MSG_RAID_LEADER : CHAT_MSG_RAID) : (leader ? CHAT_MSG_PARTY_LEADER : CHAT_MSG_PARTY); + BotLanguage::GroupChat(from, group, type, text, raid ? -1 : group->GetMemberGroup(from->GetGUID())); +} + +// The raid leader's voice on `map`: the group's leader when that is a bot, else an assistant bot, else the first bot by guid (alive +// or not: a dead leader still talks). Null: no bot of the group there. +Player* BanterLeader(Group* group, Map* map) +{ + Player* assistant = nullptr; + Player* first = nullptr; + for (GroupReference const& ref : group->GetMembers()) + { + Player* m = ref.GetSource(); + if (!m || !m->IsInWorld() || m->GetMap() != map || !Services::Lifecycle().is_bot(m->GetGUID().GetCounter())) + continue; + if (group->IsLeader(m->GetGUID())) + return m; + if (!assistant && group->IsAssistant(m->GetGUID())) + assistant = m; + if (!first || m->GetGUID() < first->GetGUID()) + first = m; + } + return assistant ? assistant : first; +} + +// A line waiting for its time: the fixed text, said at `due` unless the program's own line for `ask` came back in time. +struct BanterSay { uint32_t due = 0; ObjectGuid group; ObjectGuid bot; std::string text; uint64 ask = 0; }; +std::vector g_banterQueue; +BanterGate g_banter; + +void QueueBanter(Group* group, Player* bot, Mishap m, std::string const& name, std::string const& boss, std::string const& text, + bool leader, BanterLevel level, uint32_t delayMs, uint32_t now) +{ + if (text.empty() || !bot || g_banterQueue.size() >= 64) + return; + uint64 const ask = BotBridge::AskRaidLine(bot, MishapWord(m), MishapDetail(m, name, boss), text, BanterLevelWord(level), + leader ? "raid leader" : "raider", delayMs, kModelWaitMs); + g_banterQueue.push_back({ now + (ask ? std::max(delayMs, kModelWaitMs) : delayMs), group->GetGUID(), bot->GetGUID(), text, ask }); + TC_LOG_INFO("playerbot.v2.raid", "[raid_banter] {} ({}{}): {}{}", bot->GetName(), MishapWord(m), leader ? ", leader" : "", text, + ask ? " (asked the program first)" : ""); +} + +// World thread, every plan pass: the fixed lines whose time has come. +void SayDueBanter(uint32_t now) +{ + for (auto it = g_banterQueue.begin(); it != g_banterQueue.end();) + { + if (int32_t(now - it->due) < 0) + { + ++it; + continue; + } + if (!it->ask || !BotBridge::RaidLineAnswered(it->ask)) + if (Player* bot = ObjectAccessor::FindConnectedPlayer(it->bot)) + if (Group* group = bot->GetGroup(); group && group->GetGUID() == it->group) + SayInGroupChat(bot, group, it->text); + it = g_banterQueue.erase(it); + } +} + +// The leader reacts to a mishap (rate limited per raid by BanterGate). `name`: the raider (or spell) it is about. +void LeaderReacts(Group* group, Map* map, Mishap m, std::string const& name, std::string const& boss, uint32_t now) +{ + BanterLevel const level = BanterNow(); + if (level == BanterLevel::Off || !group || !map || !GroupHasHuman(group)) + return; + Player* leader = BanterLeader(group, map); + if (!leader || !g_banter.Allow(group->GetGUID().GetCounter(), m, name, level, now)) + return; + QueueBanter(group, leader, m, name, boss, LeaderLine(m, level, name, urand(0, 2)), true, level, urand(600, 1600), now); +} + +// After a wipe: the leader's line, then one or two other bots (blame, excuses, "my bad"). +void WipeBanter(Group* group, Map* map, std::string const& firstDead, std::string const& boss, uint32_t now) +{ + BanterLevel const level = BanterNow(); + if (level == BanterLevel::Off || !group || !map || !GroupHasHuman(group)) + return; + Player* leader = BanterLeader(group, map); + if (!leader || !g_banter.Allow(group->GetGUID().GetCounter(), Mishap::Wipe, std::string(), level, now)) + return; + QueueBanter(group, leader, Mishap::Wipe, firstDead, boss, LeaderLine(Mishap::Wipe, level, firstDead, urand(0, 2)), true, level, + urand(1500, 3000), now); + std::vector others; + for (GroupReference const& ref : group->GetMembers()) + if (Player* m = ref.GetSource(); m && m != leader && m->IsInWorld() && m->GetMap() == map && + Services::Lifecycle().is_bot(m->GetGUID().GetCounter())) + others.push_back(m); + for (size_t i = others.size(); i > 1; --i) + std::swap(others[i - 1], others[urand(0, uint32(i - 1))]); + // The one who died first answers first when it is a bot ("my bad"); then somebody else. + for (size_t i = 0; i < others.size(); ++i) + if (others[i]->GetName() == firstDead) + std::swap(others[0], others[i]); + size_t const speakers = std::min(others.size(), urand(1, 2)); + uint32_t at = urand(4000, 6500); + for (size_t i = 0; i < speakers; ++i) + { + bool const self = others[i]->GetName() == firstDead; + std::string const blame = firstDead == others[i]->GetName() ? std::string() : firstDead; + QueueBanter(group, others[i], Mishap::Wipe, firstDead, boss, WipeReply(level, blame, self, urand(0, 31)), false, level, at, now); + at += urand(2500, 4500); + } +} + +// Per raid group: what the banter watches between plan passes. +struct BanterWatch +{ + std::unordered_map> bad; // member -> (inside a hazard since, health then) + struct Cast { uint32_t spell = 0; int32_t left = 0; }; + std::map casts; // enemy -> its interrupt-first cast in progress + struct Cc { int32_t left = 0; std::string hitter; }; + std::map cc; // enemy -> its long crowd control, and a member hitting it + uint32_t seen = 0; +}; +std::unordered_map g_banterWatch; + +// A member stands inside one of the hazard circles the raid rules put around it (noted by the movement pass for bots, and for the +// humans at the end of the plan pass). +void BanterNoteBad(uint64_t key, Player* p, bool inside, uint32_t now) +{ + auto& bad = g_banterWatch[key].bad; + uint64_t const id = p->GetGUID().GetCounter(); + if (!inside) + bad.erase(id); + else if (!bad.count(id)) + bad[id] = { now ? now : 1u, uint32_t(p->GetHealth()) }; +} + +int32_t LongestCcLeft(Unit* u) +{ + int32_t left = u->IsPolymorphed() ? 10000 : 0; + for (Ranks const* ranks : { &kBanish, &kShackle, &kHibernate, &kPolymorph }) + for (uint32_t id : *ranks) + if (Aura const* a = u->GetAura(id)) + left = std::max(left, a->GetDuration()); + return left; +} + +// The mishaps of one plan pass: a raider in the bad stuff for 3 s and hurt, an interrupt-first cast that went off, a long crowd control +// broken under someone's damage. (Extra pulls: TrackPull; wipes and kills: EndQuietPulls.) +void SpotMishaps(Plan const& plan, Group* group, uint64_t key, Map* map, uint32_t now) +{ + BanterWatch& w = g_banterWatch[key]; + w.seen = now; + if (BanterNow() == BanterLevel::Off) + return; + std::string boss; + for (Unit* u : plan.enemies) + if (Creature* c = u->ToCreature(); c && IsBoss(c, plan.rules)) + boss = c->GetName(); + + for (Member const& m : plan.members) + { + auto it = w.bad.find(m.p->GetGUID().GetCounter()); + if (it == w.bad.end() || now - it->second.first < 3000 || m.p->GetHealth() >= it->second.second) + continue; + it->second = { now, uint32_t(m.p->GetHealth()) }; // the next call for the same raider needs another 3 s in it + LeaderReacts(group, map, Mishap::StoodInBad, m.p->GetName(), boss, now); + } + + std::map casts; + std::map cc; + ObjectGuid const skull = group->GetTargetIcon(7); + for (Unit* enemy : plan.enemies) + { + if (Spell const* s = enemy->GetCurrentSpell(CURRENT_GENERIC_SPELL); s && InterruptFirst(plan.mapId, s->GetSpellInfo()->Id)) + casts[enemy->GetGUID()] = { s->GetSpellInfo()->Id, s->GetTimer() }; + if (Controlled(enemy)) + { + BanterWatch::Cc c{ LongestCcLeft(enemy), {} }; + for (Member const& m : plan.members) + if (m.p->GetVictim() == enemy) + c.hitter = m.p->GetName(); + cc[enemy->GetGUID()] = c; + } + } + // A cast that was nearly done and is gone without a school lockout on its caster went off: nobody kicked it. + for (auto const& [guid, was] : w.casts) + { + if (casts.count(guid) && casts[guid].spell == was.spell) + continue; + Unit* enemy = ObjectAccessor::GetUnit(*plan.members.front().p, guid); + SpellInfo const* info = sSpellMgr->GetSpellInfo(was.spell, DIFFICULTY_NONE); + if (!enemy || !enemy->IsAlive() || !info || was.left > 700 || enemy->GetSpellHistory()->IsSchoolLocked(info->GetSchoolMask())) + continue; + char const* spellName = info->SpellName ? info->SpellName->Str[LOCALE_enUS] : nullptr; + LeaderReacts(group, map, Mishap::MissedKick, spellName ? spellName : "the cast", enemy->GetName(), now); + } + // A crowd control with more than 3 s left that is gone while its target lives: somebody broke it (the skull on it is the owner's + // call to kill it, not a mistake). + for (auto const& [guid, was] : w.cc) + { + if (cc.count(guid) || was.left <= 3000 || guid == skull) + continue; + Unit* enemy = ObjectAccessor::GetUnit(*plan.members.front().p, guid); + if (enemy && enemy->IsAlive() && enemy->IsInCombat()) + LeaderReacts(group, map, Mishap::BrokeCc, was.hitter, boss, now); + } + w.casts = std::move(casts); + w.cc = std::move(cc); +} + +void ForgetBanterWatch(uint32_t now) +{ + for (auto it = g_banterWatch.begin(); it != g_banterWatch.end();) + it = now - it->second.seen > 60000u ? g_banterWatch.erase(it) : std::next(it); + if (g_banter.Tracked() > 128) + g_banter.Prune(now); +} + // Pull log for the test-night digest (scripts/bot-log-digest.ps1). One [raid_encounter] line when a group on a raid map // enters combat and one when the fight is over (no enemy for 4 s): what was pulled, how long it took and how it ended. // World thread only, a few map operations per raid group every plan pass. @@ -4174,6 +4407,9 @@ struct PullLog std::unordered_map hitBy; std::string firstDead, firstCause; uint32_t deaths = 0; + // Extra pulls (RaidBanter): new mobs that are no summons joining after the pull's first seconds, counted in a 5 s window. + uint32_t newMobsFrom = 0, newMobs = 0; + std::string newMobsOn; // the raider the first of them attacks }; std::unordered_map g_pulls; constexpr uint32_t kPullEndQuietMs = 4000; @@ -4461,6 +4697,29 @@ void TrackPull(uint64_t key, Group* group, detail::Plan const& plan, Map* map, u bool const boss = detail::IsBoss(c, plan.rules); pl.engaged.emplace(c->GetGUID(), PullLog::Mob{ c->GetEntry(), c->GetName(), boss }); added = true; + // A pack joining a fight that runs (not the boss's own summons, not in the pull's first 8 s): an extra pull. + if (!boss && !c->IsSummon() && now_ms - pl.startMs >= 8000) + { + if (!pl.newMobsFrom || now_ms - pl.newMobsFrom > 5000) + { + pl.newMobsFrom = now_ms ? now_ms : 1u; + pl.newMobs = 0; + pl.newMobsOn.clear(); + } + ++pl.newMobs; + if (pl.newMobsOn.empty()) + if (Unit* v = c->GetVictim(); v && v->IsPlayer()) + pl.newMobsOn = v->GetName(); + } + } + if (pl.newMobs >= 2) + { + std::string boss; + for (auto const& [eg, em] : pl.engaged) + if (em.boss && boss.empty()) + boss = em.name; + LeaderReacts(group, map, Mishap::ExtraPull, pl.newMobsOn, boss, now_ms); + pl.newMobs = 0; } for (auto& [eg, em] : pl.engaged) if (Creature* ec = map->GetCreature(eg)) @@ -4548,6 +4807,20 @@ void EndQuietPulls(uint32_t now_ms) // The boss dead is a kill even with its adds still standing (Garr's Firesworn, Ragnaros' Sons of Flame): the left list names them. bool const bossKilled = bosses > 0 && bossesDead == bosses; char const* result = killed == pl.engaged.size() || bossKilled ? "kill" : ((alive * 4 <= pl.startAlive && mostDead) || humanDeadNoneAlive ? "wipe" : "reset"); + // The raid leader's word on it, and after a wipe the others' (RaidBanter). A group of 15 or fewer has the companions' own + // wipe and kill lines (PartyBanter) instead. + if (Group* bg = sGroupMgr->GetGroupByGUID(ObjectGuid::Create(pl.groupLow)); + bg && map && (bg->GetMembersCount() > 15 || !Services::Config().behavior_party_banter())) + { + std::string bossName; + for (auto const& [guid, mob] : pl.engaged) + if (mob.boss && bossName.empty()) + bossName = mob.name; + if (bossKilled) + LeaderReacts(bg, map, Mishap::BossDown, pl.firstDead, bossName, now_ms); + else if (std::strcmp(result, "wipe") == 0) + WipeBanter(bg, map, pl.firstDead, bossName, now_ms); + } TC_LOG_INFO("playerbot.v2.raid", "[raid_encounter] ts={} map={} group={} pull end: result={} dur={}s killed={}/{} alive={}/{} deaths={} | {}{}{}", uint64_t(GameTime::GetGameTime()), pl.mapId, pl.groupLow, result, (pl.lastSeenMs - pl.startMs) / 1000, killed, uint32_t(pl.engaged.size()), alive, pl.startAlive, pl.deaths, PullLabel(pl), left.empty() ? "" : " | left: ", left); @@ -5009,6 +5282,7 @@ void Brain::Update(uint32_t now_ms) LogDeadHumanReleaseState(now_ms); EndAbandonedEncounters(now_ms); + SayDueBanter(now_ms); // Bucket bots on raid maps that have rules by (group, map). struct Bucket { Group* group = nullptr; uint32_t mapId = 0; uint64_t refBot = 0; Player* ref = nullptr; }; @@ -5204,6 +5478,7 @@ void Brain::Update(uint32_t now_ms) o.active = true; std::vector const circles = HazardsFor(plan, m, now_ms); nextMoveCtx[m.p->GetGUID().GetCounter()] = BuildMoveContext(plan, m, circles); + BanterNoteBad(key, m.p, !circles.empty() && InsideAny(circles, m.p->GetPositionX(), m.p->GetPositionY(), 0.0f), now_ms); if (!m.p->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED | UNIT_STATE_CONFUSED | UNIT_STATE_FLEEING)) { DecideMove(plan, m, now_ms, circles, o); @@ -5285,6 +5560,19 @@ void Brain::Update(uint32_t now_ms) ApplyFightScript(plan, next, now_ms, dump); PublishMeleeSoak(plan, next); PublishAuraReactions(plan, next); + + // The raid leader's eye (RaidBanter): the humans' hazard circles too (the bots' were noted by the movement pass), then the + // mishaps of this pass. Last in the pass, so the hazard pass's per-member scratch state is no longer read by anything. + if (BanterNow() != BanterLevel::Off) + { + for (Member const& m : plan.members) + if (!m.bot) + { + std::vector const circles = HazardsFor(plan, m, now_ms); + BanterNoteBad(key, m.p, !circles.empty() && InsideAny(circles, m.p->GetPositionX(), m.p->GetPositionY(), 0.0f), now_ms); + } + SpotMishaps(plan, b.group, key, b.ref->GetMap(), now_ms); + } } // Change-only decision log (WARN so it shows with the usual Logger.playerbot.v2=3 test setup): @@ -5321,6 +5609,7 @@ void Brain::Update(uint32_t now_ms) lastSignature.clear(); if (g_callouts.Tracked() > 256) g_callouts.Prune(now_ms); + ForgetBanterWatch(now_ms); if (g_lastTacticSpot.size() > 256) g_lastTacticSpot.clear(); if (g_lastTacticSpotLog.size() > 256) diff --git a/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp b/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp index eb83daca4f..0f5ac99ac9 100644 --- a/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp +++ b/src/modules/PlayerbotV2/Util/BotLocaleRu.cpp @@ -810,6 +810,70 @@ std::vector const& RussianEntries() { "no AoE", "без АоЕ" }, { "no fear", "без страха" }, { "tank at your spot", "танк на вашем месте" }, + // ---- raid leader banter (Bot/Raid/RaidBanter.h): raid chat is informal, so "ты" here; no past tense about the speaker; "my bad" and "rip" are in the party banter above + { "{}, out of the bad stuff pls", "{}, выйди из гадости, пжл" }, + { "{} you're standing in it", "{}, ты стоишь прямо в этом" }, + { "{} move, that hurts", "{}, отойди, это больно" }, + { "{} GET OUT OF IT", "{}, ВЫЙДИ ОТТУДА" }, + { "{} why are you standing in that again", "{}, почему ты опять там стоишь" }, + { "{} MOVE. it's not a buff", "{}, ДВИГАЙСЯ. это не бафф" }, + { "who's on kicks? {} went off", "кто на киках? {} не сбили" }, + { "kick {} next time pls", "в следующий раз сбейте {}, пжл" }, + { "{} got through, kickers wake up", "{} не сбили, кикеры, проснитесь" }, + { "NOBODY KICKED {}??", "НИКТО НЕ СБИЛ {}??" }, + { "{} went off AGAIN. kick it", "{} ОПЯТЬ не сбили. сбивайте" }, + { "are the kickers asleep? {} went off", "кикеры спят? {} не сбили" }, + { "{} broke the cc, watch your target", "{} сбивает контроль, следи за целью" }, + { "careful {}, that was cc'd", "осторожно, {}, цель под контролем" }, + { "{} broke it, check the marks", "{} сбивает контроль, смотри на метки" }, + { "{} STOP BREAKING MY CC", "{}, ХВАТИТ СБИВАТЬ МОЙ КОНТРОЛЬ" }, + { "{} broke cc again. target. the. skull", "{} опять сбивает контроль. бей. в. череп" }, + { "who broke it? oh it's {} again", "кто сбил? а, опять {}" }, + { "cc broke, watch your targets", "контроль слетел, следите за целями" }, + { "someone broke the cc, check the marks", "кто-то сбил контроль, смотрите на метки" }, + { "cc's gone, tanks pick it up", "контроль слетел, танки, подберите" }, + { "WHO BROKE THE CC", "КТО СБИЛ КОНТРОЛЬ" }, + { "cc broke AGAIN. target the skull", "контроль ОПЯТЬ слетел. бейте в череп" }, + { "who's hitting the cc'd one. stop", "кто бьёт цель под контролем. хватит" }, + { "extra pull, adds on {}, tanks grab them", "лишний пул, адды на {}, танки, забирайте" }, + { "adds on {}, pick them up", "адды на {}, подберите их" }, + { "we've got company, adds on {}", "у нас гости, адды на {}" }, + { "WHO PULLED THAT. adds on {}", "КТО ЭТО ЗАПУЛИЛ. адды на {}" }, + { "{} has adds, tanks GRAB THEM", "на {} адды, танки, ЗАБИРАЙТЕ" }, + { "extra pull again?? adds on {}", "опять лишний пул?? адды на {}" }, + { "extra pull, tanks grab the adds", "лишний пул, танки, забирайте аддов" }, + { "we've got company, tanks pick them up", "у нас гости, танки, подберите их" }, + { "adds incoming, tanks", "адды идут, танки" }, + { "WHO PULLED THAT", "КТО ЭТО ЗАПУЛИЛ" }, + { "extra pull AGAIN, tanks grab them", "ОПЯТЬ лишний пул, танки, забирайте" }, + { "adds. why are there adds", "адды. откуда адды" }, + { "wipe, it happens. run back and rebuff", "вайп, бывает. бегите назад и бафайтесь" }, + { "ok that's a wipe, run back, we got this", "ок, это вайп, бегите назад, у нас получится" }, + { "wipe. {} went first, let's go again", "вайп. {} - первый труп, давайте ещё раз" }, + { "WIPE. {} died first. again", "ВАЙП. {} - опять первый труп" }, + { "that was a mess. run back and stay out of the bad stuff", "это был бардак. бегите назад и не стойте в гадости" }, + { "{} died first, everyone run back. AGAIN", "{} - первый труп, все бегом назад. ОПЯТЬ" }, + { "gg, nice one everyone", "гг, все молодцы" }, + { "gg, clean kill", "гг, чистое убийство" }, + { "gg, rez {} and let's move on", "гг, поднимите {} и идём дальше" }, + { "FINALLY. gg", "НАКОНЕЦ-ТО. гг" }, + { "gg. see, not that hard", "гг. видите, не так уж сложно" }, + { "gg. {}, we'll talk about dying later", "гг. {}, про смерти поговорим потом" }, + { "sorry, my bad", "сорри, моя вина" }, + { "lag, i swear", "лаг, клянусь" }, + { "i was rooted ok", "меня зарутило, ок" }, + { "healers?", "хилы?" }, + { "lag", "лаг" }, + { "who had the bomb", "у кого была бомба" }, + { "one more go", "ещё разок" }, + { "{} pulled aggro i think", "кажется, {} срывает аггро" }, + { "that was {} lol", "это всё {} лол" }, + { "that was {}'s fault", "это вина {}" }, + { "{} pulled aggro AGAIN", "{} ОПЯТЬ срывает аггро" }, + { "healers??", "хилы??" }, + { "can we get {} out of the fire next time", "можно в следующий раз вытащить {} из огня" }, + { "lag. definitely lag", "лаг. точно лаг" }, + { "who had the bomb. be honest", "у кого была бомба. честно" }, // ---- arena (.bot arena, the arena ready line) ------------------------------------------------------------------------ { "Your arena is ready. Enter: click Enter at the minimap or type .bot arena enter. Leave: type .bot arena leave.", "Ваша арена готова. Войти: нажмите «Войти» у миникарты или введите .bot arena enter. Отказаться: введите .bot arena leave." }, { "No arena is ready for you yet.", "Для вас пока нет готовой арены." }, diff --git a/src/modules/PlayerbotV2/Util/ConfigReader.cpp b/src/modules/PlayerbotV2/Util/ConfigReader.cpp index f5c1a87040..4bdda66c1b 100644 --- a/src/modules/PlayerbotV2/Util/ConfigReader.cpp +++ b/src/modules/PlayerbotV2/Util/ConfigReader.cpp @@ -79,6 +79,7 @@ void ConfigReader::apply_from_loaded_config() raid_enabled_ = c.GetBoolDefault("Playerbot.Raid.Enable", true, true); boss_warnings_enabled_ = c.GetBoolDefault("Playerbot.Raid.BossWarnings", true, true); raid_callouts_enabled_ = c.GetBoolDefault("Playerbot.Raid.Callouts", true, true); + raid_banter_ = c.GetIntDefault("Playerbot.Raid.Banter", 1, true); raid_auto_accept_rez_ = c.GetBoolDefault("Playerbot.Raid.AutoAcceptOwnerRez", true, true); housing_enabled_ = c.GetBoolDefault("Playerbot.Housing.Enabled", false, true); diff --git a/src/modules/PlayerbotV2/Util/ConfigReader.h b/src/modules/PlayerbotV2/Util/ConfigReader.h index 06cf66d681..59c2821d7e 100644 --- a/src/modules/PlayerbotV2/Util/ConfigReader.h +++ b/src/modules/PlayerbotV2/Util/ConfigReader.h @@ -57,6 +57,7 @@ public: bool raid_enabled() const { return raid_enabled_; } bool boss_warnings_enabled() const { return boss_warnings_enabled_; } bool raid_callouts_enabled() const { return raid_callouts_enabled_; } + int32 raid_banter() const { return raid_banter_; } // 0 off, 1 mild, 2 harsh (Raid/RaidBanter.h) bool raid_auto_accept_rez() const { return raid_auto_accept_rez_; } // Housing @@ -608,6 +609,7 @@ private: bool raid_enabled_ = true; bool boss_warnings_enabled_ = true; bool raid_callouts_enabled_ = true; + int32 raid_banter_ = 1; bool raid_auto_accept_rez_ = true; bool housing_enabled_ = true; diff --git a/src/modules/PlayerbotV2/conf/playerbot.conf.dist b/src/modules/PlayerbotV2/conf/playerbot.conf.dist index bb3a8f2e4a..1caf0006fa 100644 --- a/src/modules/PlayerbotV2/conf/playerbot.conf.dist +++ b/src/modules/PlayerbotV2/conf/playerbot.conf.dist @@ -573,6 +573,13 @@ Playerbot.Raid.BossWarnings = 1 # lines come from the raid rules, and they are rate limited (a few lines a minute). 0 turns them off. Playerbot.Raid.Callouts = 1 +# A raid leader bot who reacts to mistakes in raid chat (someone standing in the bad stuff, a cast nobody kicked, broken crowd +# control, an extra pull) and bots that argue a little after a wipe ("healers?", "that was X's fault", "my bad"). Game mistakes +# only, in good fun, never a slur. Works without a model; with the bot bridge answering chat the program may word the lines +# (a line not back within 2.5 s is said the fixed way). At most one leader line every 20 s (mild) or 10 s (harsh). +# 0 = off, 1 = mild (teasing), 2 = harsh (a leader who freaks out at every mishap) +Playerbot.Raid.Banter = 1 + # A resurrection a bot casts on you is accepted for you after 3 s without an answer (the 70205 client shows no accept popup). Playerbot.Raid.AutoAcceptOwnerRez = 1 diff --git a/src/modules/PlayerbotV2/tools/bot_bridge_ollama.py b/src/modules/PlayerbotV2/tools/bot_bridge_ollama.py index 5aec6e5677..3985d4ec4c 100644 --- a/src/modules/PlayerbotV2/tools/bot_bridge_ollama.py +++ b/src/modules/PlayerbotV2/tools/bot_bridge_ollama.py @@ -416,9 +416,9 @@ class ChatApi: log("model service %s: %s" % (self.url, "ready, model " + self.model if self.up else "not reachable, fixed answers for now")) return self.up - def chat(self, system, user, timeout=None): + def chat(self, system, user, timeout=None, max_tokens=None): # 160 tokens is room for the longest answer (a line, an action and a memory); fewer would cut the JSON off - body = {"model": self.model, "temperature": 0.8, "max_tokens": 160, + body = {"model": self.model, "temperature": 0.8, "max_tokens": max_tokens or 160, "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]} for attempt in (0, 1, 2): if self.json_mode: @@ -1168,6 +1168,65 @@ def answer_talk(event, api, minds, opts): log("%s [%s, %.1f s]: %s" % (bot, "talk" if channel == "say" else channel, time.time() - started, say)) +def answer_raid_line(event, api, opts): + """A bot's raid chat line about something that just happened in the fight (the raid leader reacting to a mistake, a raider + after a wipe). Fast or nothing: the server says its fixed line itself when this one is not back within wait_ms (2.5 s), so + the prompt is short, the answer is a few words, and a slow model simply loses. No persona text of anyone's goes in: the + lines stay game banter, never about a person, never a slur (check_line still filters what comes back).""" + api = getattr(api, "primary", api) # never the paid backup for banter + started = event["_seen"] + budget = int(event.get("wait_ms", 2500) or 2500) / 1000.0 - 0.3 + if budget - (time.time() - started) < 0.4 or not api.check(): + return + bot = event.get("bot", "") + swearing = bool(event.get("swearing")) and not opts.no_swearing + harsh = str(event.get("mood", "mild")) == "harsh" + leader = str(event.get("role", "")) == "raid leader" + russian = str(event.get("locale", "")).lower() == "ruru" + system = ("You are %s, a level %s %s in a World of Warcraft raid, writing in raid chat like a real player. %s " + "Write ONE short line (at most 12 words), lowercase, no emoji, no quotes. Only about the game and this mistake: " + "never about the person behind the character, never insults about real life, never slurs, no threats. " + "Answer as JSON: {\"say\": \"...\"}." + % (bot, event.get("level", "60"), event.get("class", ""), + ("You are the raid leader and you %s." % ("freak out at every mistake, loud and dramatic, CAPS now and then, but it " + "is all in good fun" if harsh else "tease people about mistakes, " + "calm and a bit dry")) if leader else + ("You just wiped with your raid; you %s." % ("blame someone a bit, half joking" if harsh else + "make an excuse, a joke or own up")))) + if russian: + system += " " + language_line(True) + user = "Just now: %s.\nThe kind of line meant (don't copy it): %s" % (event.get("detail", "something happened"), event.get("example", "")) + if russian: + user += "\n(Answer in Russian.)" + try: + data = parse_json(api.chat(system, user, timeout=max(0.4, budget - (time.time() - started)), max_tokens=48)) + except (OSError, ValueError) as e: + log("raid line of %s: no line in time (%s); the server says its own" % (bot, e)) + return + say = str((data or {}).get("say", "")).strip().strip('"').replace("\n", " ")[:160] + if ":" in say[:24] and say.split(":", 1)[0].strip().lower() == bot.lower(): + say = say.split(":", 1)[1].strip() + say, why = check_line(say, swearing) + if why: + log("raid line of %s %s" % (bot, why)) + if not say or (russian and not mostly_cyrillic(say)): + return + took = time.time() - started + if took > budget: + log("raid line of %s came after %.1f s; the server says its own" % (bot, took)) + return + delay = max(0, int(event.get("delay_ms", 0) or 0) - int(took * 1000)) + write_reply(event["_folder"], {"reply_to": event["id"], "say": say, "channel": event.get("channel", "raid"), "delay_ms": delay}) + log("%s [raid %s, %.1f s]: %s" % (bot, event.get("what", ""), took, say)) + + +def safe_raid_line(event, api, opts): + try: + answer_raid_line(event, api, opts) + except Exception as e: # a raid line is never worth stopping the program for; the server says its fixed line + log("raid line for %s failed: %r" % (event.get("bot"), e)) + + def safe_talk(event, api, minds, opts): try: answer_talk(event, api, minds, opts) @@ -1314,6 +1373,13 @@ def main(): continue e["_seen"], e["_folder"] = time.time(), folder pending.add(pool.submit(safe_talk, e, api, minds, opts)) + elif kind == "raid_line": + # A raid line has 2.5 s or the server says its fixed one: only when the model is free right now. + pending = {p for p in pending if not p.done()} + if len(pending) >= opts.workers: + continue + e["_seen"], e["_folder"] = time.time(), folder + pending.add(pool.submit(safe_raid_line, e, api, opts)) elif kind == "action_result": log("action %s for %s: %s" % (e.get("act"), e.get("bot"), "done, " + e.get("detail", "") if e.get("ok") else "refused, " + e.get("why", ""))) diff --git a/tests/game/ClassicBossWarnings.cpp b/tests/game/ClassicBossWarnings.cpp index 63cfa255d6..8fc892b1ec 100644 --- a/tests/game/ClassicBossWarnings.cpp +++ b/tests/game/ClassicBossWarnings.cpp @@ -20,6 +20,7 @@ #include "../../src/modules/PlayerbotV2/Bot/Raid/BossWarningData_MC.h" #include "../../src/modules/PlayerbotV2/Bot/Raid/RaidCallouts.h" #include "../../src/modules/PlayerbotV2/Bot/Raid/BossTactics.h" +#include "../../src/modules/PlayerbotV2/Bot/Raid/RaidBanter.h" using namespace Playerbot::Raid; namespace CcDeny = Playerbot::CcDeny; @@ -330,3 +331,102 @@ TEST_CASE("Raid callout: rate limits per bot and per raid", "[ClassicBossWarning cap.Prune(t + 200000); CHECK(cap.Tracked() == 0); } + +TEST_CASE("Raid banter: the leader's lines", "[ClassicBossWarnings]") +{ + CHECK(LeaderLine(Mishap::StoodInBad, BanterLevel::Off, "Karrz", 0).empty()); + CHECK(LeaderLine(Mishap::Count, BanterLevel::Harsh, "Karrz", 0).empty()); + CHECK(LeaderLine(Mishap::StoodInBad, BanterLevel::Mild, "Karrz", 0) == "Karrz, out of the bad stuff pls"); + CHECK(LeaderLine(Mishap::StoodInBad, BanterLevel::Harsh, "Karrz", 0) == "Karrz GET OUT OF IT"); + CHECK(LeaderLine(Mishap::MissedKick, BanterLevel::Harsh, "Shadow Bolt", 0) == "NOBODY KICKED Shadow Bolt??"); + CHECK(LeaderLine(Mishap::BrokeCc, BanterLevel::Mild, "Gun", 1) == "careful Gun, that was cc'd"); + CHECK(LeaderLine(Mishap::BrokeCc, BanterLevel::Harsh, "", 0) == "WHO BROKE THE CC"); // nobody seen: the nameless lines + CHECK(LeaderLine(Mishap::ExtraPull, BanterLevel::Mild, "", 2) == "adds incoming, tanks"); + CHECK(LeaderLine(Mishap::ExtraPull, BanterLevel::Harsh, "Brok", 1) == "Brok has adds, tanks GRAB THEM"); + // A wipe or a kill with nobody to name skips the lines that need a name. + CHECK(LeaderLine(Mishap::Wipe, BanterLevel::Mild, "", 2) == "wipe, it happens. run back and rebuff"); + CHECK(LeaderLine(Mishap::Wipe, BanterLevel::Harsh, "", 0) == "that was a mess. run back and stay out of the bad stuff"); + CHECK(LeaderLine(Mishap::Wipe, BanterLevel::Harsh, "Brok", 0) == "WIPE. Brok died first. again"); + CHECK(LeaderLine(Mishap::BossDown, BanterLevel::Mild, "", 2) == "gg, nice one everyone"); + CHECK(LeaderLine(Mishap::BossDown, BanterLevel::Harsh, "Brok", 2) == "gg. Brok, we'll talk about dying later"); + + // Standing in the bad stuff and a missed kick are always about someone (a raider, a spell): no line without the name. + CHECK(LeaderLine(Mishap::StoodInBad, BanterLevel::Mild, "", 0).empty()); + CHECK(LeaderLine(Mishap::MissedKick, BanterLevel::Harsh, "", 1).empty()); + + // Every line, every pick: never empty when on (a name is there, or the mishap has nameless lines), never a leftover slot. + for (uint8_t m = 0; m < uint8_t(Mishap::Count); ++m) + for (BanterLevel l : { BanterLevel::Mild, BanterLevel::Harsh }) + for (uint32_t pick = 0; pick < 6; ++pick) + for (char const* name : { "", "Brok" }) + { + std::string const s = LeaderLine(Mishap(m), l, name, pick); + INFO(int(m) << " " << int(l) << " " << pick << " " << name); + bool const needsName = Mishap(m) == Mishap::StoodInBad || Mishap(m) == Mishap::MissedKick; + CHECK(s.empty() == (needsName && !*name)); + CHECK(s.find("{}") == std::string::npos); + } +} + +TEST_CASE("Raid banter: after a wipe", "[ClassicBossWarnings]") +{ + CHECK(WipeReply(BanterLevel::Off, "Brok", false, 0).empty()); + CHECK(WipeReply(BanterLevel::Mild, "Brok", true, 0) == "my bad"); + CHECK(WipeReply(BanterLevel::Harsh, "Brok", true, 3) == "i was rooted ok"); + CHECK(WipeReply(BanterLevel::Harsh, "Brok", false, 0) == "that was Brok's fault"); + CHECK(WipeReply(BanterLevel::Mild, "", false, 5) == "healers?"); // no one to blame: the next nameless line + for (BanterLevel l : { BanterLevel::Mild, BanterLevel::Harsh }) + for (uint32_t pick = 0; pick < 14; ++pick) + for (char const* blame : { "", "Brok" }) + { + std::string const s = WipeReply(l, blame, false, pick); + CHECK_FALSE(s.empty()); + CHECK(s.find("{}") == std::string::npos); + } +} + +TEST_CASE("Raid banter: what the program is told", "[ClassicBossWarnings]") +{ + CHECK(MishapDetail(Mishap::StoodInBad, "Karrz", "Ragnaros") == "Karrz keeps standing in a damaging area (fighting Ragnaros)"); + CHECK(MishapDetail(Mishap::MissedKick, "Shadow Bolt", "") == "nobody interrupted the enemy cast Shadow Bolt"); + CHECK(MishapDetail(Mishap::BrokeCc, "", "") == "someone broke a crowd-controlled enemy early"); + CHECK(MishapDetail(Mishap::ExtraPull, "Brok", "") == "an extra pack of enemies was pulled into the fight, they attack Brok"); + CHECK(MishapDetail(Mishap::Wipe, "Brok", "Lucifron") == "the raid just wiped (fighting Lucifron); Brok died first"); + CHECK(MishapDetail(Mishap::BossDown, "", "Lucifron") == "the raid just killed the boss Lucifron"); + CHECK(MishapDetail(Mishap::BossDown, "Brok", "Lucifron") == "the raid just killed the boss Lucifron; Brok died during the fight"); + CHECK(std::string(MishapWord(Mishap::BrokeCc)) == "broke_cc"); + CHECK(std::string(MishapWord(Mishap::Count)) == "mishap"); +} + +TEST_CASE("Raid banter: config and rate limits", "[ClassicBossWarnings]") +{ + CHECK((BanterLevelFromConfig(0) == BanterLevel::Off)); + CHECK((BanterLevelFromConfig(-3) == BanterLevel::Off)); + CHECK((BanterLevelFromConfig(1) == BanterLevel::Mild)); + CHECK((BanterLevelFromConfig(2) == BanterLevel::Harsh)); + CHECK((BanterLevelFromConfig(9) == BanterLevel::Harsh)); + CHECK(std::string(BanterLevelWord(BanterLevel::Harsh)) == "harsh"); + + uint32_t const t = 100000; + BanterGate g; + CHECK_FALSE(g.Allow(1, Mishap::StoodInBad, "Karrz", BanterLevel::Off, t)); + CHECK(g.Allow(1, Mishap::StoodInBad, "Karrz", BanterLevel::Mild, t)); + CHECK_FALSE(g.Allow(1, Mishap::MissedKick, "Bolt", BanterLevel::Mild, t + 5000)); // leader gap + CHECK(g.Allow(2, Mishap::MissedKick, "Bolt", BanterLevel::Mild, t + 5000)); // another raid + CHECK(g.Allow(1, Mishap::MissedKick, "Bolt", BanterLevel::Mild, t + BanterGate::kLeaderGapMs)); + CHECK_FALSE(g.Allow(1, Mishap::StoodInBad, "Gun", BanterLevel::Mild, t + BanterGate::kLeaderGapMs * 2)); // same kind + CHECK(g.Allow(1, Mishap::StoodInBad, "Gun", BanterLevel::Mild, t + BanterGate::kSameKindMs)); + CHECK_FALSE(g.Allow(1, Mishap::StoodInBad, "Karrz", BanterLevel::Mild, t + 2 * BanterGate::kSameKindMs - 1000)); + CHECK(g.Allow(1, Mishap::StoodInBad, "Karrz", BanterLevel::Mild, t + BanterGate::kSameNameMs + 1000)); // same raider, later + + // Harsh speaks more often; the wipe and the kill always get their line, once per fight end. + BanterGate h; + CHECK(h.Allow(3, Mishap::StoodInBad, "A", BanterLevel::Harsh, t)); + CHECK(h.Allow(3, Mishap::BrokeCc, "B", BanterLevel::Harsh, t + BanterGate::kLeaderGapHarshMs)); + CHECK(h.Allow(3, Mishap::Wipe, "", BanterLevel::Harsh, t + BanterGate::kLeaderGapHarshMs + 500)); + CHECK_FALSE(h.Allow(3, Mishap::BossDown, "", BanterLevel::Harsh, t + BanterGate::kLeaderGapHarshMs + 900)); + CHECK(h.Allow(3, Mishap::BossDown, "", BanterLevel::Harsh, t + BanterGate::kLeaderGapHarshMs + 500 + BanterGate::kFightEndMs)); + + h.Prune(t + 500000); + CHECK(h.Tracked() == 0); +} diff --git a/tests/game/ClassicBotLocale.cpp b/tests/game/ClassicBotLocale.cpp index 6d436698df..f3f3927f0c 100644 --- a/tests/game/ClassicBotLocale.cpp +++ b/tests/game/ClassicBotLocale.cpp @@ -20,6 +20,7 @@ #ifdef TESTS_HAVE_PLAYERBOT_V2 #include "../../src/modules/PlayerbotV2/Util/BotLocaleText.h" +#include "../../src/modules/PlayerbotV2/Bot/Raid/RaidBanter.h" #include #include @@ -127,6 +128,38 @@ TEST_CASE("BotLocale: raid callouts", "[BotLocale]") CHECK(Translate(Lang::Ru, "wipe, run back to the entrance") == "вайп, бегите ко входу"); } +TEST_CASE("BotLocale: raid leader banter", "[BotLocale]") +{ + using namespace Playerbot::Raid; + CHECK(Translate(Lang::Ru, "Karrz GET OUT OF IT") == "Karrz, ВЫЙДИ ОТТУДА"); + CHECK(Translate(Lang::Ru, "NOBODY KICKED Shadow Bolt??") == "НИКТО НЕ СБИЛ Shadow Bolt??"); + CHECK(Translate(Lang::Ru, "WIPE. Brok died first. again") == "ВАЙП. Brok - опять первый труп"); + CHECK(Translate(Lang::Ru, "that was Brok's fault") == "это вина Brok"); + CHECK(Translate(Lang::Ru, "i was rooted ok") == "меня зарутило, ок"); + + // Every fixed line the leader or a raider can say has its Russian form. + Catalog const& ru = Russian(); + for (uint8_t m = 0; m < uint8_t(Mishap::Count); ++m) + for (BanterLevel l : { BanterLevel::Mild, BanterLevel::Harsh }) + for (uint32_t pick = 0; pick < 3; ++pick) + for (char const* name : { "", "Brok" }) + { + std::string const s = LeaderLine(Mishap(m), l, name, pick); + INFO(s); + CHECK((s.empty() || ru.Knows(s))); + } + for (BanterLevel l : { BanterLevel::Mild, BanterLevel::Harsh }) + for (uint32_t pick = 0; pick < 8; ++pick) + for (char const* blame : { "", "Brok" }) + for (bool self : { false, true }) + { + std::string const s = WipeReply(l, blame, self, pick); + INFO(s); + CHECK_FALSE(s.empty()); + CHECK(ru.Knows(s)); + } +} + TEST_CASE("BotLocale: boss tactics answers", "[BotLocale]") { CHECK(Translate(Lang::Ru, "Tactics for Lucifron: adds first, no AoE, tank at your spot. Your bots use them every time you fight Lucifron.")