-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathscroll.py
More file actions
387 lines (353 loc) · 13.9 KB
/
scroll.py
File metadata and controls
387 lines (353 loc) · 13.9 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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#!/usr/bin/env python
# Scroll IRC Art Bot - Developed by acidvegas in Python (https://git.supernets.org/acidvegas/scroll)
# scroll/scroll.py
import asyncio
import random
import re
import ssl
import time
import urllib.request
try:
import aiohttp
except ImportError:
raise SystemExit('missing required aiohttp library (pip install aiohttp)')
try:
import chardet
except ImportError:
raise SystemExit('missing required chardet library (pip install chardet)')
class connection:
server = 'irc.supernets.org'
port = 6697
ipv6 = False
ssl = True
vhost = None # Must in ('ip', port) format
channel = '#superbowl'
key = None
modes = 'BdDg'
class identity:
nickname = 'scroll'
username = 'scroll'
realname = 'git.acid.vegas/scroll'
nickserv = 'changeme'
class repo:
url = 'https://git.supernets.org/'
repo = 'ircart/ircart'
# Settings
admin = 'acidvegas!*@*' # Can use wildcards (Must be in nick!user@host format)
# Formatting Control Characters / Color Codes
bold = '\x02'
italic = '\x1D'
underline = '\x1F'
reverse = '\x16'
reset = '\x0f'
white = '00'
black = '01'
blue = '02'
green = '03'
red = '04'
brown = '05'
purple = '06'
orange = '07'
yellow = '08'
light_green = '09'
cyan = '10'
light_cyan = '11'
light_blue = '12'
pink = '13'
grey = '14'
light_grey = '15'
def color(msg, foreground, background=None):
return f'\x03{foreground},{background}{msg}{reset}' if background else f'\x03{foreground}{msg}{reset}'
def debug(data):
print('{0} | [~] - {1}'.format(time.strftime('%I:%M:%S'), data))
def error(data, reason=None):
print('{0} | [!] - {1} ({2})'.format(time.strftime('%I:%M:%S'), data, str(reason))) if reason else print('{0} | [!] - {1}'.format(time.strftime('%I:%M:%S'), data))
def get_url(url, git=False):
data = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
if git:
data['Accept'] = 'application/vnd.github.v3+json'
req = urllib.request.Request(url, headers=data)
return urllib.request.urlopen(req, timeout=10)
def is_admin(ident):
return re.compile(admin.replace('*','.*')).search(ident)
def ssl_ctx():
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return ctx
class Bot():
def __init__(self):
self.db = None
self.last = time.time()
self.loops = dict()
self.host = ''
self.playing = False
self.settings = {
'flood' : 1,
'ignore' : 'big,birds,doc,gorf,hang,nazi,pokemon',
'lines' : 500,
'msg' : 0.5,
'paste' : True,
'results' : 25}
self.slow = False
self.reader = None
self.writer = None
async def raw(self, data):
self.writer.write(data[:510].encode('utf-8') + b'\r\n')
await self.writer.drain()
async def action(self, chan, msg):
await self.sendmsg(chan, f'\x01ACTION {msg}\x01')
async def sendmsg(self, target, msg):
await self.raw(f'PRIVMSG {target} :{msg}')
async def irc_error(self, chan, msg, reason=None):
await self.sendmsg(chan, '[{0}] {1} {2}'.format(color('ERROR', red), msg, color(f'({reason})', grey))) if reason else await self.sendmsg(chan, '[{0}] {1}'.format(color('ERROR', red), msg))
async def connect(self):
while True:
try:
options = {
'host' : connection.server,
'port' : connection.port,
'limit' : 1024,
'ssl' : ssl_ctx() if connection.ssl else None,
'family' : 10 if connection.ipv6 else 2,
'local_addr' : connection.vhost
}
self.reader, self.writer = await asyncio.wait_for(asyncio.open_connection(**options), 15)
await self.raw(f'USER {identity.username} 0 * :{identity.realname}')
await self.raw('NICK ' + identity.nickname)
except Exception as ex:
error('failed to connect to ' + connection.server, ex)
else:
await self.listen()
finally:
for item in self.loops:
if self.loops[item]:
self.loops[item].cancel()
self.loops = dict()
self.playing = False
self.slow = False
await asyncio.sleep(30)
async def sync(self):
self.db = {'root': []}
page = 1
per_page = 1000 # Gitea's default per_page limit
while True:
try:
timeout = aiohttp.ClientTimeout(total=30)
headers = {'User-Agent': 'scroll/1.0'}
async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
async with session.get(f'{repo.url}/api/v1/repos/{repo.repo}/git/trees/{repo.branch}?recursive=1&page={page}&per_page={per_page}', ssl=False) as resp:
if resp.status != 200:
error('failed to sync database', await resp.text())
return
files = await resp.json()
# Process files from this page
for file in files['tree']:
if file['path'].startswith('ircart/') and file['path'].endswith('.txt') and not file['path'].startswith('ircart/.'):
name = file['path'][7:-4]
if '/' in name:
dir, fname = name.split('/', 1)
self.db[dir] = self.db[dir]+[fname,] if dir in self.db else [fname,]
else:
self.db['root'].append(name)
# Check if we've processed all pages
if not files.get('truncated', False):
break
page += 1
except Exception as ex:
error('failed to sync database', ex)
return
async def play(self, chan, name, paste=False):
try:
if paste:
ascii = get_url(name)
else:
ascii = get_url(f'{repo.url}/{repo.repo}/raw/{repo.branch}/ircart/{name}.txt')
if ascii.getcode() == 200:
raw = ascii.read()
encoding = chardet.detect(raw)['encoding'] or 'utf-8'
ascii = raw.decode(encoding, errors='replace').splitlines()
if len(ascii) > int(self.settings['lines']) and chan != '#scroll':
await self.irc_error(chan, 'file is too big', f'take those {len(ascii):,} lines to #scroll')
else:
if not paste:
await self.action(chan, 'the ascii gods have chosen... ' + color(name, cyan))
for line in ascii:
line = line.replace('\n','').replace('\r','')
await self.sendmsg(chan, line + reset)
await asyncio.sleep(self.settings['msg'])
else:
await self.irc_error(chan, 'invalid name', name) if not paste else await self.irc_error(chan, 'invalid url', name)
except Exception as ex:
try:
await self.irc_error(chan, f'error playing {name}', ex)
except:
error(f'error playing {name}', ex)
finally:
self.playing = False
async def listen(self):
while True:
try:
if self.reader.at_eof():
break
data = await asyncio.wait_for(self.reader.readuntil(b'\r\n'), 600)
line = data.decode('utf-8').strip()
args = line.split()
debug(line)
if line.startswith('ERROR :Closing Link:'):
raise Exception('Connection has closed.')
elif args[0] == 'PING':
await self.raw('PONG '+args[1][1:])
elif args[1] == '001':
if connection.modes:
await self.raw(f'MODE {identity.nickname} +{connection.modes}')
if identity.nickserv:
await self.sendmsg('NickServ', f'IDENTIFY {identity.nickname} {identity.nickserv}')
await asyncio.sleep(6)
await self.raw(f'JOIN {connection.channel} {connection.key}') if connection.key else await self.raw('JOIN ' + connection.channel)
await self.raw('JOIN #scroll')
await self.sync()
elif args[1] == '311' and len(args) >= 6: # RPL_WHOISUSER
nick = args[2]
host = args[5]
if nick == identity.nickname:
self.host = host
elif args[1] == '433':
error('The bot is already running or nick is in use.')
elif args[1] == 'INVITE' and len(args) == 4:
invited = args[2]
chan = args[3][1:]
if invited == identity.nickname and chan in (connection.channel, '#scroll'):
await self.raw(f'JOIN {connection.channel} {connection.key}') if connection.key else await self.raw('JOIN ' + connection.channel)
elif args[1] == 'JOIN' and len(args) >= 3:
nick = args[0].split('!')[0][1:]
host = args[0].split('@')[1]
if nick == identity.nickname:
self.host = host
elif args[1] == 'KICK' and len(args) >= 4:
chan = args[2]
kicked = args[3]
if kicked == identity.nickname and chan in (connection.channel,'#scroll'):
await asyncio.sleep(3)
await self.raw(f'JOIN {connection.channel} {connection.key}') if connection.key else await self.raw('JOIN ' + connection.channel)
elif args[1] == 'PRIVMSG' and len(args) >= 4:
ident = args[0][1:]
nick = args[0].split('!')[0][1:]
chan = args[2]
msg = ' '.join(args[3:])[1:]
if chan in (connection.channel, '#scroll'):
args = msg.split()
if msg == '@scroll':
await self.sendmsg(chan, bold + 'Scroll IRC Art Bot - Developed by acidvegas in Python - https://git.supernets.org/ircart/scroll')
elif args[0] == '.ascii':
if msg == '.ascii stop':
if self.playing:
if chan in self.loops:
self.loops[chan].cancel()
elif time.time() - self.last < self.settings['flood']:
if not self.slow:
if not self.playing:
await self.irc_error(chan, 'slow down nerd')
self.slow = True
elif len(args) >= 2 and not self.playing:
self.slow = False
if msg == '.ascii dirs':
for dir in self.db:
await self.sendmsg(chan, '[{0}] {1}{2}'.format(color(str(list(self.db).index(dir)+1).zfill(2), pink), dir.ljust(10), color('('+str(len(self.db[dir]))+')', grey)))
await asyncio.sleep(self.settings['msg'])
elif msg == '.ascii list':
await self.sendmsg(chan, underline + color(f'{repo.url}/{repo.repo}/src/{repo.branch}/ircart/.list', light_blue))
elif args[1] == 'random' and len(args) in (2,3):
if len(args) == 3:
query = args[2]
else:
choices = [item for item in self.db if item not in self.settings['ignore'] and self.db[item]]
if not choices:
await self.irc_error(chan, 'database is empty', 'try .ascii sync')
continue
query = random.choice(choices)
if query in self.db and self.db[query]:
ascii = f'{query}/{random.choice(self.db[query])}'
self.playing = True
self.loops[chan] = asyncio.create_task(self.play(chan, ascii))
else:
results = [{'name':ascii,'dir':dir} for dir in self.db for ascii in self.db[dir] if query in ascii]
if results:
ascii = random.choice(results)
ascii = f'{ascii["dir"]}/{ascii["name"]}'
self.playing = True
self.loops[chan] = asyncio.create_task(self.play(chan, ascii))
else:
await self.irc_error(chan, 'invalid directory name or search query', query)
elif msg == '.ascii sync' and is_admin(ident):
await self.sync()
await self.sendmsg(chan, bold + color('database synced', light_green))
elif args[1] == 'play' and len(args) == 3 and self.settings['paste']:
url = args[2]
if url.startswith('https://pastebin.com/raw/') and len(url.split('raw/')) > 1:
self.loops[chan] = asyncio.create_task(self.play(chan, url, paste=True))
else:
await self.irc_error(chan, 'invalid pastebin url', url)
elif args[1] == 'search' and len(args) == 3:
query = args[2]
results = [{'name':ascii,'dir':dir} for dir in self.db for ascii in self.db[dir] if query in ascii]
if results:
for item in results[:int(self.settings['results'])]:
if item['dir'] == 'root':
await self.sendmsg(chan, '[{0}] {1}'.format(color(str(results.index(item)+1).zfill(2), pink), item['name']))
else:
await self.sendmsg(chan, '[{0}] {1} {2}'.format(color(str(results.index(item)+1).zfill(2), pink), item['name'], color('('+item['dir']+')', grey)))
await asyncio.sleep(self.settings['msg'])
else:
await self.irc_error(chan, 'no results found', query)
elif args[1] == 'settings':
if len(args) == 2:
for item in self.settings:
await self.sendmsg(chan, color(item.ljust(13), yellow) + color(str(self.settings[item]), grey))
elif len(args) == 4 and is_admin(ident):
setting = args[2]
option = args[3]
if setting in self.settings:
if setting in ('flood','lines','msg','results'):
try:
option = float(option)
self.settings[setting] = option
await self.sendmsg(chan, color('OK', light_green))
except ValueError:
await self.irc_error(chan, 'invalid option', 'must be a float or int')
elif setting == 'paste':
if option == 'on':
self.settings[setting] = True
await self.sendmsg(chan, color('OK', light_green))
elif option == 'off':
self.settings[setting] = False
await self.sendmsg(chan, color('OK', light_green))
else:
await self.irc_error(chan, 'invalid option', 'must be on or off')
else:
await self.irc_error(chan, 'invalid setting', setting)
elif len(args) == 2:
query = args[1]
results = [dir+'/'+ascii for dir in self.db for ascii in self.db[dir] if query == ascii]
if results:
results = results[0].replace('root/','')
self.playing = True
self.loops[chan] = asyncio.create_task(self.play(chan, results))
else:
await self.irc_error(chan, 'no results found', query)
except (UnicodeDecodeError, UnicodeEncodeError):
pass
except Exception as ex:
error('fatal error occured', ex)
break
finally:
self.last = time.time()
if __name__ == '__main__':
print('#'*56)
print('#{:^54}#'.format(''))
print('#{:^54}#'.format('Scroll IRC Art Bot'))
print('#{:^54}#'.format('Developed by acidvegas in Python'))
print('#{:^54}#'.format('https://git.supernets.org/ircart/scroll'))
print('#{:^54}#'.format(''))
print('#'*56)
asyncio.run(Bot().connect())