-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
169 lines (144 loc) · 6.23 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""
TODO:
customize help screen
add option to schedule tsume
segmentize tsume solution
"""
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import json
import random
import csv
from github import Github
import itertools
import io
import re
load_dotenv()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
QBANK_LINK = os.getenv("QBANK_LINK")
bot = commands.Bot(command_prefix='$', activity=discord.Game('$help | Please message Carl#7846 for support'))
bot.remove_command('help')
allTsumes = []
tsumeSorted = {'1': [], '3': [], '5': [], '7': []}
g = Github(GITHUB_TOKEN)
qbankRepo = g.get_repo(QBANK_LINK)
def download_file_from_github(pathToFile):
print(pathToFile)
return qbankRepo.get_contents(pathToFile).decoded_content
tsumeLengths = {
'https://www.shogitown.com/beginner/1tetume/1tetume.html':'1',
'https://www.shogitown.com/beginner/tume/tume.html':'3',
'https://www.shogitown.com/beginner/5te_2004/5te_tume.html': '5'
}
# load tsumes from shogitown txt
jsonList = json.loads('[' + ','.join(open('links_shogitown.txt', 'r').readlines()) + ']')
for jsonObj in jsonList:
tsumeLength = tsumeLengths[jsonObj['source']]
jsonObj['te'] = tsumeLength
# load tsumes from qbank
pathToCsv = 'tsuminaref/reference.csv'
response = download_file_from_github(pathToCsv)
qbankCsv = csv.DictReader(response.decode('utf-8').splitlines(), delimiter='\t')
qbankList = []
for row in qbankCsv:
row['filename_new_q'] = row['filename_new_q'].replace('png', 'jpg')
row['filename_new_a'] = row['filename_new_a'].replace('png', 'jpg')
row['questionGithub'] = 'tsuminator/question_bank/' + row['filename_new_q']
row['answerGithub'] = 'tsuminator/question_bank/' + row['filename_new_a']
qbankList.append(row)
index = 0
for jsonObj in itertools.chain(jsonList, qbankList):
allTsumes.append(jsonObj)
jsonObj['index'] = index
tsumeSorted[jsonObj['te']].append(jsonObj)
index += 1
@bot.command()
async def tsume(ctx, *args):
""""""
isZeroArgs = len(args) == 0
isArgX = False if isZeroArgs else str(args[0]).lower() == 'x'
if not isZeroArgs:
matcher = re.match(r'^(\d*)-(\d*)$', args[0])
if matcher:
lower = int(matcher[1])
upper = int(matcher[2])
if isZeroArgs or args[0].replace('te', '') in tsumeSorted.keys() or (matcher and lower <= upper) or isArgX:
if not isZeroArgs and not isArgX:
te = args[0].replace('te', '')
if matcher:
tsumeLists = []
for i in tsumeSorted:
if lower <= int(i) and int(i) <= upper:
tsumeLists.append(tsumeSorted[i])
randomTsume = random.choice(random.choices(tsumeLists, weights=map(len, tsumeLists))[0])
else:
randomTsumeNum = random.randint(0, len(tsumeSorted[te])-1)
randomTsume = tsumeSorted[te][randomTsumeNum]
else:
randomTsumeNum = random.randint(0, len(allTsumes)-1)
randomTsume = allTsumes[randomTsumeNum]
embed = discord.Embed(
title='Random Tsume #%s' % randomTsume['index'],
description='%sTo get the answer type `$answer %i`' % ('' if isArgX else randomTsume['te'] + 'te. ', randomTsume['index']) ,
color=0x00ff00)
if randomTsume.get('question'):
embed.set_image(url=randomTsume['question'])
await ctx.send(embed=embed)
else:
imgBin = download_file_from_github(randomTsume['questionGithub'])
imgObj = io.BytesIO(imgBin)
imgFile = discord.File(imgObj, filename=randomTsume['filename_new_q'])
embed.set_image(url='attachment://' + randomTsume['filename_new_q'])
await ctx.send(file=imgFile, embed=embed)
@bot.command()
async def answer(ctx, arg:int):
if arg >= 0 and arg < len(allTsumes):
currTsume = allTsumes[arg]
if currTsume.get('answer'):
await ctx.send('Solution to tsume #%s: ||%s||' % (arg, currTsume['answer']))
else:
imgBin = download_file_from_github(currTsume['answerGithub'])
imgObj = io.BytesIO(imgBin)
imgFile = discord.File(imgObj, filename='SPOILER_' + currTsume['filename_new_a'])
# embed.set_image(url='attachment://' + currTsume['answerGithub'])
await ctx.send('Solution to tsume #%s (click to show spoiler)' % arg, file=imgFile)
@bot.command()
async def pat(ctx):
embed = discord.Embed(
title='Thanks.',
color=0xFF7F7F)
embed.set_image(url="https://github.com/raw/justremember/tsuminator/master/lklk.png")
await ctx.send(embed=embed, delete_after=5)
@bot.command()
async def help(ctx):
embed = discord.Embed(
colour = discord.Colour.orange()
)
embed.set_author(name='Tsuminator Help')
embed.add_field(name='$tsume', value='Get random tsume. Sample arguments: 3te, 1te, 5, 3-7, or no argument. Currently available tsumes are from 1te to 7te. Also accepts x as argument, to hide the # of moves.', inline=False)
embed.add_field(name='$answer', value='Get answer to a tsume. Takes a tsume # as argument.', inline=False)
embed.add_field(name='$help', value='Shows this help message.', inline=False)
embed.add_field(name='What is tsume?', value='Tsumeshogi are checkmate problems in shogi. More info: http://www.shogi.net/nexus/ladder/help.html', inline=False)
embed.add_field(name='Too hard! I want easier problems.', value='Check out https://lishogi.org/study/Ke2kN7y8 for easier tsumeshogi.', inline=False)
await ctx.send(embed=embed)
# simple http server for pings
import threading
def serve():
import http.server
import socketserver
from http import HTTPStatus
PORT = int(os.getenv("PORT") or 8080)
class Handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(HTTPStatus.OK)
self.end_headers()
self.wfile.write(b'Tsuminator is up')
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
thr = threading.Thread(target=serve, name='Http')
thr.start()
bot.run(DISCORD_TOKEN)