mkreiser / ESPN-Fantasy-Football-API

Connect to ESPN's fantasy football API via this JS API client for web and NodeJS. Available as an npm package.
http://espn-fantasy-football-api.s3-website.us-east-2.amazonaws.com/
GNU Lesser General Public License v3.0
314 stars 81 forks source link

Feature request: basic usage example #128

Closed philip closed 1 year ago

philip commented 5 years ago

This is a documentation/example request that a provides an example (and associated documentation to run it) that displays basic information about the user's ESPN league. Likely Node.js based as to function with both private/public leagues.

This is geared towards either a complete novice programmer (hobbyist) or someone new to Node.js. It'd include every step, including how to start the Node.js server.

travisryan commented 5 years ago

Is this something you currently need, or are you requesting this to help the next person because you had alot of trouble getting it working?

I'm asking because if you already went through it, then write it up yourself and post it here. @mkreiser is obviously busy, and any help we can give is great!

If you need some help, post your questions and I and others will try to help you through it.

ReeceLangerock commented 5 years ago

Agreed, if it's something you need help with I can probably cleanup the simple node server I started with and put in a PR sometime this weekend.

philip commented 5 years ago

Thanks for the responses!

I’m not able to write this but I can test/review/pr against someone else’s work after the fact; by following the dummies guide to interface my private league.

atlflyer commented 5 years ago

I'm not a nodejs novice, but I am a bit mystified by the usage examples in the README. I'm used to using require not import, so I'm not sure what to do about the syntax error that import { ... } from 'espn-fantasy-football-api/node'; causes. Google suggests that nodejs only has experimental support for ES6 modules, but I can't figure out what that means for this situation. A brief usage example for command line nodejs would really help.

travisryan commented 5 years ago

agreed. I think a ticket I opened not long ago had an example someone gave me. For now, look that up.

atlflyer commented 5 years ago

Thanks, I found this on the v3 upgrade issue, which worked for me:

const { Client } = require("espn-fantasy-football-api/node"); const myClient = new Client({ leagueId: my league id here });

Dropping it here for anyone else who has the same problem and finds this thread.

philip commented 5 years ago

I’m holding onto hope that @ReeceLangerock swoops in and posts an example :)

mkreiser commented 5 years ago

Here's a script I wrote with the client to calculate the best possible lineup each team could have started for a week:

const _ = require('lodash');
const { Client } = require('./node-dev');

const myClient = new Client({
  // your deets here
});

class Psychic {
  static filterPosition(boxscorePlayer, position) {
    return (
      boxscorePlayer.position === position ||
      _.includes(boxscorePlayer.player.eligiblePositions, position)
    );
  }

  static handleNonFlexPosition(lineup, position) {
    const players = _.filter(lineup, (player) => this.filterPosition(player, position));
    const sortedPlayers = _.sortBy(players, ['totalPoints']);
    return _.last(sortedPlayers);
  }

  static analyzeLineup(lineup, score) {
    let bestSum = 0;
    const bestRoster = [];
    let numChanges = 0;

    const bestQB = this.handleNonFlexPosition(lineup, 'QB')
    bestRoster.push(bestQB.player.fullName);
    bestSum += bestQB.totalPoints;
    if (bestQB.position === 'Bench') {
      numChanges += 1;
    }

    const bestDefense = this.handleNonFlexPosition(lineup, 'D/ST')
    bestRoster.push(bestDefense.player.fullName);
    bestSum += bestDefense.totalPoints;
    if (bestDefense.position === 'Bench') {
      numChanges += 1;
    }

    const bestKicker = this.handleNonFlexPosition(lineup, 'K')
    bestRoster.push(bestKicker.player.fullName);
    bestSum += bestKicker.totalPoints;
    if (bestKicker.position === 'Bench') {
      numChanges += 1;
    }

    const flexPlayers = _.filter(lineup, (player) => this.filterPosition(player, 'RB') ||
      this.filterPosition(player, 'WR') ||
      this.filterPosition(player, 'TE')
    );
    const sortedFlexPlayers = _.sortBy(flexPlayers, ['totalPoints']);

    const flexPos = { RB: 2, WR: 2, TE: 1, FLEX: 1 };

    while (_.sum(_.values(flexPos)) && !_.isEmpty(sortedFlexPlayers)) {
      const player = sortedFlexPlayers.pop();
      const acceptPlayer = () => {
        bestRoster.push(player.player.fullName);
        bestSum += player.totalPoints;
        if (player.position === 'Bench') {
          numChanges += 1;
        }
      }

      if (flexPos.RB && _.includes(player.player.eligiblePositions, 'RB')) {
        acceptPlayer();
        flexPos.RB -= 1;
      } else if (flexPos.WR && _.includes(player.player.eligiblePositions, 'WR')) {
        acceptPlayer();
        flexPos.WR -= 1;
      } else if (flexPos.TE && _.includes(player.player.eligiblePositions, 'TE')) {
        acceptPlayer();
        flexPos.TE -= 1;
      } else if (flexPos.FLEX) {
        acceptPlayer();
        flexPos.FLEX -= 1;
      }
    }

    return {
      bestSum,
      bestRoster,
      currentScore: score,
      numChanges
    };
  }

  static runForWeek({ seasonId, matchupPeriodId, scoringPeriodId }) {
    const bestLineups = {};
    return myClient.getBoxscoreForWeek({ seasonId, matchupPeriodId, scoringPeriodId }).then((boxes) => {
      _.forEach(boxes, (box) => {
        bestLineups[box.awayTeamId] = this.analyzeLineup(box.awayRoster, box.awayScore);
        bestLineups[box.homeTeamId] = this.analyzeLineup(box.homeRoster, box.homeScore);
      });

      return bestLineups;
    });
  }
}

Psychic.runForWeek({ seasonId: 2019, matchupPeriodId: 4, scoringPeriodId: 4 }).then((result) => {
  console.log(result);
  return result;
});
nallgood commented 5 years ago

Thanks for everything here, this is truly amazing! Would it be possible to post an example showing how to pull in boxscores for a specific matchupPeriodID? I'm on the verge of understanding getBoxscoreForWeek(), but for some reason seem to be missing something obvious.

Seth-Duncan commented 5 years ago

Does anyone have a simple example of how to spin up the NodeJS server and call basic methods for a private league (I'm not asking for posted creds or cookies). I'm trying to utilize this in a Vue.js app on localhost to create a custom live FF stats viewer for my league and can't seem to even get passed the ability to set cookies and make a simple call for even getting league info.

Thanks for any help at all.

jamigibbs commented 5 years ago

@Seth-Duncan I was just messing around with a React chrome extension boilerplate and the ESPN api integrated so maybe that will help you get your Vue app running. If you're not sure how to setup a Node server, it might be best to start with a Vue boilerplate that incorporates all of that for you already (like I've done):

https://github.com/jamigibbs/espn-fantasy-chrome-extension/blob/master/src/pages/Popup/Popup.jsx

Seth-Duncan commented 5 years ago

@jamigibbs Thank you Jami!

I'll take a look at this and try and incorporate it to my Vue app. One question, are you running this off localhost? I only ask because I get JS Errors from trying to set Cookies when running this on localhost via npm serve.

Thank you again!

Ccallaway93 commented 5 years ago

I am new to NodeJs and trying to learn by creating a simple web app for my Fantasy League. I am also interested in just a basic example that shows how to run some of these methods. Like getBoxScore for example. Thanks!

mkreiser commented 1 year ago

Added the Psychic script to the README in #241