diff --git a/bot.py b/bot.py
index 8bed9e8..f35a0e8 100644
--- a/bot.py
+++ b/bot.py
@@ -21,51 +21,51 @@ users = {}
class Kuser:
def __init__(self, userid, username='', password='', status='第一次用', question='題外'):
- self._userid = userid
- self._username = username
- self._password = password
- self._status = status
- self._question = question
- self._api = KCOJ(URL)
+ self.userid = userid
+ self.username = username
+ self.password = password
+ self.status = status
+ self.question = question
+ self.api = KCOJ(URL)
def new_user(self):
self.help()
self.press_username()
def press_username(self):
- self._status = '輸入學號'
- self._question = '題外'
- bot.sendMessage(self._userid, "請輸入您的學號:", reply_markup=ReplyKeyboardRemove())
+ self.status = '輸入學號'
+ self.question = '題外'
+ bot.sendMessage(self.userid, "請輸入您的學號:", reply_markup=ReplyKeyboardRemove())
def press_password(self, text):
- self._status = '輸入密碼'
- self._question = '題外'
- self._username = text
- bot.sendMessage(self._userid,
+ self.status = '輸入密碼'
+ self.question = '題外'
+ self.username = text
+ bot.sendMessage(self.userid,
"輸入完可刪除訊息以策安全!\n"
"請輸入您的密碼:", reply_markup=ReplyKeyboardRemove())
def press_oldpassword(self):
- self._status = '舊的密碼'
- self._question = '題外'
- bot.sendMessage(self._userid,
+ self.status = '舊的密碼'
+ self.question = '題外'
+ bot.sendMessage(self.userid,
"請輸入要原本的舊密碼:",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠"]
], resize_keyboard=True))
def press_newpassword(self, text):
- if text != self._password:
- self._status = '正常使用'
- self._question = '題外'
- bot.sendMessage(self._userid, "密碼錯誤!",
+ if text != self.password:
+ self.status = '正常使用'
+ self.question = '題外'
+ bot.sendMessage(self.userid, "密碼錯誤!",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠"]
], resize_keyboard=True))
else:
- self._status = '修改密碼'
- self._question = '題外'
- bot.sendMessage(self._userid,
+ self.status = '修改密碼'
+ self.question = '題外'
+ bot.sendMessage(self.userid,
"使用此功能請務必小心!\n"
"請輸入要設定的新密碼:",
reply_markup=ReplyKeyboardMarkup(keyboard=[
@@ -73,51 +73,51 @@ class Kuser:
], resize_keyboard=True))
def change_password(self, text):
- self._status = '正常使用'
- self._question = '題外'
- self._password = text
- bot.sendMessage(self._userid,
- "修改成功!" if self._api.change_password(self._password) == True else "修改失敗。",
+ self.status = '正常使用'
+ self.question = '題外'
+ self.password = text
+ bot.sendMessage(self.userid,
+ "修改成功!" if self.api.change_password(self.password) == True else "修改失敗。",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠"]
], resize_keyboard=True))
def login(self, text):
- self._status = '正常使用'
- self._question = '題外'
- self._password = text
- bot.sendMessage(self._userid, "登入中...", reply_markup=ReplyKeyboardRemove())
- if self.check_online(self._userid) == True:
- self.show_homepage(self._userid)
+ self.status = '正常使用'
+ self.question = '題外'
+ self.password = text
+ bot.sendMessage(self.userid, "登入中...", reply_markup=ReplyKeyboardRemove())
+ if self.check_online(self.userid) == True:
+ self.show_homepage(self.userid)
def login_failed(self, chat_id, message_id):
- self._status = '正常使用'
- self._question = '題外'
- if chat_id != self._userid:
+ self.status = '正常使用'
+ self.question = '題外'
+ if chat_id != self.userid:
bot.sendMessage(chat_id, "登入失敗,請先私訊我重新登入 KCOJ", reply_to_message_id=message_id)
- bot.sendMessage(self._userid, "哇...登入失敗,讓我們重新開始", reply_markup=ReplyKeyboardRemove())
+ bot.sendMessage(self.userid, "哇...登入失敗,讓我們重新開始", reply_markup=ReplyKeyboardRemove())
self.press_username()
def connect_failed(self, chat_id, message_id):
- self._status = '正常使用'
- self._question = '題外'
- if chat_id != self._userid:
+ self.status = '正常使用'
+ self.question = '題外'
+ if chat_id != self.userid:
bot.sendMessage(chat_id, "KCOJ 離線中!請稍後再試", reply_to_message_id=message_id)
else:
- bot.sendMessage(self._userid, "KCOJ 離線中!請稍後再試",
+ bot.sendMessage(self.userid, "KCOJ 離線中!請稍後再試",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "幫助📚"]
], resize_keyboard=True))
def check_online(self, chat_id, message_id=''):
- result = self._api.check_online()
+ result = self.api.check_online()
if result == None:
self.connect_failed(chat_id, message_id)
return False
else:
if result == False:
- self._api.login(self._username, self._password, 2)
- result = self._api.check_online()
+ self.api.login(self.username, self.password, 2)
+ result = self.api.check_online()
if result == False:
self.login_failed(chat_id, message_id)
elif result == None:
@@ -125,15 +125,15 @@ class Kuser:
return result == True
def logout(self):
- self._status = '正常使用'
- self._question = '題外'
- bot.sendMessage(self._userid, "您現在已經是登出的狀態。", reply_markup=ReplyKeyboardRemove())
+ self.status = '正常使用'
+ self.question = '題外'
+ bot.sendMessage(self.userid, "您現在已經是登出的狀態。", reply_markup=ReplyKeyboardRemove())
self.press_username()
def show_homepage(self, chat_id):
- self._status = '正常使用'
- self._question = '題外'
- q_dict = self._api.list_questions()
+ self.status = '正常使用'
+ self.question = '題外'
+ q_dict = self.api.list_questions()
q_str = ''
for key in q_dict.keys():
if q_dict[key][1] == '期限未到':
@@ -141,7 +141,7 @@ class Kuser:
q_str += "⚠️" if q_dict[key][2] == '未繳' else "✅"
q_str += " /question_" + key + "\n\n"
bot.sendMessage(chat_id,
- "💁 " + self._username + " " + NAME + "\n"
+ "💁 " + self.username + " " + NAME + "\n"
"➖➖➖➖➖\n"
"📝可繳交的作業\n\n" + q_str + \
"➖➖➖➖➖\n" + choice(promote.sentences),
@@ -149,13 +149,13 @@ class Kuser:
reply_markup=ReplyKeyboardMarkup(keyboard=[
["題庫📝"],
["登出🚪", "改密碼💱", "幫助📚"]
- ], resize_keyboard=True) if chat_id == self._userid else ReplyKeyboardRemove(),
+ ], resize_keyboard=True) if chat_id == self.userid else ReplyKeyboardRemove(),
disable_web_page_preview=False)
def list_questions(self, chat_id):
- self._status = '正常使用'
- self._question = '題外'
- q_dict = self._api.list_questions()
+ self.status = '正常使用'
+ self.question = '題外'
+ q_dict = self.api.list_questions()
q_str = ''
for key in q_dict.keys():
q_str += "📗" if q_dict[key][1] == '期限未到' else "📕"
@@ -163,7 +163,7 @@ class Kuser:
q_str += "⚠️" if q_dict[key][2] == '未繳' else "✅"
q_str += " /question_" + key + "\n\n"
reply = bot.sendMessage(chat_id,
- "💁 " + self._username + " " + NAME + "\n"
+ "💁 " + self.username + " " + NAME + "\n"
"➖➖➖➖➖\n"
"📝所有作業\n\n" + q_str + \
"➖➖➖➖➖\n" + choice(promote.sentences),
@@ -171,21 +171,21 @@ class Kuser:
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "更新🔃"],
["登出🚪", "改密碼💱", "幫助📚"]
- ], resize_keyboard=True) if chat_id == self._userid else ReplyKeyboardRemove(),
+ ], resize_keyboard=True) if chat_id == self.userid else ReplyKeyboardRemove(),
disable_web_page_preview=False)
bot.sendMessage(chat_id, "點我到題庫頂", reply_to_message_id=reply['message_id'])
def show_question(self, number, chat_id):
- self._status = '查看題目'
- self._question = number
+ self.status = '查看題目'
+ self.question = number
if number in external.QUESTION:
ext_q = True
content = external.QUESTION[number]
else:
ext_q = False
- content = '```\n' + self._api.show_question(number) + '\n```'
- q = self._api.list_questions()[number]
- q_str = "💁 *" + self._username + "* [" + NAME + "]\n"
+ content = '```\n' + self.api.show_question(number) + '\n```'
+ q = self.api.list_questions()[number]
+ q_str = "💁 *" + self.username + "* [" + NAME + "]\n"
q_str += "➖➖➖➖➖\n"
q_str += "📗" if q[1] == '期限未到' else "📕"
q_str += "*" + number + "* (DL: " + q[0] + ")\n [[[" + q[3] + "]]] [[[" + q[2] + "]]]"
@@ -196,12 +196,12 @@ class Kuser:
["首頁🏠", "題庫📝"],
["交作業📮" if q[1] == '期限未到' else '', "看結果☑️" if q[2] == '已繳' else '', "通過者🌐"],
["登出🚪", "改密碼💱", "幫助📚"]
- ], resize_keyboard=True) if chat_id == self._userid else ReplyKeyboardRemove())
+ ], resize_keyboard=True) if chat_id == self.userid else ReplyKeyboardRemove())
if ext_q == False:
bot.sendMessage(chat_id, "點我到題目頂", reply_to_message_id=reply['message_id'])
def help(self):
- bot.sendMessage(self._userid,
+ bot.sendMessage(self.userid,
"這裡是 Kuo C Online Judge Bot!\n"
"可以簡稱 KCOJ Bot,目前定居於 [" + NAME + "]\n"
"作用是讓大家可以方便的透過我使用郭老程設課的 Online Judge\n"
@@ -223,27 +223,27 @@ class Kuser:
parse_mode='Markdown')
def upload_answer(self):
- self._status = '上傳答案'
- q = self._api.list_questions()[self._question]
- q_str = "💁 " + self._username + " " + NAME + "\n"
+ self.status = '上傳答案'
+ q = self.api.list_questions()[self.question]
+ q_str = "💁 " + self.username + " " + NAME + "\n"
q_str += "➖➖➖➖➖\n"
q_str += "📗" if q[1] == '期限未到' else "📕"
- q_str += "" + self._question + " (DL: " + q[0] + ")\n [[" + q[3] + "]] [[" + q[2] + "]]"
+ q_str += "" + self.question + " (DL: " + q[0] + ")\n [[" + q[3] + "]] [[" + q[2] + "]]"
q_str += "⚠️" if q[2] == '未繳' else "✅"
- bot.sendMessage(self._userid,
+ bot.sendMessage(self.userid,
q_str + "\n\n現在請把你的程式碼讓我看看(請別超過 20 MB)\n"
"可以使用「文字訊息」或是「傳送檔案」的方式\n"
"(注意:可在程式碼前後加上單獨成行的 ``` 避免可能的錯誤。)", parse_mode='HTML',
reply_markup=ReplyKeyboardMarkup(keyboard=[
- ["刪除作業⚔️"] if self._api.list_questions()[self._question][2] == '已繳' else [],
+ ["刪除作業⚔️"] if self.api.list_questions()[self.question][2] == '已繳' else [],
["首頁🏠", "回題目📜"]
], resize_keyboard=True))
def send_answer(self, text, file_id):
- self._status = '正常使用'
+ self.status = '正常使用'
# define filename
- filename = sys.path[0] + '/' + self._username + self._question
- if self._api.list_questions()[self._question][3] == 'Python':
+ filename = sys.path[0] + '/' + self.username + self.question
+ if self.api.list_questions()[self.question][3] == 'Python':
filename += '.py'
else:
filename += '.c'
@@ -253,16 +253,16 @@ class Kuser:
f.write(text)
else:
bot.download_file(file_id, filename)
- self._api.delete_answer(self._question)
- if self._api.upload_answer(self._question, filename) == True:
- bot.sendMessage(self._userid, "上傳成功",
+ self.api.delete_answer(self.question)
+ if self.api.upload_answer(self.question, filename) == True:
+ bot.sendMessage(self.userid, "上傳成功",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "回題目📜"],
["看結果☑️"],
["登出🚪", "改密碼💱", "幫助📚"]
], resize_keyboard=True))
else:
- bot.sendMessage(self._userid, "上傳失敗",
+ bot.sendMessage(self.userid, "上傳失敗",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "回題目📜"],
["登出🚪", "改密碼💱", "幫助📚"]
@@ -270,51 +270,51 @@ class Kuser:
os.remove(filename)
def delete_answer(self):
- bot.sendMessage(self._userid, "移除成功" if self._api.delete_answer(self._question) == True else "移除失敗",
+ bot.sendMessage(self.userid, "移除成功" if self.api.delete_answer(self.question) == True else "移除失敗",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "回題目📜"],
["登出🚪", "改密碼💱", "幫助📚"]
], resize_keyboard=True))
def send_failed(self):
- self._status = '正常使用'
- bot.sendMessage(self._userid, "檔案不能超過 20 MB!上傳失敗",
+ self.status = '正常使用'
+ bot.sendMessage(self.userid, "檔案不能超過 20 MB!上傳失敗",
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "回題目📜"],
["登出🚪", "改密碼💱", "幫助📚"]
], resize_keyboard=True))
def list_passers(self):
- self._status = '正常使用'
- q = self._api.list_questions()[self._question]
- q_str = "💁 " + self._username + " " + NAME + "\n"
+ self.status = '正常使用'
+ q = self.api.list_questions()[self.question]
+ q_str = "💁 " + self.username + " " + NAME + "\n"
q_str += "➖➖➖➖➖\n"
q_str += "📗" if q[1] == '期限未到' else "📕"
- q_str += "" + self._question + " (DL: " + q[0] + ")\n [[" + q[3] + "]] [[" + q[2] + "]]"
+ q_str += "" + self.question + " (DL: " + q[0] + ")\n [[" + q[3] + "]] [[" + q[2] + "]]"
q_str += "⚠️" if q[2] == '未繳' else "✅"
q_str += "\n"
- for passer in self._api.list_passers(self._question):
+ for passer in self.api.list_passers(self.question):
q_str += "\n" + passer
- reply = bot.sendMessage(self._userid, q_str + "
",
+ reply = bot.sendMessage(self.userid, q_str + "",
parse_mode='HTML',
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "回題目📜"],
["登出🚪", "改密碼💱", "幫助📚"]
], resize_keyboard=True))
- bot.sendMessage(self._userid, "點我到名單頂", reply_to_message_id=reply['message_id'])
+ bot.sendMessage(self.userid, "點我到名單頂", reply_to_message_id=reply['message_id'])
def list_results(self):
- self._status = '正常使用'
- q = self._api.list_questions()[self._question]
- q_str = "💁 " + self._username + " " + NAME + "\n"
+ self.status = '正常使用'
+ q = self.api.list_questions()[self.question]
+ q_str = "💁 " + self.username + " " + NAME + "\n"
q_str += "➖➖➖➖➖\n"
q_str += "📗" if q[1] == '期限未到' else "📕"
- q_str += "" + self._question + " (DL: " + q[0] + ")\n"
- for result in self._api.list_results(self._question, self._username):
+ q_str += "" + self.question + " (DL: " + q[0] + ")\n"
+ for result in self.api.list_results(self.question, self.username):
q_str += "\n測試編號 " + result[0] + "
:"
q_str += "✔️ " if result[1] == '通過測試' else "❌ "
q_str += result[1]
- bot.sendMessage(self._userid, q_str,
+ bot.sendMessage(self.userid, q_str,
parse_mode='HTML',
reply_markup=ReplyKeyboardMarkup(keyboard=[
["首頁🏠", "回題目📜"],
@@ -343,7 +343,7 @@ def on_chat(msg):
last_name = ''
print("😊 student_name:", msg['from']['first_name'], last_name, "😊")
# id
- print("😯 student_id:", user._username, "😯")
+ print("😯 student_id:", user.username, "😯")
print()
# ==========================================================
@@ -365,17 +365,17 @@ def on_chat(msg):
user.help()
# first-time user
- elif user._status == '第一次用':
+ elif user.status == '第一次用':
if chat_type == 'private':
user.new_user()
# press password
- elif user._status == '輸入學號':
+ elif user.status == '輸入學號':
if chat_type == 'private':
user.press_password(msg['text'])
# login
- elif user._status == '輸入密碼':
+ elif user.status == '輸入密碼':
if chat_type == 'private':
user.login(msg['text'])
@@ -401,35 +401,35 @@ def on_chat(msg):
users[str(from_id)] = user
user.logout()
- elif (command[0] == '/delete' or command[0] == '刪除作業⚔️') and user._question != '題外':
+ elif (command[0] == '/delete' or command[0] == '刪除作業⚔️') and user.question != '題外':
if user.check_online(chat_id, msg['message_id']) == True:
user.delete_answer()
- elif (command[0] == '/upload' or command[0] == '交作業📮') and user._question != '題外':
+ elif (command[0] == '/upload' or command[0] == '交作業📮') and user.question != '題外':
if user.check_online(chat_id, msg['message_id']) == True:
user.upload_answer()
- elif (command[0] == '/result' or command[0] == '看結果☑️') and user._question != '題外':
+ elif (command[0] == '/result' or command[0] == '看結果☑️') and user.question != '題外':
if user.check_online(chat_id, msg['message_id']) == True:
user.list_results()
- elif (command[0] == '/passer' or command[0] == '通過者🌐') and user._question != '題外':
+ elif (command[0] == '/passer' or command[0] == '通過者🌐') and user.question != '題外':
if user.check_online(chat_id, msg['message_id']) == True:
user.list_passers()
- elif command[0] == '回題目📜' and user._question != '題外':
+ elif command[0] == '回題目📜' and user.question != '題外':
if user.check_online(chat_id, msg['message_id']) == True:
- user.show_question(user._question, chat_id)
+ user.show_question(user.question, chat_id)
- elif user._status == '舊的密碼':
+ elif user.status == '舊的密碼':
if user.check_online(chat_id, msg['message_id']) == True:
user.press_newpassword(msg['text'])
- elif user._status == '修改密碼':
+ elif user.status == '修改密碼':
if user.check_online(chat_id, msg['message_id']) == True:
user.change_password(msg['text'])
- elif user._status == '上傳答案':
+ elif user.status == '上傳答案':
if user.check_online(chat_id, msg['message_id']) == True:
user.send_answer(msg['text'], '')
@@ -438,7 +438,7 @@ def on_chat(msg):
bot.sendMessage(chat_id, "(ˊ・ω・ˋ)")
elif content_type == 'document':
- if user._status == '上傳答案' or user._status == '查看題目':
+ if user.status == '上傳答案' or user.status == '查看題目':
if user.check_online(chat_id, msg['message_id']) == True:
if msg['document']['file_size'] > 167770000:
user.send_failed()
@@ -450,11 +450,11 @@ def backup_db():
for key in users.keys():
user = users[key]
users_backup[key] = {
- 'userid': user._userid,
- 'username': user._username,
- 'password': user._password,
- 'status': user._status,
- 'question': user._question
+ 'userid': user.userid,
+ 'username': user.username,
+ 'password': user.password,
+ 'status': user.status,
+ 'question': user.question
}
with open(sys.path[0] + '/users.json', 'w') as f:
json.dump(users_backup, f, indent=' ')
diff --git a/kcoj.py b/kcoj.py
index 9acf4f2..cc86969 100644
--- a/kcoj.py
+++ b/kcoj.py
@@ -4,22 +4,22 @@ from bs4 import BeautifulSoup
class KCOJ:
def __init__(self, url):
- self._url = url
- self._session = requests.Session()
+ self.url = url
+ self.session = requests.Session()
# login KCOJ
def login(self, username, password, course):
try:
payload = {'name': username,
'passwd': password,
'rdoCourse': course}
- return self._session.post(self._url + '/Login', data=payload, timeout=0.5)
+ return self.session.post(self.url + '/Login', data=payload, timeout=0.5)
except requests.exceptions.Timeout:
return None
# check online status
def check_online(self):
try:
- response = self._session.get(self._url + '/TopMenu', timeout=0.5)
+ response = self.session.get(self.url + '/TopMenu', timeout=0.5)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.find('a').get_text().strip() == '線上考試'
except requests.exceptions.Timeout:
@@ -29,7 +29,7 @@ class KCOJ:
def list_questions(self):
try:
questions = {}
- response = self._session.get(self._url + '/HomeworkBoard', timeout=0.5)
+ response = self.session.get(self.url + '/HomeworkBoard', timeout=0.5)
soup = BeautifulSoup(response.text, 'html.parser')
for tag in soup.find_all('tr'):
if tag.find('a') == None:
@@ -48,7 +48,7 @@ class KCOJ:
# show the content of the question
def show_question(self, number):
try:
- response = self._session.get(self._url + '/showHomework', params={'hwId': number}, timeout=0.5)
+ response = self.session.get(self.url + '/showHomework', params={'hwId': number}, timeout=0.5)
soup = BeautifulSoup(response.text, 'html.parser')
raw = soup.find('body').get_text().replace('繳交作業', '').strip()
content = ''
@@ -62,7 +62,7 @@ class KCOJ:
def list_passers(self, number):
try:
passers = []
- response = self._session.get(self._url + '/success.jsp', params={'HW_ID': number}, timeout=0.5)
+ response = self.session.get(self.url + '/success.jsp', params={'HW_ID': number}, timeout=0.5)
soup = BeautifulSoup(response.text, 'html.parser')
for tr in soup.find_all('tr'):
passer = tr.get_text().replace('\n', '').strip()
@@ -76,7 +76,7 @@ class KCOJ:
def list_results(self, number, username):
try:
results = []
- response = self._session.get(self._url + '/CheckResult.jsp', params={'questionID': number, 'studentID': username}, timeout=0.5)
+ response = self.session.get(self.url + '/CheckResult.jsp', params={'questionID': number, 'studentID': username}, timeout=0.5)
soup = BeautifulSoup(response.text, 'html.parser')
for tr in soup.find_all('tr'):
td = tr.find('td')
@@ -91,7 +91,7 @@ class KCOJ:
try:
payload = {'pass': password,
'submit': 'sumit'}
- response = self._session.post(self._url + '/changePasswd', data=payload, timeout=0.5)
+ response = self.session.post(self.url + '/changePasswd', data=payload, timeout=0.5)
soup = BeautifulSoup(response.text, 'html.parser')
return str(soup.find('body')).split()[-2].strip() == 'Success'
except requests.exceptions.Timeout:
@@ -100,7 +100,7 @@ class KCOJ:
# delete the answer of the question
def delete_answer(self, number):
try:
- response = self._session.get(self._url + '/delHw', params={'title': number}, timeout=0.5)
+ response = self.session.get(self.url + '/delHw', params={'title': number}, timeout=0.5)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.find('body').get_text().replace('\n', '').strip() == 'delete success'
except requests.exceptions.Timeout:
@@ -109,8 +109,8 @@ class KCOJ:
# hand in a answer
def upload_answer(self, number, file_path):
try:
- self._session.get(self._url + '/upLoadHw', params={'hwId': number}, timeout=0.5)
- response = self._session.post(self._url + '/upLoadFile',
+ self.session.get(self.url + '/upLoadHw', params={'hwId': number}, timeout=0.5)
+ response = self.session.post(self.url + '/upLoadFile',
data={'FileDesc': 'Send from kcoj_bot'},
files={'hwFile': open(file_path, 'rb')},
timeout=0.5)