Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Tarot card drawing logic for daily user draws #98

Open
wants to merge 1 commit into
base: v3
Choose a base branch
from

Conversation

g1331
Copy link
Owner

@g1331 g1331 commented Feb 17, 2025

Enhance the Tarot plugin to support daily card draws for users, recording their results to prevent duplicate draws on the same day.

好的,这是翻译成中文的 pull request 总结:

Sourcery 总结

实现每日塔罗牌抽牌功能,存储结果以防止同一天重复抽牌。如果用户尝试在同一天再次抽牌,则显示之前的结果。

新功能:

  • 为用户实现每日塔罗牌抽牌功能,存储他们的抽牌结果以防止同一天重复抽牌。
  • 如果用户今天已经抽过牌,则在消息中显示“[重复]”,并再次显示之前的结果。
Original summary in English

Summary by Sourcery

Implement daily Tarot card draws, storing results to prevent duplicate draws on the same day. Display previous results if a user attempts to draw again on the same day.

New Features:

  • Implement daily Tarot card draws for users, storing their draw results to prevent duplicates within the same day.
  • Display "[Duplicate]" in the message if the user has already drawn a card today, and show the previous result again.

Copy link
Contributor

sourcery-ai bot commented Feb 17, 2025

## Sourcery 提供的审查者指南

此 Pull Request 引入了每日塔罗牌抽取功能。它存储用户当天的抽取结果,如果用户在同一天尝试再次抽取,则返回相同的牌。该实现涉及存储用户特定的卡牌抽取信息,检查现有的抽取结果,并在可用时返回存储的卡牌。

#### Tarot 的更新类图

```mermaid
classDiagram
    class Tarot {
        - _user_draws: Dict[int, Tuple[str, dict, str]]
        + get_tarot(user_id: int) MessageChain
        + get_random_tarot() Tuple[dict, str]
    }
    note for Tarot "存储用户每日结果: {user_id: (date, card_info, filename)}"

文件级别变更

变更 详情 文件
实现了用户的每日塔罗牌抽取功能,防止同一天多次抽取。
  • 添加了一个字典 _user_draws 来存储用户每日的卡牌抽取结果。
  • 修改了 get_tarot 以检查用户今天是否已经抽取过卡牌。
  • 如果用户今天已经抽取过卡牌,则返回之前的结果。
  • 如果用户今天还没有抽取过卡牌,则抽取一张新卡并存储结果。
  • 添加了 sender 参数到 tarot 函数以获取用户 ID。
  • 添加了卡牌信息的当前含义。
modules/self_contained/tarot/__init__.py

提示和命令

与 Sourcery 互动

  • 触发新的审查: 在 Pull Request 上评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审查评论。
  • 从审查评论生成 GitHub Issue: 通过回复审查评论,要求 Sourcery 从该评论创建一个 Issue。您也可以回复审查评论并使用 @sourcery-ai issue 从该评论创建一个 Issue。
  • 生成 Pull Request 标题: 在 Pull Request 标题中的任何位置写入 @sourcery-ai 以随时生成标题。您也可以在 Pull Request 上评论 @sourcery-ai title 以随时(重新)生成标题。
  • 生成 Pull Request 摘要: 在 Pull Request 正文中的任何位置写入 @sourcery-ai summary 以随时在您想要的位置生成 PR 摘要。您也可以在 Pull Request 上评论 @sourcery-ai summary 以随时(重新)生成摘要。
  • 生成审查者指南: 在 Pull Request 上评论 @sourcery-ai guide 以随时(重新)生成审查者指南。
  • 解决所有 Sourcery 评论: 在 Pull Request 上评论 @sourcery-ai resolve 以解决所有 Sourcery 评论。如果您已经处理了所有评论并且不想再看到它们,这将非常有用。
  • 驳回所有 Sourcery 审查: 在 Pull Request 上评论 @sourcery-ai dismiss 以驳回所有现有的 Sourcery 审查。如果您想从一个新的审查开始,这将特别有用 - 不要忘记评论 @sourcery-ai review 以触发新的审查!
  • 为 Issue 生成行动计划: 在 Issue 上评论 @sourcery-ai plan 以为其生成行动计划。

自定义您的体验

访问您的 仪表板 以:

  • 启用或禁用审查功能,例如 Sourcery 生成的 Pull Request 摘要、审查者指南等。
  • 更改审查语言。
  • 添加、删除或编辑自定义审查说明。
  • 调整其他审查设置。

获取帮助

```
Original review guide in English

