Browse Source

Make python code PEP8 compliant

master
Alexey Chernyshov 7 years ago
parent
commit
5c2d83e3c7
3 changed files with 109 additions and 40 deletions
  1. 27
    12
      src/documents.py
  2. 71
    26
      src/magic-judge-telegram-bot.py
  3. 11
    2
      src/oracle.py

+ 27
- 12
src/documents.py View File

@@ -6,13 +6,17 @@ with open('data/cr.json') as file:
crDataNames = crData['glossary'].keys()
crDataNumbers = crData['sections'].keys()

print('Registered {} CR glossary terms and {} CR sections'.format(len(crDataNames), len(crDataNumbers)))
print(
'Registered {} CR glossary terms and {} CR sections'.format(
len(crDataNames),
len(crDataNumbers)))


def cr_search(words):

if not words:
return 'I need some clues to search for, my master!'
words = [word.casefold() for word in words]
if words[0][0].isdigit():
lang = 'en'
@@ -23,7 +27,8 @@ def cr_search(words):
other = []
section = words[0].casefold()
pos = len(section)
for name in sorted([name for name in crDataNumbers if name.startswith(section)]):
for name in sorted([name for name in crDataNumbers
if name.startswith(section)]):
diff = name[pos:].strip('.')
if len(diff) < 2 and (len(diff) == 0 or diff.isalpha()):
results.append(name)
@@ -33,35 +38,45 @@ def cr_search(words):
if not results:
return 'This section doesn\'t exist, my master!'

text = '\n'.join(['<b>{}</b> {}'.format(name, crData['sections'][name][lang]) for name in results])
text = '\n'.join(
['<b>{}</b> {}'.format(name, crData['sections'][name][lang])
for name in results])
if other:
text += '\n<i>(Subsections: {}-{})</i>'.format(other[0], other[-1])
if len(text) > 4000:
text = '<b>{}</b> {}\n<i>(See also: {}-{})</i>'.format(results[0], crData['sections'][results[0]][lang], results[1], results[-1])
text = '<b>{}</b> {}\n<i>(See also: {}-{})</i>'.format(
results[0], crData['sections'][results[0]][lang], results[1], results[-1])

else:
nameCandidates = [name for name in crDataNames if all(word in name.casefold() for word in words)]
nameCandidates = [
name for name in crDataNames if all(
word in name.casefold() for word in words)]

term = ' '.join(words)
if len(words) > 1:
goodCandidates = [name for name in nameCandidates if term in name.casefold()]
goodCandidates = [name for name in nameCandidates
if term in name.casefold()]
if goodCandidates:
nameCandidates = goodCandidates

bestCandidates = [name for name in nameCandidates if name.casefold().startswith(term)]
bestCandidates = [name for name in nameCandidates
if name.casefold().startswith(term)]
if bestCandidates:
nameCandidates = bestCandidates
excellentCandidate = [name for name in nameCandidates if name.casefold() == term]
excellentCandidate = [name for name in nameCandidates
if name.casefold() == term]
if excellentCandidate:
nameCandidates = excellentCandidate

if not nameCandidates:
return 'I searched very thoroughly, but returned empty-handed, my master!'

if len(nameCandidates) > 20:
return 'I need more specific clues, my master! This would return {} names'.format(len(nameCandidates))
return 'I need more specific clues, my master! This would return {} names'.format(
len(nameCandidates))

text = '\n'.join(['<b>{}</b>\n{}'.format(name, crData['glossary'][name]) for name in sorted(nameCandidates)])
text = '\n'.join(
['<b>{}</b>\n{}'.format(name, crData['glossary'][name])
for name in sorted(nameCandidates)])

return text

+ 71
- 26
src/magic-judge-telegram-bot.py View File

@@ -2,11 +2,18 @@ import logging
import json
import oracle
import documents
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, CallbackQueryHandler, MessageHandler, Filters
from telegram import InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardButton, InlineKeyboardMarkup
import gc
from telegram.ext import (Updater, CommandHandler, InlineQueryHandler,
CallbackQueryHandler, MessageHandler, Filters)
from telegram import (InlineQueryResultArticle, InputTextMessageContent,
InlineKeyboardButton, InlineKeyboardMarkup)

#logging.basicConfig(
# level=logging.DEBUG,
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

#gc.set_debug(gc.DEBUG_LEAK)

#logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

def format_card(card):
mana = ''
@@ -27,6 +34,7 @@ def format_card(card):
text,
footer)


def preview_card(card):
mana = ''
if 'manaCost' in card:
@@ -36,6 +44,7 @@ def preview_card(card):
mana,
card['type'])


def start_command(bot, update):
commands = [
'/o <card name or search strings> - oracle text for a card',
@@ -44,35 +53,52 @@ def start_command(bot, update):
'/ipg <section> (coming soon)',
'/mtr <section> (coming soon)',
]
update.message.reply_text('How can I help?\n{}'.format('\n'.join(commands)), quote = False)
update.message.reply_text(
'How can I help?\n{}'.format(
'\n'.join(commands)),
quote=False)


def oracle_command(bot, update, args):
if not args:
update.message.reply_text('I need some clues to search for, my master!', quote=False)
update.message.reply_text(
'I need some clues to search for, my master!',
quote=False)
return
words = [word.casefold() for word in args]

nameCandidates = oracle.get_matching_names(words)

if not nameCandidates:
update.message.reply_text('I searched very thoroughly, but returned empty-handed, my master!', quote=False)
update.message.reply_text(
'I searched very thoroughly, but returned empty-handed, my master!',
quote=False)
return

