forked from pyhoneybot/honeybot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
618 lines (503 loc) 路 16 KB
/
main.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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# -*- coding: utf-8 -*-
"""
Example Google style docstrings.
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
Attributes:
connect_config (ConfigParser): Module level variables may be documented in
either the ``Attributes`` section of the module docstring, or in an
inline docstring immediately following the variable.
Either form is acceptable, but the two should not be mixed. Choose
one convention to document module level variables and be consistent
with it.
memory_reader (ConfigParser): TODO.
pluggins (List): TODO.
logger (Logger): TODO.
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
"""
import configparser
import importlib
import logging
import socket
import sys
import time
connect_config = configparser.ConfigParser()
connect_config.read('settings/CONNECT.conf')
memory_reader = configparser.ConfigParser()
plugins = []
# Start logger
logger = logging.getLogger('bot_core')
"""
BOT CONNECTION SETUP
"""
class Bot_core(object):
"""
Core of the bot.
Detailed Description.
Args:
password (str): Password for the bot, defaults to ''
Attributes:
server_url (str): String for the IRC Server.
port (int): Port for the IRC Server.
name (str): Name of the bot.
owners (list of str): String list of owners.
password (str): Password of the bot.
friends (list of str): String list of friends.
autojoin_channels (list of str): String list of autojoin_channels.
required_modules (list of str): String list of required modules.
time (time): Get the current time.
irc (socket): socket for the IRC server.
isListenOn (int): TODO.
domain (str): Server domain.
sp_command (str): command string of the bot.
plugins (lsit of str): List of plugins.
"""
def __init__(self, password=''):
self.server_url = connect_config['INFO']['server_url']
self.port = int(connect_config['INFO']['port'])
self.name = connect_config['INFO']['name']
self.owners = self.configfile_to_list('OWNERS')
self.password = password
self.friends = self.configfile_to_list('FRIENDS')
self.autojoin_channels = self.configfile_to_list('AUTOJOIN_CHANNELS')
self.required_modules = self.requirements()
self.time = time.time()
self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.isListenOn = 1
dom = self.server_url.split('.')
self.domain = '.'.join(dom[-2:])
self.sp_command = 'hbot'
self.plugins = []
"""
STRINGS
"""
def set_nick_command(self):
"""
Get string for set nickname command.
Returns:
str: String for the set nick command.
Examples:
bot_core = Bot_core()
bot_core.set_nick_command()
"""
return 'NICK {0} \r\n'.format(self.name)
def present_command(self):
"""
Get string for present command.
Returns:
str: String for the present command.
Examples:
bot_core = Bot_core()
bot_core.present_command()
"""
return 'USER {0} {0} {0} : {0} IRC\r\n'.format(self.name)
def identify_command(self):
"""
Get string for identify command.
Returns:
str: Command for the identify command.
Examples:
bot_core = Bot_core()
bot_core.identify_command()
"""
return 'msg NickServ identify {0} \r\n'.format(self.password)
def join_channel_command(self, channel):
"""
Get string for join channel command.
Args:
channel (str): String of the channelname command.
Returns:
str: Command to join Channel.
Examples:
channel_name_command = '<command_name>'
bot_core = Bot_core()
bot_core.join_channel_command(channel_name_command)
"""
return 'JOIN {0} \r\n'.format(channel)
def specific_send_command(self, target, msg):
"""
Get string for specific send command.
Args:
target (str): String of the target that should receive the message.
msg (str): String of the Message that's to be sent to target.
Returns:
str: Command for messaging specific user.
Examples:
target_name = '<target_name>'
str msg = 'I am a test message'
bot_core = Bot_core()
bot_core.specific_send_command(target_name, msg)
"""
return "PRIVMSG {0} :{1}\r\n".format(target,msg)
def pong_return(self, domain):
"""
Get string for Pong command.
Args:
domain(str): String of the current domain.
Returns:
str: Command for Pong.
Examples:
domain_name = '<current user domain>'
bot_core = Bot_core()
bot_core.pong_return(domain_name)
"""
return 'PONG :{}\r\n'.format(domain)
"""
MESSAGE VALIDATION
"""
def message_info(self, s):
"""
Get info of a message.
Args:
s(str): Incoming message information
Returns:
dict of {str: str}: interprets the incoming message and splits the message to get the following information out of the message viz 'prefix', 'command', 'args', 'address', 'user'. Then returns the information as a dictionary containing following information:
{
'prefix': <prefix_string_value>\
'command': <command_string_value>\
'args': <array_of_argument_strings>\
'address': <target address to which the message was sent>\
'user':<user name who sent the message>\
}
Examples:
message = '<incoming message>'
bot_core = Bot_core()
bot_core.message_info(message)
"""
def prevent_none(x):
"""
Processes the arguments for None values.
Args:
x(any or None): can be any type of variable
Returns:
Union of [x,''](any or str): returns x if x is not None else ''.
Examples:
x = ['a', 'b']
prevent_none(message)
"""
return x if x else ''
try:
prefix = ''
trailing = []
address = ''
if not s:
pass
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
address = args[0] if '#' in args[0] else prefix.split('!~')[0]
user = prefix.split('!')[0]
# return prefix, command, args, address
return {
'prefix': prevent_none(prefix),
'command': prevent_none(command),
'args': ['' if e is None else e for e in args],
'address': prevent_none(address),
'user': prevent_none(user)
}
except Exception as e:
logger.error(e)
def bot_info(self):
"""
Get bot info.
Returns:
dict of {str: str}: TODO.
Examples:
bot_core = Bot_core()
bot_core.bot_info(message)
"""
return {
'name': self.name,
'special_command': self.sp_command,
'required_modules': self.required_modules,
'owners': self.owners,
'time': self.time,
'friends': self.friends
}
"""
MESSAGE UTIL
"""
def send(self, msg):
"""
Send a message.
Args:
msg (str): The message that's to be sent.
Examples:
TODO
"""
self.irc.send(bytes(msg, "UTF-8"))
def send_target(self, target, msg):
"""
Send a specific message to target.
Args:
target (str): The target that's to be messaged.
msg (str): The message that's to be sent.
Examples:
TODO
"""
self.send(self.specific_send_command(target, msg))
def join(self, channel):
"""
Join a specific channel.
Args:
channel (str): The channel the bot should join.
Examples:
TODO
"""
self.send(self.join_channel_command(channel))
"""
BOT UTIL
"""
def load_plugins(self, plugins_to_load):
"""
Load plugins that are specified in the plugins list.
Args:
plugins_to_load (list of str): List of plugins to load.
Examples:
TODO
"""
list_to_add = self.plugins
logger.info('Loading plugins...')
to_load = []
plugs = 'settings/{}.conf'.format(plugins_to_load)
with open(plugs) as f:
to_load = f.read().split('\n')
to_load = list(filter(lambda x: x != '', to_load))
for file in to_load:
try:
module = importlib.import_module('plugins.{}'.format(file))
except ModuleNotFoundError as e:
logger.warning(f"module import error, skipped' {e} in {file}")
obj = module.Plugin
list_to_add.append(obj)
self.plugins = list_to_add
logger.info('Loaded plugins...')
def configfile_to_list(self, filename):
"""
Turn specified configfile to a list.
Args:
filenamae (str): Name of the file that should be converted.
Returns:
elements (list of str): Elements of the configfile as strings.
Examples:
TODO
"""
elements = []
with open('settings/{}.conf'.format(filename)) as f:
elements = f.read().split('\n')
elements = list(filter(lambda x: x != '', elements))
return elements
def methods(self):
"""
Return methods of the bot.
Returns:
dict of {str:str}: Dictionary of command names and strings.
Examples:
TODO
"""
return {
'send_raw': self.send,
'send': self.send_target,
'join': self.join,
'mem_add': self.memory_add_value,
'mem_rem': self.memory_remove_value,
'mem_fetch': self.memory_fetch_value
}
def run_plugins(self, listfrom, incoming):
"""
Runs the plugins.
Args:
listfrom (TODO): TODO
incoming (TODO): TODO
Examples:
TODO
"""
'''
incoming is the unparsed string. refer to test.py
'''
# if self.message_info(incoming)['args'][1][0] == ".":
# print("\033[0;32mReceived!\033[0;0m")
for plugin in listfrom:
# print(f"\033[0;33mTrying {plugin}\033[0;0m")
plugin.run(self, incoming, self.methods(), self.message_info(incoming), self.bot_info())
"""
SETUP REQUIREMENTS
"""
def requirements(self):
"""
Return requirements of the bot.
Returns:
reqs (list of str): List of the requirements.
Examples:
TODO
"""
reqs = []
with open('../requirements.txt') as f:
reqs = f.read().split('\n')
reqs = [m.split('==')[0] for m in reqs if m]
return reqs
# TODO: classify methods according to APIs and have
# a memory API
def memory_add_value(self, memfile, section, key, value):
"""
add value into memory.
Args:
memfile (TODO): TODO
section (TODO): TODO
key (TODO): TODO
value (TODO): TODO
Examples:
TODO
"""
memory_reader.read('memory/{}.txt'.format(memfile))
memory_reader[section][key] = value
with open('memory/{}.txt'.format(memfile), 'w') as file:
memory_reader.write(file)
def memory_remove_value(self, memfile, section, key):
"""
remove value from memory.
Args:
memfile (TODO): TODO
section (TODO): TODO
key (TODO): TODO
Examples:
TODO
"""
memory_reader.read('memory/{}.txt'.format(memfile))
memory_reader.remove_option(section, key)
with open('memory/{}.txt'.format(memfile), 'w') as file:
memory_reader.write(file)
def memory_fetch_value(self, memfile, section, key):
"""
fetches value from memory.
Args:
memfile (TODO): TODO
section (TODO): TODO
key (TODO): TODO
Returns:
(str): Value of the key as a string.
Examples:
TODO
"""
memory_reader.read('memory/{}.txt'.format(memfile))
return memory_reader[section][key]
"""
MESSAGE PARSING
"""
def core_commands_parse(self, incoming):
"""
parse core commands.
Args:
incoming (TODO): TODO
Examples:
TODO
"""
'''
PLUGINS
'''
self.run_plugins(self.plugins, incoming)
'''
BOT IRC FUNCTIONS
'''
def connect(self):
"""
Connect to the IRC
Examples:
TODO
"""
self.irc.connect((self.server_url, self.port))
def identify(self):
"""
Identifies command.
Examples:
TODO
"""
self.send(self.identify_command())
def greet(self):
"""
Greet the channel ? (TODO).
Examples:
TODO
"""
self.send(self.set_nick_command())
self.send(self.present_command())
for channel in self.autojoin_channels:
self.send(self.join_channel_command(channel))
def pull(self):
"""
TODO
Examples:
TODO
"""
while self.isListenOn:
try:
data = self.irc.recv(2048)
raw_msg = data.decode("UTF-8")
msg = raw_msg.strip('\n\r')
self.stay_alive(msg)
self.core_commands_parse(msg)
logger.info(msg)
if len(data) == 0:
try:
logger.critical(f'<must handle reconnection - {len(data)}==0>')
sys.exit()
except Exception as e:
logger.info(e)
except Exception as e:
logger.info(e)
"""
ONGOING REQUIREMENT/S
"""
def stay_alive(self, incoming):
"""
TODO
Args:
incoming (TODO): TODO
Examples:
TODO
"""
if not incoming:
logger.critical('<must handle reconnection - incoming is not True>')
sys.exit()
parts = incoming.split(':')
if parts[0].strip().lower() == 'ping':
logger.warning(parts[1])
self.send(self.pong_return(self.domain))
self.send(self.pong_return(parts[1]))
# all in one for registered bot
def registered_run(self):
"""
TODO
Examples:
TODO
"""
self.connect()
self.identify()
self.greet()
self.load_plugins('PLUGINS')
self.pull()
def unregistered_run(self):
"""
TODO
Examples:
TODO
"""
self.connect()
self.greet()
self.load_plugins('PLUGINS')
self.pull()