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

feat: Plugin football #2461

Merged
merged 14 commits into from
Jan 23, 2025
Merged

feat: Plugin football #2461

merged 14 commits into from
Jan 23, 2025

Conversation

suleigolden
Copy link
Contributor

Relates to

No specific issue or ticket linked.


Risks

Low Risk:

  • The plugin is self-contained and doesn't interfere with other parts of the system.
  • Only affects the plugin-football package, specifically the fetching of football data and its corresponding tests.

Background

What does this PR do?

This PR introduces the plugin-football, which integrates with the Football-Data.org API to provide live football match data and league standings. It includes:

  • New Features:
    • fetchMatchAction: Retrieves live match scores, teams, and key events.
    • fetchStandingsAction: Retrieves league standings for a specific competition.
  • Unit Tests:
    • Tests for fetchMatchAction and fetchStandingsAction using Vitest.
    • Mocked API responses for consistent and reliable testing.
  • Bug Fixes:
    • Correctly handles API key retrieval from environment variables.
    • Fixes API response parsing issues for edge cases.

What kind of change is this?

  • Features (non-breaking change which adds functionality)
  • Improvements (misc. changes to existing features)
  • Bug fixes (non-breaking change which fixes an issue)
  • Updates (new versions of included code)

Documentation changes needed?

  • My changes require a change to the project documentation.

The documentation should include:

  • How to configure the Football-Data.org API key in the .env file.

  • Examples of how to use fetchMatchAction and fetchStandingsAction.

  • My changes do not require a change to the project documentation.


Testing

Where should a reviewer start?

  1. Review the fetchMatchAction implementation in packages/plugin-football/src/actions/fetchMatchAction.ts.
  2. Review the fetchStandingsAction implementation in packages/plugin-football/src/actions/fetchStandingsAction.ts.
  3. Review the test suite in packages/plugin-football/src/tests/match-action.test.ts.

Detailed testing steps

  1. Setup:

    • Ensure the .env file contains the correct FOOTBALL_API_KEY.
    • Install dependencies using pnpm install.
  2. Run Tests:

    • Execute the test suite for the plugin:
      pnpm vitest packages/plugin-football/src/tests/match-action.test.ts
      pnpm vitest packages/plugin-football/src/tests/fetch-standings-action.test.ts
    • Verify that all tests pass.
  3. Manual Verification:

    • Use fetchMatchAction to fetch live match data from the Football-Data.org API.
    • Use fetchStandingsAction to retrieve league standings and verify the output.

Screenshots

Before

N/A (New feature)

After

N/A (New feature)


Deploy Notes

No special deployment steps are required. Ensure the .env file includes the FOOTBALL_API_KEY.


Database changes

None.


Deployment instructions

  1. Add the FOOTBALL_API_KEY to the .env file in the deployment environment.
  2. Restart the application if necessary to apply environment variable changes.

Discord username

N/A

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Hi @suleigolden! Welcome to the elizaOS community. Thanks for submitting your first pull request; your efforts are helping us accelerate towards AGI. We'll review it shortly. You are now an elizaOS contributor!

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces a new football plugin (@elizaos/plugin-football) to the ElizaOS agent ecosystem. The plugin enables fetching live football match scores, standings, and related data through dedicated actions. It includes comprehensive configuration files, TypeScript types, and test suites to ensure robust functionality. The plugin is integrated into the main agent configuration, allowing seamless data retrieval for football-related queries.

Changes

File Change Summary
agent/package.json Added @elizaos/plugin-football as a workspace dependency
agent/src/index.ts Imported footballPlugin and added to plugin list
packages/plugin-football/... New plugin package with:
- package.json configuration
- Actions for fetching matches and standings
- TypeScript types
- Test suites
- Build and lint configurations

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 11

🧹 Nitpick comments (7)
packages/plugin-football/src/types.ts (1)

1-10: Enhance type definitions for better type safety

Consider making the types more specific:

+export type MatchStatus = 'SCHEDULED' | 'LIVE' | 'FINISHED' | 'POSTPONED' | 'CANCELLED';
+
+export type MatchEvent = {
+    type: 'GOAL' | 'YELLOW_CARD' | 'RED_CARD' | 'SUBSTITUTION';
+    minute: number;
+    team: string;
+    player: string;
+};
+
 export type MatchData = {
     league: string;
     matches: Array<{
         homeTeam: string;
         awayTeam: string;
-        score: string;
-        status: string;
-        events: string[];
+        score: { home: number; away: number };
+        status: MatchStatus;
+        events: MatchEvent[];
     }>;
 };
