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

crDataNames = crData['glossary'].keys() crDataNames = crData['glossary'].keys()
crDataNumbers = crData['sections'].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): def cr_search(words):


if not words: if not words:
return 'I need some clues to search for, my master!' return 'I need some clues to search for, my master!'
words = [word.casefold() for word in words] words = [word.casefold() for word in words]
if words[0][0].isdigit(): if words[0][0].isdigit():
lang = 'en' lang = 'en'
other = [] other = []
section = words[0].casefold() section = words[0].casefold()
pos = len(section) 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('.') diff = name[pos:].strip('.')
if len(diff) < 2 and (len(diff) == 0 or diff.isalpha()): if len(diff) < 2 and (len(diff) == 0 or diff.isalpha()):
results.append(name) results.append(name)
if not results: if not results:
return 'This section doesn\'t exist, my master!' 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: if other:
text += '\n<i>(Subsections: {}-{})</i>'.format(other[0], other[-1]) text += '\n<i>(Subsections: {}-{})</i>'.format(other[0], other[-1])
if len(text) > 4000: 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: 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) term = ' '.join(words)
if len(words) > 1: 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: if goodCandidates:
nameCandidates = 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: if bestCandidates:
nameCandidates = 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: if excellentCandidate:
nameCandidates = excellentCandidate nameCandidates = excellentCandidate


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


if len(nameCandidates) > 20: 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 return text

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

import json import json
import oracle import oracle
import documents 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): def format_card(card):
mana = '' mana = ''
text, text,
footer) footer)



def preview_card(card): def preview_card(card):
mana = '' mana = ''
if 'manaCost' in card: if 'manaCost' in card:
mana, mana,
card['type']) card['type'])



def start_command(bot, update): def start_command(bot, update):
commands = [ commands = [
'/o <card name or search strings> - oracle text for a card', '/o <card name or search strings> - oracle text for a card',
'/ipg <section> (coming soon)', '/ipg <section> (coming soon)',
'/mtr <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): def oracle_command(bot, update, args):
if not 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 return
words = [word.casefold() for word in args] words = [word.casefold() for word in args]


nameCandidates = oracle.get_matching_names(words) nameCandidates = oracle.get_matching_names(words)


if not nameCandidates: 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 return


if len(nameCandidates) > 20: 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 return


if len(nameCandidates) > 1: 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 return


reply = [] reply = []
for name in nameCandidates: for name in nameCandidates:
for oracleName in oracle.get_oracle_names(name): for oracleName in oracle.get_oracle_names(name):
reply.append(format_card(oracle.get_card(oracleName))) 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): def question_command(bot, update, args):
text = ' '.join(args).casefold() text = ' '.join(args).casefold()


reply = [] reply = []
for name in names: 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: 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): def inline_oracle(bot, update):
query = update.inline_query.query.casefold() query = update.inline_query.query.casefold()
id=card['name'], id=card['name'],
title=word, title=word,
description=preview_card(card), 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) bot.answerInlineQuery(update.inline_query.id, results)



def callback_name(bot, update): def callback_name(bot, update):
message_id = update.callback_query.message.message_id message_id = update.callback_query.message.message_id
chat_id = update.callback_query.message.chat.id chat_id = update.callback_query.message.chat.id
bot.answerCallbackQuery(update.callback_query.id) bot.answerCallbackQuery(update.callback_query.id)
return 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) bot.answerCallbackQuery(update.callback_query.id)



def text(bot, update): def text(bot, update):
if update.message.chat.type != 'private': if update.message.chat.type != 'private':
return return




def comp_rules_command(bot, update, args): 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): def ask_command(bot, update, args):
pass pass



def dispatcher_setup(dispatcher): def dispatcher_setup(dispatcher):
dispatcher.add_handler(CommandHandler('start', start_command)) dispatcher.add_handler(CommandHandler('start', start_command))
dispatcher.add_handler(CommandHandler('help', start_command)) dispatcher.add_handler(CommandHandler('help', start_command))
dispatcher.add_handler(CommandHandler('o', oracle_command, pass_args=True)) 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(CommandHandler('ask', ask_command, pass_args=True))
dispatcher.add_handler(InlineQueryHandler(inline_oracle)) dispatcher.add_handler(InlineQueryHandler(inline_oracle))
dispatcher.add_handler(CallbackQueryHandler(callback_name)) dispatcher.add_handler(CallbackQueryHandler(callback_name))
dispatcher.add_handler(MessageHandler(Filters.text, text)) dispatcher.add_handler(MessageHandler(Filters.text, text))



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



+ 11
- 2
src/oracle.py View File

namesToSearch = names.keys() namesToSearch = names.keys()
with open('data/oracle.json') as file: with open('data/oracle.json') as file:
oracleData = json.load(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): 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) term = ' '.join(words)




return nameCandidates return nameCandidates



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



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



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

Loading…
Cancel
Save