Reviewer's Guide by Sourcery

This pull request introduces a daily Tarot card draw feature. It stores the user's draw for the day and returns the same card if they try to draw again on the same day. The implementation involves storing user-specific card draw information, checking for existing draws, and returning the stored card if available.

Updated class diagram for Tarot

classDiagram
    class Tarot {
        - _user_draws: Dict[int, Tuple[str, dict, str]]
        + get_tarot(user_id: int) MessageChain
        + get_random_tarot() Tuple[dict, str]
    }
    note for Tarot "Stores user daily results: {user_id: (date, card_info, filename)}"
Loading

File-Level Changes

Change Details Files
Implemented daily Tarot card draws for users, preventing multiple draws on the same day.
  • Added a dictionary _user_draws to store user's daily card draw results.
  • Modified get_tarot to check if the user has already drawn a card today.
  • If the user has drawn a card today, return the previous result.
  • If the user hasn't drawn a card today, draw a new card and store the result.
  • Added the sender parameter to the tarot function to get the user ID.
  • Added the current meaning to the card information.
modules/self_contained/tarot/__init__.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

@g1331 - 我已经审查了你的更改 - 这里有一些反馈:

总体评论

  • 考虑将 _user_draws 持久化到文件中,以便每日抽奖可以在机器人重启后继续存在。
这是我在审查期间查看的内容
  • 🟡 一般问题:发现 3 个问题
  • 🟢 安全性:一切看起来都不错
  • 🟢 测试:一切看起来都不错
  • 🟢 复杂性:一切看起来都不错
  • 🟢 文档:一切看起来都不错

Sourcery 对开源是免费的 - 如果你喜欢我们的评论,请考虑分享它们 ✨
帮助我更有用! 请在每条评论上点击 👍 或 👎,我将使用反馈来改进你的评论。
Original comment in English

Hey @g1331 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider persisting _user_draws to a file so the daily draws persist across bot restarts.
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

card_type = "正位" if card_dir == "normal" else "逆位"
content = f"[重复] {card['name']} ({card['name-en']}) {card_type}\n牌意:{card['meaning'][card_dir]}"
elements = []
img_path = f"{os.getcwd()}/statics/tarot/{card_dir}/{filename}.jpg"
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: 考虑使用 pathlib 构建跨平台文件路径。

在所有平台上,将 os.getcwd() 与字符串连接使用可能并不稳健。 考虑使用 Path(file).parent / 'statics' / 'tarot' / card_dir / (filename + '.jpg') 构建文件路径。

建议的实施方式:

import os
from pathlib import Path
                img_path = str(Path(__file__).parent / 'statics' / 'tarot' / card_dir / (filename + '.jpg'))
Original comment in English

suggestion: Consider using pathlib for cross-platform file path construction.

Using os.getcwd() with string concatenation may not be robust on all platforms. Consider using Path(file).parent / 'statics' / 'tarot' / card_dir / (filename + '.jpg') to construct the file path.

Suggested implementation:

import os
from pathlib import Path
                img_path = str(Path(__file__).parent / 'statics' / 'tarot' / card_dir / (filename + '.jpg'))

@staticmethod
def get_tarot() -> MessageChain:
async def get_tarot(user_id: int) -> MessageChain:
Copy link
Contributor

Choose a reason for hiding this comment

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

question (bug_risk): 审查异步上下文中 _user_draws 的潜在并发问题。

