initial commit

This commit is contained in:
cottongin 2019-02-20 15:51:20 -06:00
commit aab0c5bbe9
5 changed files with 266 additions and 0 deletions

1
README.md Normal file
View File

@ -0,0 +1 @@
Fetches golf scores

49
__init__.py Normal file
View File

@ -0,0 +1,49 @@
###
# Copyright (c) 2018, cottongin
# All rights reserved.
#
#
###
"""
GolfScores: Fetches golf scores
"""
import sys
import supybot
from supybot import world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.unknown
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = ''
from . import config
from . import plugin
if sys.version_info >= (3, 4):
from importlib import reload
else:
from imp import reload
# In case we're being reloaded.
reload(config)
reload(plugin)
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing:
from . import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

33
config.py Normal file
View File

@ -0,0 +1,33 @@
###
# Copyright (c) 2018, cottongin
# All rights reserved.
#
#
###
from supybot import conf, registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('GolfScores')
except:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x: x
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified themself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('GolfScores', True)
GolfScores = conf.registerPlugin('GolfScores')
# This is where your configuration variables (if any) should go. For example:
# conf.registerGlobalValue(GolfScores, 'someConfigVariableName',
# registry.Boolean(False, _("""Help for someConfigVariableName.""")))
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

168
plugin.py Normal file
View File

@ -0,0 +1,168 @@
###
# Copyright (c) 2018, cottongin
# All rights reserved.
#
#
###
import pendulum
import requests
from supybot import utils, plugins, ircutils, callbacks
from supybot.commands import *
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('GolfScores')
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x: x
CURRENT_URL = 'https://statdata.pgatour.com/{trn_type}/current/message.json'
SCOREBOARD = 'https://statdata.pgatour.com/{trn_type}/{trn_id}/leaderboard-v2mini.json'
class GolfScores(callbacks.Plugin):
"""Fetches golf scores"""
threaded = True
def _fetchCurrent(self, type_='r'):
tmp = None
try:
jdata = requests.get(CURRENT_URL.format(trn_type=type_)).json()
tmp = jdata['tid']
return [type_, tmp]
except:
return [type_, tmp]
return [type_, tmp]
@wrap([getopts({'all': '', 'info': '', 'champions': ''}), optional('text')])
def golf(self, irc, msg, args, options, search=None):
""" [player name]
Fetches leaderboard for active or previous tournament,
optionally pass a name to find player in standings
"""
options = dict(options)
type_is_champions = options.get('champions')
if type_is_champions:
trn = self._fetchCurrent(type_='s')
else:
trn = self._fetchCurrent()
if not trn[1]:
irc.reply('Something went wrong getting the current/previous tournament')
return
if options.get('info'):
url = 'https://www.pgatour.com/bin/data/feeds/weather.json/{}{}'.format(
trn[0], trn[1])
print(url)
idata = requests.get(url).json()
url2 = 'https://statdata.pgatour.com/r/current/schedule-v2.json' #.format(trn[0])
#print(url2)
sdata = requests.get(url2).json()
#print(sdata)
# now get the leaderboard json
try:
jdata = requests.get(SCOREBOARD.format(trn_type=trn[0], trn_id=trn[1]))
print(jdata.url)
jdata = jdata.json()
except:
irc.reply('Something went wrong fetching the leaderboard')
return
leaderboard = jdata.get('leaderboard')
if not leaderboard:
irc.reply('No leaderboard found')
return
name = ircutils.bold(leaderboard['tournament_name'])
date = "{}-{}".format(
pendulum.parse(leaderboard['start_date'], strict=False).format('MMMD'),
pendulum.parse(leaderboard['end_date'], strict=False).format('MMMD'))
round_ = 'Round {}'.format(leaderboard['current_round'])
if leaderboard['round_state']:
round_ += ' ({})'.format(leaderboard['round_state'])
cut_line = leaderboard['cut_line'].get('cut_count') or len(leaderboard['players'])
positions = []
if not options.get('info'):
for idx, player in enumerate(leaderboard['players']):
if player['player_bio']['short_name']:
plyr_name = '{}.{}'.format(player['player_bio']['short_name'].replace('.', ''),
player['player_bio']['last_name'])
else:
plyr_name = '{}'.format(player['player_bio']['last_name'])
full_name = '{} {}'.format(player['player_bio']['first_name'],
player['player_bio']['last_name'])
if idx >= cut_line:
if player['status'] == 'wd':
rank = ircutils.mircColor('WD', 'orange')
else:
rank = ircutils.mircColor('CUT', 'red')
else:
rank = str(player['current_position'])
if player['thru']:
thru = ' {:+d} thru {} '.format(player['today'], ircutils.mircColor(str(player['thru']), 'green')) \
if player['thru'] != 18 else ' {:+d}'.format(player['today']) + ircutils.bold(ircutils.mircColor(' F ', 'red'))
else:
thru = ' '
score = '{:+d}'.format(player['total']) if player['total'] else '-'
string = '{} {}{}({})'.format(
ircutils.bold(ircutils.mircColor(rank, 'blue')),
plyr_name,
thru,
score)
if search:
if search.lower() in full_name.lower():
positions.append(string)
else:
positions.append(string)
if not positions:
positions.append('Player not found')
#return
if options.get('info'):
loc = idata['current_observation']['display_location']['full']
weather = idata['current_observation']['weather']
try:
temp = idata['current_observation']['temperature_string']
wind = idata['current_observation']['wind_string']
except:
temp = "{}F".format(idata['current_observation']['temp_f'])
wind = "{}mph {}".format(idata['current_observation']['wind_mph'], idata['current_observation']['wind_dir'])
w_string = '{} :: {} - {} - Wind: {}'.format(loc, weather, temp, wind)
year = sdata['currentYears'][trn[0]]
for item in sdata['years']:
if item['year'] == year:
data = item['tours']
for t in data:
if t['tourCodeLc'] == trn[0]:
tdata = t['trns']
for tour in tdata:
if tour['permNum'] == trn[1]:
tmp = tour
break
course = tmp['courses'][0]['courseName']
purse = tmp['Purse']
winnerPrize = tmp['winnersShare']
defending = '{} {}'.format(tmp['champions'][0]['playerName']['first'], tmp['champions'][0]['playerName']['last'])
w_string += ' :: {} :: \x02Defending champion:\x02 {} :: \x02Purse:\x02 ${} (${} to winner)'.format(
course, defending, purse, winnerPrize)
positions.append(w_string)
trunc = 10 if not options.get('all') else len(positions)
irc.reply('{} ({}) :: {} :: {}'.format(name, date, round_,
', '.join(p for p in positions[:trunc])))
return
Class = GolfScores
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:

15
test.py Normal file
View File

@ -0,0 +1,15 @@
###
# Copyright (c) 2018, cottongin
# All rights reserved.
#
#
###
from supybot.test import *
class GolfScoresTestCase(PluginTestCase):
plugins = ('GolfScores',)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: