forked from Armando-J/post_bot
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathvndb.py
More file actions
123 lines (102 loc) · 3.92 KB
/
vndb.py
File metadata and controls
123 lines (102 loc) · 3.92 KB
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
"""
@author: HarHar (https://github.com/HarHar)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
py3 conversion by RathHunt (https://github.com/RathHunt)
"""
import socket
try:
import ujson as json
except:
import json
class vndbException(Exception):
pass
class VNDB(object):
""" Python interface for vndb's api (vndb.org)"""
protocol = 1
def __init__(self, clientname, clientver, username=None, password=None, debug=False):
self.sock = socket.socket()
if debug:
print('Connecting to api.vndb.org')
self.sock.connect(('api.vndb.org', 19534))
if debug:
print('Connected')
if debug:
print('Authenticating')
if (username == None) or (password == None):
self.sendCommand('login', {'protocol': self.protocol, 'client': clientname,
'clientver': float(clientver)})
else:
self.sendCommand('login', {'protocol': self.protocol, 'client': clientname,
'clientver': float(clientver), 'username': username, 'password': password})
res = self.getRawResponse()
if res.find('error ') == 0:
raise vndbException(json.loads(
' '.join(res.split(' ')[1:]))['msg'])
if debug:
print('Authenticated')
def close(self):
self.sock.close()
def get(self, type, flags, filters, options):
""" Gets a VN/producer
Example:
>>> results = vndb.get('vn', 'basic', '(title="Clannad")', '')
>>> results['items'][0]['image']
u'http://s.vndb.org/cv/99/4599.jpg'
"""
args = '{0} {1} {2} {3}'.format(type, flags, filters, options)
self.sendCommand('get', args)
res = self.getResponse()[1]
return res
def sendCommand(self, command, args=None):
""" Sends a command
Example
>>> self.sendCommand('test', {'this is an': 'argument'})
"""
whole = ''
whole += command.lower()
if isinstance(args, str):
whole += ' ' + args
elif isinstance(args, dict):
whole += ' ' + json.dumps(args)
self.sock.send(('{0}\x04'.format(whole)).encode('utf-8'))
def getResponse(self):
""" Returns a tuple of the response to a command that was previously sent
Example
>>> self.sendCommand('test')
>>> self.getResponse()
('ok', {'test': 0})
"""
res = self.getRawResponse()
cmdname = res.split(' ')[0]
if len(res.split(' ')) > 1:
args = json.loads(' '.join(res.split(' ')[1:]))
if cmdname == 'error':
if args['id'] == 'throttled':
raise vndbException(
'Throttled, limit of 100 commands per 10 minutes')
else:
raise vndbException(args['msg'])
return (cmdname, args)
def getRawResponse(self):
""" Returns a raw response to a command that was previously sent
Example:
>>> self.sendCommand('test')
>>> self.getRawResponse()
'ok {"test": 0}'
"""
finished = False
whole = ''
while not finished:
whole += (self.sock.recv(4096)).decode('utf-8')
if '\x04' in whole:
finished = True
return whole.replace('\x04', '').strip()