if len(nameCandidates) > 20:
update.message.reply_text('I need more specific clues, my master! This would return {} names'.format(len(nameCandidates)), quote=False)
update.message.reply_text(
'I need more specific clues, my master! This would return {} names'.format(
len(nameCandidates)), quote=False)
return

if len(nameCandidates) > 1:
# TODO: if len(name) < 64 is a quickfix for /o show, which fails to send correct callback data for un... card
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(name, callback_data=name)] for name in nameCandidates if len(name) < 64])
update.message.reply_text('Which one?', reply_markup=reply_markup, quote=False)
# TODO: if len(name) < 64 is a quickfix for /o show, which fails to
# send correct callback data for un... card
reply_markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(name, callback_data=name)]
for name in nameCandidates if len(name) < 64])
update.message.reply_text(
'Which one?',
reply_markup=reply_markup,
quote=False)
return

reply = []
for name in nameCandidates:
for oracleName in oracle.get_oracle_names(name):
reply.append(format_card(oracle.get_card(oracleName)))
update.message.reply_text('\n'.join(reply), parse_mode='HTML', quote = False)
update.message.reply_text('\n'.join(reply), parse_mode='HTML', quote=False)


def question_command(bot, update, args):
text = ' '.join(args).casefold()
@@ -81,9 +107,15 @@ def question_command(bot, update, args):

reply = []
for name in names:
reply.append('"' + name + '":\n' + '\n'.join([format_card(oracle.get_card(oracleName)) for oracleName in oracle.get_oracle_names(name)]))
reply.append(
'"' + name + '":\n' + '\n'.join(
[format_card(oracle.get_card(oracleName))
for oracleName in oracle.get_oracle_names(name)]))
if reply:
update.message.reply_text('\n\n'.join(reply), parse_mode='HTML', quote = False)
update.message.reply_text(
'\n\n'.join(reply),
parse_mode='HTML', quote=False)


def inline_oracle(bot, update):
query = update.inline_query.query.casefold()
@@ -107,11 +139,12 @@ def inline_oracle(bot, update):
id=card['name'],
title=word,
description=preview_card(card),
input_message_content=InputTextMessageContent(format_card(card), parse_mode='HTML')
)
)
input_message_content=InputTextMessageContent(
format_card(card),
parse_mode='HTML')))
bot.answerInlineQuery(update.inline_query.id, results)


def callback_name(bot, update):
message_id = update.callback_query.message.message_id
chat_id = update.callback_query.message.chat.id
@@ -122,14 +155,13 @@ def callback_name(bot, update):
bot.answerCallbackQuery(update.callback_query.id)
return

bot.editMessageText(
chat_id = chat_id,
message_id = message_id,
parse_mode = 'HTML',
text = '\n'.join([format_card(oracle.get_card(oracleName)) for oracleName in names])
)
bot.editMessageText(chat_id=chat_id, message_id=message_id,
parse_mode='HTML', text='\n'.join(
[format_card(oracle.get_card(oracleName))
for oracleName in names]))
bot.answerCallbackQuery(update.callback_query.id)


def text(bot, update):
if update.message.chat.type != 'private':
return
@@ -141,22 +173,35 @@ def text(bot, update):


def comp_rules_command(bot, update, args):
update.message.reply_text(documents.cr_search(args), parse_mode='HTML', quote = False)
update.message.reply_text(
documents.cr_search(args),
parse_mode='HTML', quote=False)


def ask_command(bot, update, args):
pass


def dispatcher_setup(dispatcher):
dispatcher.add_handler(CommandHandler('start', start_command))
dispatcher.add_handler(CommandHandler('help', start_command))
dispatcher.add_handler(CommandHandler('o', oracle_command, pass_args=True))
dispatcher.add_handler(CommandHandler('q', question_command, pass_args=True))
dispatcher.add_handler(CommandHandler('cr', comp_rules_command, pass_args=True))
dispatcher.add_handler(
CommandHandler(
'q',
question_command,
pass_args=True))
dispatcher.add_handler(
CommandHandler(
'cr',
comp_rules_command,
pass_args=True))
dispatcher.add_handler(CommandHandler('ask', ask_command, pass_args=True))
dispatcher.add_handler(InlineQueryHandler(inline_oracle))
dispatcher.add_handler(CallbackQueryHandler(callback_name))
dispatcher.add_handler(MessageHandler(Filters.text, text))


with open('config.json') as file:
config = json.load(file)


+ 11
- 2
src/oracle.py View File

@@ -5,10 +5,16 @@ with open('data/names.json') as file:
namesToSearch = names.keys()
with open('data/oracle.json') as file:
oracleData = json.load(file)
print('Registered {} card names and {} oracle entries'.format(len(namesToSearch), len(oracleData)))
print(
'Registered {} card names and {} oracle entries'.format(
len(namesToSearch),
len(oracleData)))


def get_matching_names(words):
nameCandidates = [name for name in namesToSearch if all(word in name.casefold() for word in words)]
nameCandidates = [
name for name in namesToSearch if all(
word in name.casefold() for word in words)]

term = ' '.join(words)

@@ -23,18 +29,21 @@ def get_matching_names(words):

return nameCandidates


def get_card(name):
if name in oracleData:
return oracleData[name]
else:
return None


def get_oracle_names(name):
if name in names:
return names[name]
else:
return None


def get_names_in_text(text):
result = []
for name in namesToSearch:

Loading…
Cancel
Save