packages/plugin-football/tsup.config.ts (1)

8-8: Fix misleading comment about module format

The comment suggests targeting CommonJS but the format is set to ESM.

-    format: ["esm"], // Ensure you're targeting CommonJS
+    format: ["esm"], // Output as ECMAScript modules
packages/plugin-football/src/actions/fetchStandingsAction.ts (1)

53-95: Update example responses to be more realistic

The example responses contain hard-coded team positions that might become outdated.

Consider using more generic examples that focus on the response format rather than specific team positions.

packages/plugin-football/src/tests/fetch-standings-action.test.ts (2)

40-90: Enhance test coverage for standings data validation.

The successful fetch test case could be more comprehensive:

  1. Add assertions for the structure of the standings data
  2. Test edge cases like empty standings or malformed team data
 it("should fetch standings successfully", async () => {
     global.fetch = vi.fn(() =>
         Promise.resolve({
             ok: true,
             json: () =>
                 Promise.resolve({
                     standings: [
                         {
                             table: [
                                 {
                                     position: 1,
                                     team: { name: "Manchester City" },
                                     points: 45,
+                                    played: 20,
+                                    won: 14,
+                                    draw: 3,
+                                    lost: 3,
+                                    goalsFor: 45,
+                                    goalsAgainst: 21,
                                 },
                             ],
                         },
                     ],
                 }),
         })
     ) as any;

     const result = await fetchStandingsAction.handler(
         mockRuntime,
         {} as Memory,
         {} as State
     );
     expect(result).toEqual({
         standings: [
             {
                 table: [
                     {
                         position: 1,
                         team: { name: "Manchester City" },
                         points: 45,
+                        played: 20,
+                        won: 14,
+                        draw: 3,
+                        lost: 3,
+                        goalsFor: 45,
+                        goalsAgainst: 21,
                     },
                 ],
             },
         ],
     });
+    // Validate data structure
+    expect(result.standings[0].table[0]).toHaveProperty('played');
+    expect(result.standings[0].table[0]).toHaveProperty('won');
+    expect(result.standings[0].table[0]).toHaveProperty('lost');
 });

+it("should handle empty standings gracefully", async () => {
+    global.fetch = vi.fn(() =>
+        Promise.resolve({
+            ok: true,
+            json: () => Promise.resolve({ standings: [] })
+        })
+    ) as any;
+
+    const result = await fetchStandingsAction.handler(
+        mockRuntime,
+        {} as Memory,
+        {} as State
+    );
+    expect(result.standings).toEqual([]);
+});

92-106: Enhance error handling test coverage.

The error handling test should verify the error logging functionality and test different error scenarios.

 it("should handle fetch errors gracefully", async () => {
+    const errorSpy = vi.spyOn(elizaLogger, 'error');
     global.fetch = vi.fn(() =>
         Promise.resolve({
             ok: false,
-            statusText: "Internal Server Error",
+            status: 500,
+            statusText: "Internal Server Error"
         })
     ) as any;

     const result = await fetchStandingsAction.handler(
         mockRuntime,
         {} as Memory,
         {} as State
     );
     expect(result).toBe(false);
+    expect(errorSpy).toHaveBeenCalledWith(
+        "Error fetching standings data:",
+        "Internal Server Error"
+    );
 });

+it("should handle network errors", async () => {
+    global.fetch = vi.fn(() => Promise.reject(new Error("Network error")));
+
+    const result = await fetchStandingsAction.handler(
+        mockRuntime,
+        {} as Memory,
+        {} as State
+    );
+    expect(result).toBe(false);
+});
packages/plugin-football/src/tests/match-action.test.ts (1)

27-38: Extract mock data to a shared fixture file.

The mock response structure is duplicated across test files. Consider extracting it to a shared fixture.

+// __fixtures__/mockResponses.ts
+export const mockMatchData = {
+    matches: [
+        {
+            homeTeam: { name: "Chelsea" },
+            awayTeam: { name: "Arsenal" },
+            score: {
+                fullTime: { homeTeam: 1, awayTeam: 2 },
+            },
+        },
+    ],
+};

