Skip to content

Commit

Permalink
Merge pull request #17 from tawilkinson/fix-empty-TTS-links
Browse files Browse the repository at this point in the history
Fix empty TTS links
  • Loading branch information
tawilkinson authored Feb 21, 2021
2 parents 674dde7 + 87c454a commit 82063c3
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 22 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,5 @@ dmypy.json
.prof

# End of https://www.toptal.com/developers/gitignore/api/python,linux

.vscode
2 changes: 1 addition & 1 deletion bot/project.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
repo="boardgamebot"
tag="0.9.2"
tag="0.9.3"
name="bgbot"

# NB:
Expand Down
72 changes: 64 additions & 8 deletions bot/python/games.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import discord
import json
import os
import re
from discord.ext import commands
from online_game_search import search_web_board_game_data


class Games(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.cont = 1
self.end_regex = r'\s\([0-9]+\)$'
self.parser = re.compile(self.end_regex)

def base_embed(self, game, cont=False):
if cont:
title = game['name'] + ' (continued)'
def base_embed(self, game):
if self.cont > 1:
title = game['name'] + f' ({self.cont})'
description = 'More game links below'
else:
title = game['name']
Expand All @@ -20,19 +24,20 @@ def base_embed(self, game, cont=False):
embed = discord.Embed(
title=title, description=description)
embed.set_thumbnail(url=game['image'])
if not cont:
if self.cont == 1:
bgg_text = '[' + game['name'] + '](' + game['bgg'] + ')'
embed.add_field(name='Read more at BGG',
value=bgg_text, inline=False)
return embed

def embed_constrain(self, name, value, embed, embeds, game):
embeds.append(embed)
embed = self.base_embed(game, True)
embed = self.base_embed(game)
embed.add_field(name=name, value=value)
return embed, embeds

def format_embed(self, game):
self.cont = 1
embeds = []
embed = self.base_embed(game)

Expand Down Expand Up @@ -79,6 +84,7 @@ def format_embed(self, game):
len(text)) > 1023 or (len(value) +
len(embed) > 5999):
count += 1
self.cont += 1
if (len(value) + len(embed) > 5999):
embed, embeds = self.embed_constrain(
name, value, embed, embeds, game)
Expand All @@ -105,13 +111,15 @@ def format_embed(self, game):
if (len(value) +
len(text)) > 1023 or (len(value) +
len(embed) > 5999):
self.cont += 1
embed, embeds = self.embed_constrain(
name, value, embed, embeds, game)
count += 1
value = ''
else:
value += text
value += '\n'
self.cont += 1
embed, embeds = self.embed_constrain(name, value,
embed, embeds, game)
else:
Expand All @@ -121,25 +129,73 @@ def format_embed(self, game):

return embeds

@commands.Cog.listener()
async def on_reaction_add(self, reaction, user, debug=False):
emoji = reaction.emoji
message = reaction.message
if user.bot:
return
if emoji in ['⏮', '◀', '▶', '⏭']:
title = message.embeds[0].title
match = self.parser.search(title)
if match is not None:
if debug:
print(f'> "{match[0]}" page matched')
search_game = search_web_board_game_data(
title.replace(str(match[0]), ''))
if debug:
print(f'> {title} is being fetched again')
idx = int(match[0].lstrip(' (').rstrip(')')) - 1
else:
search_game = search_web_board_game_data(title)
idx = 0
responses = self.format_embed(search_game)

if debug:
print(f'Index is {idx}')
if emoji == '⏮':
idx = 0
elif emoji == '◀':
idx = idx - 1
elif emoji == '▶':
idx = idx + 1
elif emoji == '⏭':
idx = len(responses) - 1

if idx < 0:
idx = 0
elif idx > len(responses):
idx = len(responses)
if debug:
print(f'Index to return is {idx}')
await message.edit(content="", embed=responses[idx])
else:
return

@commands.command(aliases=['g', 'search', 's', 'boardgame', 'bg'],
help='Print detailed info about a board game.')
async def game(self, ctx, *game):
game_str = ' '.join(game)
if game_str is None:
response = f'Please enter a game to search: `bg game <game_name>`. '
await ctx.send(response)
return
return [response]
else:
response = 'Searching for ' + game_str + ', standby whilst I search online...'
message = await ctx.send(response)
search_game = search_web_board_game_data(game_str)
if search_game:
responses = self.format_embed(search_game)
for response in responses:
await message.edit(content="", embed=response)
await message.edit(content="", embed=responses[0])
if len(responses) > 1:
emojis = ['⏮', '◀', '▶', '⏭']
for emoji in emojis:
await message.add_reaction(emoji)
return responses
else:
response = game_str + ' not found online.'
await message.edit(content=response)
return [response]


def setup(bot):
Expand Down
34 changes: 21 additions & 13 deletions bot/python/online_game_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,21 +230,29 @@ def get_tts_data(game, debug=False):
break
tts_search = Webpage(game.tts_search_url).page_html
search_results = tts_search.body.select('body a')
workshop = ''
for result in search_results:
url = result['href']
if 'https://steamcommunity.com' in url:
url = url.replace(
'/url?q=',
'').replace(
'%3F',
'?').replace(
'%3D',
'=').split('&')[0]
game.set_tts_url(f"{dlc}[ {game.name} on Steam Workshop]({url})")
try:
if 'https://steamcommunity.com/sharedfiles' in url:
url_name = result.contents[0].contents[0]
url = url.replace(
'/url?q=',
'').replace(
'%3F',
'?').replace(
'%3D',
'=').split('&')[0]
workshop += f"\n[{url_name} on Steam Workshop]({url})"
if debug:
print(
f'--> retrieved {url_name} Tabletop Simulator Steam Workshop data')
except AttributeError:
if debug:
print(
f'--> retrieved {game.name} Tabletop Simulator Steam Workshop data')
break
f'--> No url_name')

game.set_tts_url(f"{dlc}{workshop}")


def get_bga_data(game, debug=False):
Expand Down Expand Up @@ -287,7 +295,7 @@ def get_yucata_data(game, debug=False):
print(f'--> retrieved {game.name} Yucata data')


def search_web_board_game_data(game_name, debug=True):
def search_web_board_game_data(game_name, debug=False):
"""
Willwill search Board Game Geek (BGG) for a board game with that name, or
else find the next best match. If a match is found on the BGG site the name,
Expand All @@ -309,7 +317,7 @@ def search_web_board_game_data(game_name, debug=True):
"boite": "[<name> on Boite a Jeux](<boite_url>)",
}
"""
game = Game(game_name)
game = Game(game_name.lower())
if debug:
print(f'SEARCHING WEB FOR GAME DATA: {game.name}')
game_on_bgg = get_bgg_data(game, debug)
Expand Down

0 comments on commit 82063c3

Please sign in to comment.