forked from ScottehMax/pyMon
/
utils.py
143 lines (106 loc) · 4.25 KB
/
utils.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
import re
import json
from pyparsing import (Suppress, Regex, quotedString, Word, alphas,
alphanums, oneOf, Forward, Optional, dictOf, delimitedList, Group, removeQuotes)
import requests
def condense(string):
return (re.sub(r'[^A-Za-z0-9]', '', string)).lower()
def old_login(username, password, challenge, challengekeyid):
url = 'http://play.pokemonshowdown.com/action.php'
values = {'act': 'login',
'name': username,
'pass': password,
'challengekeyid': challengekeyid,
'challenge': challenge
}
r = requests.post(url, data=values)
try:
response = json.loads(r.text[1:]) # the JSON response starts with a ]
except Exception as e:
print e
return None
assertion = response['assertion']
return assertion
def login(username, password, challstr):
url = 'http://play.pokemonshowdown.com/action.php'
values = {'act': 'login',
'name': username,
'pass': password,
'challstr': challstr
}
r = requests.post(url, data=values)
try:
response = json.loads(r.text[1:]) # the JSON response starts with a ]
except Exception as e:
print e
return None
assertion = response['assertion']
return assertion
def print_info(obj):
for attrib in dir(obj)[3:]:
print attrib, '-', getattr(obj, attrib)
def get_thread():
catalog_uri = "http://a.4cdn.org/vp/catalog.json"
r = requests.get(catalog_uri)
try:
catalog = json.loads(r.text)
except ValueError:
print "Unable to decode the response"
return False
newest_thread = {'no': 0, 'last_reply_time': 0}
for page in catalog:
for thread in page['threads']:
if (('showderp' in thread.get('sub', '').lower()) or
('showderp' in thread.get('name', '').lower()) or
('showderp' in thread.get('com', '').lower())) and thread.get('last_replies'):
reply_time = thread['last_replies'][-1]['time']
if reply_time > newest_thread['last_reply_time']:
newest_thread['no'] = thread['no']
newest_thread['last_reply_time'] = reply_time
return newest_thread
def get_rank(user, room, ch):
if room not in ch.current_users:
return False
else:
for r_user in ch.current_users[room]:
if condense(user) == condense(r_user):
result = r_user[0]
return result
return False
def get_battle(ch):
battle_regex = "((https?\\:\\/\\/)?(play\\.pokemonshowdown\\.com|.*?\\.psim\\.us)\\/(battle-(?:FORMATS)\\-\\d+))"
real_regex = re.compile(battle_regex.replace('FORMATS', '|'.join(ch.battle_formats)))
thread_info = get_thread()
battle = False
if not thread_info or thread_info['no'] == 0:
return False
r = requests.get('http://a.4cdn.org/vp/res/%s.json' % thread_info['no'])
try:
thread = json.loads(r.text)
except ValueError:
print "Unable to load battle response"
return False
for post in thread['posts']:
if post.get('com'):
m = real_regex.search(post.get('com').replace('<wbr>', ''))
if m:
battle = [m.group(), post['time']]
return battle
def load_js_obj_literal(j):
"""Terrible hack."""
j = j[j.index('{'):]
j = j.replace('\n', '').replace('\t', '')
j = j.replace(';', '')
j = re.sub(r'//.*?{', r'{', j)
LBRACK, RBRACK, LBRACE, RBRACE, COLON, COMMA = map(Suppress,"[]{}:,")
integer = Regex(r"[+-]?\d+").setParseAction(lambda t:int(t[0]))
real = Regex(r"[+-]?\d+\.\d*").setParseAction(lambda t:float(t[0]))
string_ = Word(alphas,alphanums+"_") | quotedString.setParseAction(removeQuotes)
bool_ = oneOf("true false").setParseAction(lambda t: t[0]=="true")
item = Forward()
key = string_
dict_ = LBRACE - Optional(dictOf(key+COLON, item+Optional(COMMA))) + RBRACE
list_ = LBRACK - Optional(delimitedList(item)) + RBRACK
item << (real | integer | string_ | bool_ | Group(list_ | dict_ ))
result = item.parseString(j,parseAll=True)[0]
return result