-const mockResponse = {
-    matches: [
-        {
-            homeTeam: { name: "Chelsea" },
-            awayTeam: { name: "Arsenal" },
-            score: {
-                fullTime: { homeTeam: 1, awayTeam: 2 },
-            },
-        },
-    ],
-};
+import { mockMatchData } from '../__fixtures__/mockResponses';
+const mockResponse = mockMatchData;
packages/plugin-football/package.json (1)

2-3: Use semantic versioning format

The version 0.1.8+build.1 uses a non-standard format. Consider using standard semver format like 0.1.8.

-    "version": "0.1.8+build.1",
+    "version": "0.1.8"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 26f71dd and 02af3b3.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (14)
  • agent/package.json (2 hunks)
  • agent/src/index.ts (3 hunks)
  • packages/plugin-football/.npmignore (1 hunks)
  • packages/plugin-football/README.md (1 hunks)
  • packages/plugin-football/eslint.config.mjs (1 hunks)
  • packages/plugin-football/package.json (1 hunks)
  • packages/plugin-football/src/actions/fetchMatchAction.ts (1 hunks)
  • packages/plugin-football/src/actions/fetchStandingsAction.ts (1 hunks)
  • packages/plugin-football/src/index.ts (1 hunks)
  • packages/plugin-football/src/tests/fetch-standings-action.test.ts (1 hunks)
  • packages/plugin-football/src/tests/match-action.test.ts (1 hunks)
  • packages/plugin-football/src/types.ts (1 hunks)
  • packages/plugin-football/tsconfig.json (1 hunks)
  • packages/plugin-football/tsup.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • packages/plugin-football/eslint.config.mjs
  • packages/plugin-football/tsconfig.json
  • packages/plugin-football/.npmignore
🧰 Additional context used
🪛 LanguageTool
packages/plugin-football/README.md

[misspelling] ~125-~125: This word is normally spelled as one.
Context: ... 4. Goal System Improvements - Multi-step goal planning - Goal dependency tra...

(EN_COMPOUNDS_MULTI_STEP)

🪛 Markdownlint (0.37.0)
packages/plugin-football/README.md

37-37: Expected: 2; Actual: 4
Unordered list indentation

(MD007, ul-indent)


38-38: Expected: 2; Actual: 4
Unordered list indentation

(MD007, ul-indent)


39-39: Expected: 2; Actual: 4
Unordered list indentation

(MD007, ul-indent)


40-40: Expected: 2; Actual: 4
Unordered list indentation

(MD007, ul-indent)

🔇 Additional comments (1)
agent/package.json (1)

101-101: LGTM!

The plugin dependency is correctly added following the workspace pattern used for other plugins.

packages/plugin-football/src/index.ts Outdated Show resolved Hide resolved
packages/plugin-football/tsup.config.ts Outdated Show resolved Hide resolved
packages/plugin-football/src/actions/fetchMatchAction.ts Outdated Show resolved Hide resolved
agent/src/index.ts Outdated Show resolved Hide resolved
packages/plugin-football/package.json Show resolved Hide resolved
packages/plugin-football/package.json Show resolved Hide resolved
packages/plugin-football/README.md Outdated Show resolved Hide resolved
…ity and validation updates

- Added 5-second timeout using AbortController for fetchMatchAction.
- Implemented response validation to ensure data structure matches expected types.
- Improved error handling with detailed logs for better debugging.
- Removed .ts extensions from imports in index.ts to prevent production build issues.
- Cleaned up tsup.config.ts by removing unused externals (@reflink/reflink and @node-llama-cpp).
- Guarded against invalid API responses to enhance type safety.
@wtfsayo wtfsayo enabled auto-merge (squash) January 18, 2025 14:07
@wtfsayo
Copy link
Member

wtfsayo commented Jan 18, 2025

@suleigolden please give access to push to your branch / resolve conflicts

@wtfsayo wtfsayo self-requested a review January 20, 2025 12:43
@odilitime odilitime changed the title Plugin football feat: Plugin footballef Jan 22, 2025
@odilitime odilitime changed the title feat: Plugin footballef feat: Plugin football Jan 22, 2025
auto-merge was automatically disabled January 22, 2025 01:11

Head branch was pushed to by a user without write access

@wtfsayo wtfsayo enabled auto-merge (squash) January 23, 2025 13:46
@wtfsayo wtfsayo merged commit 0afde97 into elizaOS:develop Jan 23, 2025
7 checks passed
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.

2 participants