Skip to content

Commit

Permalink
馃殌 v0.1.0 release
Browse files Browse the repository at this point in the history
  • Loading branch information
conrmahr committed Jan 10, 2020
0 parents commit 727057c
Show file tree
Hide file tree
Showing 17 changed files with 1,438 additions and 0 deletions.
47 changes: 47 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2019
},
"rules": {
"brace-style": ["error", "stroustrup", { "allowSingleLine": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"handle-callback-err": "off",
"indent": ["error", "tab"],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"no-console": "off",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multi-spaces": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-shadow": ["error", { "allow": ["err", "resolve", "reject"] }],
"no-trailing-spaces": ["error"],
"no-var": "error",
"object-curly-spacing": ["error", "always"],
"prefer-const": "error",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"space-before-blocks": "error",
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"yoda": "error"
}
}
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto eol=lf
25 changes: 25 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
name: Bug report
about: Report incorrect or unexpected behaviour of discord.js
title: ''
labels: 's: unverified, type: bug'
assignees: ''

---

**Please describe the problem you are having in as much detail as possible:**

**Include a reproducible code sample here, if possible:**
```js

// Place your code here

```

**Further details:**
- nhl-discord-bot version:
- Node.js version:
- Operating system:
- Priority this issue should have:

- [ ] I have also tested the issue on latest master, commit hash:
19 changes: 19 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
name: Feature request
about: Request a feature for the core discord.js library
title: ''
labels: 'type: enhancement'
assignees: ''

---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the ideal solution**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.
10 changes: 10 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
**Please describe the changes this PR makes and why it should be merged:**


**Status**
- [ ] Code changes have been tested against the NHL API, or there are no code changes

**Semantic versioning classification:**
- [ ] This PR changes the library's interface (methods or parameters added)
- [ ] This PR includes breaking changes (methods removed or renamed, parameters moved or removed)
- [ ] This PR **only** includes non-code changes, like changes to documentation, README, etc.
18 changes: 18 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: build
on: [push, pull_request]

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: ['10', '12']
name: Node v${{ matrix.node-version }} Build
steps:
- uses: actions/checkout@v1
- name: Setup node
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.DS_Store
node_modules/
config.json
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Conor Meagher

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<img width="128" height="128" align="left" style="float: left; margin: 0 10px 0 0;" alt="NHL Discord Bot" src="https://cdn.discordapp.com/avatars/535203406592344067/1473d566732ea6ffd24d02be45af8b21.png">

# :ice_hockey: NHL Discord Bot
![Build Status](https://github.com/conrmahr/nhl-discord-bot/workflows/build/badge.svg)

NHL-DB is a self-hosted Discord bot that returns live NHL scores and schedules on command using the [discord.js](https://discord.js.org/) library. Issues or feature requests can be submitted to this repo.

>**Disclaimer:** The NHL Discord Bot is not associated with the National Hockey League; National Hockey League Players' Association, Discord Inc., or its properties.
26 changes: 26 additions & 0 deletions commands/about.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const Discord = require('discord.js');
const { name, version, description } = require('../package.json');

module.exports = {
name: 'about',
usage: '',
description: `Shows information about ${name}.`,
category: 'about',
aliases: ['about', 'a'],
examples: [],
async execute(message) {

const embed = new Discord.RichEmbed();
embed.setColor(0xa1cdff);
embed.setAuthor('About', 'https://cdn.discordapp.com/avatars/535203406592344067/1473d566732ea6ffd24d02be45af8b21.png');
embed.setDescription([
`**${name}** is developed by **[@conrmahr](https://github.com/conrmahr)** and uses the **[Discord.js](https://discord.js.org)** library.`,

`Issues or feature requests can be submitted to the **[GitHub repo](https://github.com/conrmahr/${name})**.`,
'',
`${description} v${version}.`,
]);

return message.channel.send(embed);
},
};
47 changes: 47 additions & 0 deletions commands/help.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const { RichEmbed } = require('discord.js');

module.exports = {
name: 'help',
usage: '<command>',
description: 'List all of my commands or info about a specific command.',
category: 'help',
aliases: ['help', 'h'],
examples: ['nhl', 'teams'],
execute(message, args, prefix) {
const { commands } = message.client;

if (!args.length) {
const embed = new RichEmbed();
embed.setColor(0xa1cdff);
embed.addField('Command List',
[
'This is a list of all available commands.',
`To view details for a command, type \`${prefix}help <command>\`.`,
]);
embed.addField('Commands', `\`${commands.map(c => c.name).join('` `')}\``);

return message.channel.send(embed);

}

const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
const text = `${prefix}${command.aliases[0]}`;

if (!command) {
return message.reply(`\`${name}\` is not a valid command. Type \`${prefix}help\` for a list of commands.`);
}
const embed = new RichEmbed();
embed.setColor(0xa1cdff);
embed.setTitle(`\`${prefix}${command.name} ${command.usage}\``);
embed.addField('Description', command.description);
if (command.examples.length) {
embed.addField('Examples', `\`${text} ${command.examples.join(`\`\n\`${text} `)}\``, true);
}
if (command.aliases.length > 1) {
embed.addField('Aliases', `\`${command.aliases.join('` `')}\``, true);
}
return message.channel.send(embed);

},
};
150 changes: 150 additions & 0 deletions commands/nhl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
const { RichEmbed } = require('discord.js');
const fetch = require('node-fetch');
const moment = require('moment-timezone');
const querystring = require('querystring');

module.exports = {
name: 'nhl',
usage: '<date> <team> <opponent>',
description: 'Get games for a tomorrow, yesterday, next 5 games, last 5 games, or given date (YYYY-MM-DD). If none is specified, return games scheduled for today. Add team abbreviation to filter for a specific team and opponent.',
category: 'scores',
aliases: ['nhl', 'n'],
examples: ['', 'nyi', 'tomorrow', 'next nyi nyr'],
async execute(message, args, prefix) {

const { teams } = await fetch('https://statsapi.web.nhl.com/api/v1/teams/').then(response => response.json());
const { seasons } = await fetch('https://statsapi.web.nhl.com/api/v1/seasons/current/').then(response => response.json());
const endpoint = 'https://statsapi.web.nhl.com/api/v1/schedule/?';
const parameters = {};
let limit = 1;

if (args[0]) {

if (['last', 'yesterday', 'today', 'tomorrow', 'next'].includes(args[0])) {
switch (args[0]) {
case 'last':
parameters.startDate = moment(seasons[0].regularSeasonStartDate).format('MM/DD/YYYY');
parameters.endDate = moment().format('MM/DD/YYYY');
limit = 5;
break;
case 'yesterday':
parameters.startDate = moment().add(-1, 'day').format('MM/DD/YYYY');
parameters.endDate = parameters.startDate;
break;
case 'today':
parameters.startDate = moment().format('MM/DD/YYYY');
parameters.endDate = parameters.startDate;
break;
case 'tomorrow':
parameters.startDate = moment().add(1, 'day').format('MM/DD/YYYY');
parameters.endDate = parameters.startDate;
break;
case 'next':
parameters.startDate = moment().format('MM/DD/YYYY');
parameters.endDate = moment(seasons[0].seasonEndDate).format('MM/DD/YYYY');
limit = 5;
break;
}
}
else if (moment(args[0], 'YYYY-MM-DD').isValid()) {
parameters.startDate = moment(args[0]).format('MM/DD/YYYY');
parameters.endDate = moment(args[0]).format('MM/DD/YYYY');
}
else {
args.push(args[0]);
}

if (args[1]) {

const teamObj = teams.find(o => o.abbreviation === args[1].toUpperCase() || o.teamName.toUpperCase().split(' ').pop() === args[1].toUpperCase());

if (teamObj) {
parameters.teamId = teamObj.id;
}
else {
return message.channel.send(`\`${args[1]}\` is not a valid team. Type \`${prefix}teams\` for a list of teams.`);
}
}

if (args[2]) {

const opponentObj = teams.find(o => o.abbreviation === args[2].toUpperCase() || o.teamName.toUpperCase().split(' ').pop() === args[1].toUpperCase());

if (opponentObj) {
parameters.opponentId = opponentObj.id;
}
else {
return message.channel.send(`\`${args[2]}\` is not a valid opponent. Type \`${prefix}teams\` for a list of teams.`);
}
}
}

parameters.gameType = ['PR', 'R', 'P', 'A'];
parameters.expand = ['schedule.linescore'];
const query = querystring.stringify(parameters);
const schedule = await fetch(endpoint + query).then(response => response.json());
const checkGames = schedule.totalGames;
if (!checkGames) return message.reply('No games scheduled.');

function getScores(games) {
return games.map(game => {

function isBold(w, l) {
if(w > l) {
return '**';
}
else {
return '';
}
}

function formatPeriod(p) {
switch(p) {
case 'OT':
return 'F/OT';
case 'SO':
return 'F/SO';
default:
return 'F';
}
}

const { status: { statusCode }, teams: { away, home }, linescore } = game;
const awayTeam = teams.find(o => o.id === away.team.id).abbreviation;
const homeTeam = teams.find(o => o.id === home.team.id).abbreviation;
const awayBB = isBold(away.score, home.score);
const homeBB = isBold(home.score, away.score);

if (statusCode < 3) {
const gameTimeEST = moment(game.gameDate).tz('America/New_York').format('h:mm A z');
return `${awayTeam} @ ${homeTeam} (${gameTimeEST})`;
}
else if (statusCode > 2 && statusCode < 5) {
const awayPP = linescore.teams.away.powerPlay ? '[*PP*]' : '';
const homePP = linescore.teams.home.powerPlay ? '[*PP*]' : '';
const awayEN = linescore.teams.away.goaliePulled ? '[*EN*]' : '';
const homeEN = linescore.teams.home.goaliePulled ? '[*EN*]' : '';
return `${awayTeam} ${away.score} ${awayPP} ${awayEN} ${homeTeam} ${home.score} ${homePP} ${homeEN} (${linescore.currentPeriodTimeRemaining}/${linescore.currentPeriodOrdinal})`;
}
else if (statusCode > 5 && statusCode < 8) {
return `${awayBB}${awayTeam} ${away.score}${awayBB} ${homeBB}${homeTeam} ${home.score}${homeBB} (${formatPeriod(linescore.currentPeriodOrdinal)})`;
}
else if (statusCode === 9) {
return `${awayTeam} @ ${homeTeam} PPD`;
}
}).join('\n');
}

if (args[0] === 'last') {
schedule.dates.reverse();
}

const embed = new RichEmbed();
embed.setColor(0xa1cdff);
embed.setAuthor('NHL Scores', 'https://upload.wikimedia.org/wikipedia/en/thumb/3/3a/05_NHL_Shield.svg/150px-05_NHL_Shield.svg.png');
schedule.dates.slice(0, limit).map(({ date, games }) => embed.addField(':hockey: ' + moment(date).format('ddd, MMM DD'), `${getScores(games)}`));

message.channel.send(embed);

},
};

0 comments on commit 727057c

Please sign in to comment.