由于 _user_draws 是从异步函数访问的类级别可变字典,请考虑并发访问是否可能导致竞争条件。 如果此代码并发执行,则简单的锁定机制或异步安全数据结构可能会有所帮助。

Original comment in English

question (bug_risk): Review potential concurrency issues with _user_draws in an async context.

Since _user_draws is a class-level mutable dictionary accessed from an async function, consider whether concurrent access might lead to race conditions. A simple locking mechanism or an async-safe data structure could help if this code is executed concurrently.

Comment on lines +52 to +61
if last_date == today:
card_dir = (
"normal"
if card["meaning"]["normal"] in card["meaning"].get("current", "")
else "reverse"
)
card_type = "正位" if card_dir == "normal" else "逆位"
content = f"[重复] {card['name']} ({card['name-en']}) {card_type}\n牌意:{card['meaning'][card_dir]}"
elements = []
img_path = f"{os.getcwd()}/statics/tarot/{card_dir}/{filename}.jpg"
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: 考虑将卡片方向显式存储在缓存中。

目前,重复的分支通过检查 card['meaning']['normal'] 是否在 card['meaning'].get('current', '') 中来推断卡片方向。 如果卡片文本发生更改,这种间接推断可能会容易出错。 将所选方向与卡片详细信息一起存储可以简化逻辑并提高未来的可维护性。

建议的实施方式:

    _user_draws: Dict[int, Tuple[str, dict, str, str]] = {}
        # Check if user already drew today
        if user_id in Tarot._user_draws:
            last_date, card, filename, card_dir = Tarot._user_draws[user_id]
            if last_date == today:
                card_type = "正位" if card_dir == "normal" else "逆位"
                content = f"[重复] {card['name']} ({card['name-en']}) {card_type}\n牌意:{card['meaning'][card_dir]}"
                elements = []
                img_path = f"{os.getcwd()}/statics/tarot/{card_dir}/{filename}.jpg"
                if filename and os.path.exists(img_path):
                    elements.append(Image(path=img_path))
                elements.append(Plain(text=content))
                return MessageChain(elements)
        # Draw new card
        card, filename = Tarot.get_random_tarot()
        card_dir = random.choice(["normal", "reverse"])
        card["meaning"]["current"] = card["meaning"][card_dir]  # Store current meaning
        Tarot._user_draws[user_id] = (today, card, filename, card_dir)

确保相应地更新代码中依赖于 _user_draws 结构的任何其他部分。

Original comment in English

suggestion: Consider storing the card orientation explicitly in the cache.

Currently, the repeated branch infers the card orientation by checking if card['meaning']['normal'] is in card['meaning'].get('current', ''). This indirect inference may be error prone if card texts change. Storing the chosen orientation alongside the card details could simplify the logic and improve future maintainability.

Suggested implementation:

    _user_draws: Dict[int, Tuple[str, dict, str, str]] = {}
        # Check if user already drew today
        if user_id in Tarot._user_draws:
            last_date, card, filename, card_dir = Tarot._user_draws[user_id]
            if last_date == today:
                card_type = "正位" if card_dir == "normal" else "逆位"
                content = f"[重复] {card['name']} ({card['name-en']}) {card_type}\n牌意:{card['meaning'][card_dir]}"
                elements = []
                img_path = f"{os.getcwd()}/statics/tarot/{card_dir}/{filename}.jpg"
                if filename and os.path.exists(img_path):
                    elements.append(Image(path=img_path))
                elements.append(Plain(text=content))
                return MessageChain(elements)
        # Draw new card
        card, filename = Tarot.get_random_tarot()
        card_dir = random.choice(["normal", "reverse"])
        card["meaning"]["current"] = card["meaning"][card_dir]  # Store current meaning
        Tarot._user_draws[user_id] = (today, card, filename, card_dir)

Ensure that any other parts of the code that rely on the structure of _user_draws are updated accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant