Skip to content

Minh/discord hook embed - #71

Closed
minhh2792 wants to merge 4 commits into
masterfrom
minh/discord-hook-embed
Closed

Minh/discord hook embed#71
minhh2792 wants to merge 4 commits into
masterfrom
minh/discord-hook-embed

Conversation

@minhh2792

@minhh2792 minhh2792 commented Oct 12, 2025

Copy link
Copy Markdown
Member

idk
do this later

Summary by CodeRabbit

  • New Features
    • Rich Discord webhook payloads with embeds, author/footer, images, fields, and username/avatar support.
    • New %TIME% placeholder in notifications.
    • Added “cleardata” admin command to purge a player’s milestone/donation totals.
  • Refactor
    • Consolidated placeholder handling and switched to payload-based sending for webhooks.
  • Chores
    • Updated Discord configuration to a structured, payload-based format.

@minhh2792 minhh2792 self-assigned this Oct 12, 2025
@coderabbitai

coderabbitai Bot commented Oct 12, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors Discord notification system to use structured payloads with embeds and placeholder replacement, adds timestamp support in DotMan flow, introduces an admin subcommand to clear milestone data via DAO, and extends DAOs (H2/MySQL) with a delete-by-key-like operation. Updates Discord YAML to the new payload-based configuration.

Changes

Cohort / File(s) Summary
Discord payload refactor
dotman-plugin/src/main/java/net/minevn/dotman/config/Discord.kt, dotman-plugin/src/main/resources/discord.yml
Replaces simple webhook content with structured payloads (content, username, avatar, embeds). Adds mapping from YAML to payload, placeholder application, color parsing, serialization, and sending logic. Updates config to payload-based format.
Notification flow update
dotman-plugin/src/main/java/net/minevn/dotman/DotMan.kt
Adds timestamp generation and consolidates message placeholders into a map, sending replacements to each webhook instead of per-hook content assembly.
Admin command for data clearing
dotman-plugin/src/main/java/net/minevn/dotman/commands/AdminCmd.kt
Adds “cleardata” subcommand to delete player milestone/donation data by key pattern within a transaction; includes tab completion and messaging.
DAO extension (API + H2 + MySQL)
dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt, .../database/h2/PlayerDataDAOImpl.kt, .../database/mysql/PlayerDataDAOImpl.kt
Introduces delete-by-key-like capability via an abstract script getter and a concrete method executing DELETE with uuid and LIKE pattern; implements scripts for H2/MySQL.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Game as Game Logic
  participant DotMan as DotMan
  participant DiscordCfg as Discord.Config
  participant WebHook as WebHook (payload)
  participant Discord as Discord API

  Game->>DotMan: Donation processed
  DotMan->>DotMan: Build replacements (PLAYER, AMOUNT, ..., TIME)
  DotMan->>DiscordCfg: Get active WebHooks
  loop For each WebHook
    DotMan->>WebHook: send(replacements)
    WebHook->>WebHook: Apply replacements to payload/embeds
    WebHook->>Discord: POST JSON payload
    Discord-->>WebHook: 2xx/4xx/5xx
    WebHook-->>DotMan: Result (log on error)
  end
Loading
sequenceDiagram
  autonumber
  participant Admin as Admin
  participant Cmd as AdminCmd
  participant DAO as PlayerDataDAO
  participant DB as Database

  Admin->>Cmd: /dotman cleardata <player>
  Cmd->>DAO: Lookup UUID (via PlayerInfoDAO)
  alt UUID found
    Cmd->>DAO: deleteDataByKeyLike(uuid, "DONATE_TOTAL_ALL%")
    DAO->>DB: DELETE ... WHERE uuid=? AND key LIKE ?
    DB-->>DAO: affected rows
    DAO-->>Cmd: count
    Cmd-->>Admin: Report success with count
  else UUID not found
    Cmd-->>Admin: Player not found
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I thump the keys with gentle might,
New webhooks bloom in structured light.
A clock now ticks in every send—
Embeds parade, placeholders blend.
With broom-like SQL, I sweep the slate,
Clear milestones clean—don’t make me wait.
Hippity-hop, we iterate!

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The title “Minh/discord hook embed” includes a branch or author prefix and is a fragment rather than a clear, concise sentence summarizing the core change of adding embed support to Discord webhooks. It partially reflects the work on Discord embeds but is cluttered and not immediately understandable as the primary enhancement made in the PR. Please rename the pull request to a concise sentence that clearly describes the main change, for example “Add embed support to Discord webhooks,” and remove any branch or author prefixes.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch minh/discord-hook-embed

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@minhh2792 minhh2792 added the feat label Oct 12, 2025
@minhh2792

Copy link
Copy Markdown
Member Author

bị dính commit khác
tối fix

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt (1)

73-79: Align update execution method and verify DSL support

This block uses update(), while other writes here use executeUpdate(). For consistency (and to avoid potential missing-DSL issues), prefer executeUpdate() unless update() is a known helper.

Suggested change:

-        return deleteDataByKeyLikeScript().statement {
+        return deleteDataByKeyLikeScript().statement {
             setString(1, uuid)
             setString(2, likePattern)
-            update()
+            executeUpdate()
         }

If update() is intentionally provided by your DataAccess DSL, please confirm and ignore this change. Otherwise, switching to executeUpdate() avoids compile/runtime surprises.

dotman-plugin/src/main/java/net/minevn/dotman/DotMan.kt (1)

148-161: Discord replacements flow looks solid

Async, complete replacements, and TIME added correctly.

To avoid re-creating the formatter on each call, cache it:

-import java.time.format.DateTimeFormatter
+import java.time.format.DateTimeFormatter
+// ...
+private val TIME_FMT: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss dd/MM/yyyy")
 // ...
-            val timeStr = LocalDateTime.now()
-                .format(DateTimeFormatter.ofPattern("HH:mm:ss dd/MM/yyyy"))
+            val timeStr = LocalDateTime.now().format(TIME_FMT)
dotman-plugin/src/main/java/net/minevn/dotman/config/Discord.kt (1)

58-64: Avoid relying on a Throwable.warning extension

Use the existing warning(...) helper directly to prevent a potential missing-extension compile issue.

-        runCatching { post(url, "application/json", json) }
-            .onFailure { it.warning("Discord webhook failed") }
+        runCatching { post(url, "application/json", json) }
+            .onFailure { warning("Discord webhook failed: ${it.message}") }

If you do have an extension fun Throwable.warning(...), feel free to keep it; otherwise this change is safer.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3852219 and 6f5303a.

📒 Files selected for processing (7)
  • dotman-plugin/src/main/java/net/minevn/dotman/DotMan.kt (2 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/commands/AdminCmd.kt (3 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/config/Discord.kt (1 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt (2 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/database/h2/PlayerDataDAOImpl.kt (1 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/database/mysql/PlayerDataDAOImpl.kt (1 hunks)
  • dotman-plugin/src/main/resources/discord.yml (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt (2)
dotman-plugin/src/main/java/net/minevn/dotman/database/h2/PlayerDataDAOImpl.kt (1)
  • deleteDataByKeyLikeScript (51-54)
dotman-plugin/src/main/java/net/minevn/dotman/database/mysql/PlayerDataDAOImpl.kt (1)
  • deleteDataByKeyLikeScript (44-47)
dotman-plugin/src/main/java/net/minevn/dotman/commands/AdminCmd.kt (2)
dotman-plugin/src/main/java/net/minevn/dotman/utils/Utils.kt (1)
  • runNotSync (50-60)
dotman-plugin/src/main/java/net/minevn/dotman/DotMan.kt (1)
  • transactional (168-173)
🪛 YAMLlint (1.37.1)
dotman-plugin/src/main/resources/discord.yml

[error] 1-1: wrong new line character: expected \n

(new-lines)

🔇 Additional comments (4)
dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt (1)

17-17: Abstract delete-by-LIKE script looks good

Consistent with existing DAO script pattern; enables per‑DB impls cleanly.

dotman-plugin/src/main/java/net/minevn/dotman/database/h2/PlayerDataDAOImpl.kt (1)

51-54: H2 delete-by-LIKE SQL is correct and safe

Parameterized, quoted identifiers, matches DAO contract.

dotman-plugin/src/main/java/net/minevn/dotman/database/mysql/PlayerDataDAOImpl.kt (1)

44-47: MySQL delete-by-LIKE SQL is correct and safe

Parameterized, backticked identifiers, consistent with H2 impl.

dotman-plugin/src/main/java/net/minevn/dotman/commands/AdminCmd.kt (1)

319-360: Clearing milestone data command is well‑wired

Async + transactional usage is correct; DAO call fits the new delete-by-LIKE API.

Confirm that "DONATE_TOTAL_ALL%" covers all relevant milestone keys in your schema (e.g., suffixes/namespacing). If weekly/monthly or other related keys should be cleared too, consider broadening to "DONATE_TOTAL_%".

Comment on lines +1 to +48
# Cấu hình Discord Webhook cho DotMan
# - Chỉ hỗ trợ payload đầy đủ (bao gồm embed). Không còn hỗ trợ cấu hình cũ chỉ text.
# - Trường enabled mặc định là true nếu không khai báo. Đặt false để tạm tắt webhook.
# - Có thể sử dụng placeholder sau trong content/embeds:
# %PLAYER%, %AMOUNT%, %POINT_AMOUNT%, %POINT_UNIT%, %BALANCE%, %METHOD%, %TIME%
# - Màu (color) phải là chuỗi hex dạng "#RRGGBB" (ví dụ: "#58b9ff"). Nếu sai định dạng sẽ tự chuyển về trắng "#FFFFFF".
# Bạn có thể dùng https://discohook.org/ để thiết kế

discord-hooks:
- enabled: false
url: https://discord.com/api/webhooks/123456/webhook-token
content: |
## Nạp thẻ
**%PLAYER%** vừa nạp **%AMOUNT% VNĐ**
Nhận được: %POINT_AMOUNT% %POINT_UNIT%
Số dư sau khi nạp: %BALANCE% %POINT_UNIT%
Hình thức nạp: %METHOD%
payload:
username: "MineVN"
avatarUrl: "https://i.imgur.com/tdZ2LxY.png"
content:
- "Thông báo nạp tiền thành công!"
- "Thời gian: %TIME%"

embeds:
- title: "Ting ting 💸"
description:
- "Xin cảm ơn bạn đã ủng hộ server!"
color: "#58b9ff"
fields:
- name: "Người chơi"
value: "%PLAYER%"
inline: true
- name: "Số tiền"
value: "%AMOUNT% VNĐ"
inline: true
- name: "Thực nhận"
value: "%POINT_AMOUNT% %POINT_UNIT% (đang có %BALANCE% %POINT_UNIT%)"
inline: true
- name: "Phương thức"
value: "%METHOD%"
inline: true

image:
url: "https://i.imgur.com/4g5sEWu.png"
thumbnail:
url: "https://i.imgur.com/tdZ2LxY.png"
author:
name: "MineVN"
url: "https://minevn.studio/"
iconUrl: "https://i.imgur.com/tdZ2LxY.png"
footer:
text: "%TIME%"
iconUrl: "https://i.imgur.com/tdZ2LxY.png" No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

Fix newline style to LF; YAML linter error

File appears to use CRLF. Convert to LF to satisfy tooling.

Add to .gitattributes to enforce:

*.yml text eol=lf
*.yaml text eol=lf

Run to detect CRs:


🏁 Script executed:

#!/bin/bash
rg -nU '\r$' dotman-plugin/src/main/resources/discord.yml || true

Length of output: 1887


Convert discord.yml to LF line endings

All 47 lines in dotman-plugin/src/main/resources/discord.yml end with CRLF, causing YAML lint errors. Convert the file to LF (dos2unix dotman-plugin/src/main/resources/discord.yml or git add --renormalize). Enforce LF in the repo by adding to .gitattributes:

*.yml text eol=lf
*.yaml text eol=lf
🧰 Tools
🪛 YAMLlint (1.37.1)

[error] 1-1: wrong new line character: expected \n

(new-lines)

🤖 Prompt for AI Agents
In dotman-plugin/src/main/resources/discord.yml around lines 1 to 48, the file
currently uses CRLF line endings which cause YAML lint errors; convert the file
to LF line endings (e.g., run dos2unix
dotman-plugin/src/main/resources/discord.yml or git add --renormalize after
setting core.autocrlf appropriately) and commit the change, and enforce LF in
the repository by adding a .gitattributes entry for *.yml and *.yaml with text
eol=lf so future commits normalize to LF.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
dotman-plugin/src/main/java/net/minevn/dotman/DotMan.kt (1)

148-160: Cache the formatter?

Constructing DateTimeFormatter.ofPattern(...) on every notification allocates repeatedly. Consider promoting it to a private val (e.g. in companion object) and reuse it for these updates. Optional polish, but it avoids churn under heavy load.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3852219 and 10b6500.

📒 Files selected for processing (7)
  • dotman-plugin/src/main/java/net/minevn/dotman/DotMan.kt (2 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/commands/AdminCmd.kt (3 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/config/Discord.kt (1 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt (2 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/database/h2/PlayerDataDAOImpl.kt (1 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/database/mysql/PlayerDataDAOImpl.kt (1 hunks)
  • dotman-plugin/src/main/resources/discord.yml (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt (2)
dotman-plugin/src/main/java/net/minevn/dotman/database/h2/PlayerDataDAOImpl.kt (1)
  • deleteDataByKeyLikeScript (51-54)
dotman-plugin/src/main/java/net/minevn/dotman/database/mysql/PlayerDataDAOImpl.kt (1)
  • deleteDataByKeyLikeScript (44-47)
dotman-plugin/src/main/java/net/minevn/dotman/commands/AdminCmd.kt (2)
dotman-plugin/src/main/java/net/minevn/dotman/utils/Utils.kt (1)
  • runNotSync (50-60)
dotman-plugin/src/main/java/net/minevn/dotman/DotMan.kt (1)
  • transactional (168-173)
🪛 YAMLlint (1.37.1)
dotman-plugin/src/main/resources/discord.yml

[error] 1-1: wrong new line character: expected \n

(new-lines)

🔇 Additional comments (5)
dotman-plugin/src/main/java/net/minevn/dotman/database/h2/PlayerDataDAOImpl.kt (1)

51-54: SQL matches the new DAO contract.

H2 variant lines up with the abstract delete-by-key-like API and mirrors the MySQL query shape. Nicely done.

dotman-plugin/src/main/java/net/minevn/dotman/database/mysql/PlayerDataDAOImpl.kt (1)

44-47: MySQL delete script aligns with the new DAO method.

Matches the H2 implementation and fulfills the new delete-by-key-like contract with proper quoting.

dotman-plugin/src/main/java/net/minevn/dotman/commands/AdminCmd.kt (1)

319-359: Command flow looks solid.

Argument handling, UUID lookup, and transactional deletion all line up with the new DAO capability; good addition to the admin toolkit.

dotman-plugin/src/main/java/net/minevn/dotman/database/PlayerDataDAO.kt (1)

73-79: DAO helper is wired correctly.

Binding uuid and pattern then delegating to the driver script keeps things consistent with the existing statement helpers.

dotman-plugin/src/main/java/net/minevn/dotman/config/Discord.kt (1)

68-75: Config-to-webhook mapping checks out.

Filtering disabled entries and enforcing payload presence should keep runtime surprises away—nice defensive mapping.

@@ -1,12 +1,48 @@
# Bạn có thể thêm nhiều discord webhook url cùng lúc.
# Điều chỉnh enabled thành true để bật
# Cấu hình Discord Webhook cho DotMan

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fix newline style for lint compliance.

YAMLlint reports wrong newline characters (expects \n, sees \r\n). Please convert the file to Unix LF endings so CI passes. Based on static analysis hints.

🧰 Tools
🪛 YAMLlint (1.37.1)

[error] 1-1: wrong new line character: expected \n

(new-lines)

🤖 Prompt for AI Agents
In dotman-plugin/src/main/resources/discord.yml around lines 1 to 1, the file
uses Windows CRLF line endings which YAML lint flags; convert the file to use
Unix LF line endings throughout (replace \r\n with \n), ensure the editor/git
config preserves LF (e.g., set .gitattributes or core.autocrlf appropriately),
and re-save/commit the file so CI passes.

@minhh2792 minhh2792 closed this Oct 12, 2025
@minhh2792
minhh2792 deleted the minh/discord-hook-embed branch October 12, 2025 17:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant