]>
Commit | Line | Data |
---|---|---|
1 | # Erebus IRC bot - Author: John Runyon | |
2 | # vim: fileencoding=utf-8 | |
3 | # "Config" class (reading/providing access to bot.config) | |
4 | ||
5 | from __future__ import print_function | |
6 | import sys | |
7 | ||
8 | if sys.version_info.major < 3: | |
9 | import ConfigParser | |
10 | else: | |
11 | import configparser as ConfigParser | |
12 | ||
13 | class Config(object): | |
14 | def __init__(self, filename, writeout=True): | |
15 | self.__dict__['config'] = ConfigParser.RawConfigParser() | |
16 | self.__dict__['filename'] = filename | |
17 | self.__dict__['writeout'] = writeout | |
18 | self.config.read(filename) | |
19 | ||
20 | def __getattr__(self, key): | |
21 | return self.config.get('erebus', key) | |
22 | ||
23 | def __setattr__(self, key, value): | |
24 | self.config.set('erebus', key, value) | |
25 | ||
26 | def __getitem__(self, section): #!! READ-ONLY !! | |
27 | return {item: self.config.get(section, item) for item in self.config.options(section)} | |
28 | ||
29 | def level(self, cmd): | |
30 | return self.config.get('levels', cmd) | |
31 | ||
32 | def setlevel(self, cmd, level): | |
33 | self.config.set('levels', cmd, level) | |
34 | ||
35 | def items(self, section='erebus'): | |
36 | return self.config.items(section) | |
37 | ||
38 | def get(self, section, key, default=None): | |
39 | try: | |
40 | return self.config.get(section, key) | |
41 | except: | |
42 | return default | |
43 | def getboolean(self, section, key): | |
44 | val = self.get(section, key, False) | |
45 | if val == False or val == "0" or val.lower() == "false": | |
46 | return False | |
47 | else: | |
48 | return True | |
49 | ||
50 | def set(self, section, key, value): | |
51 | self.config.set(section, key, value) | |
52 | if self.writeout: self.write() | |
53 | ||
54 | def write(self): | |
55 | with open(self.filename, 'wb') as configfile: | |
56 | self.config.write(configfile) | |
57 | ||
58 | def __del__(self): | |
59 | if self.writeout: self.write() | |
60 | ||
61 | if __name__ == '__main__': | |
62 | import sys | |
63 | if len(sys.argv) > 1: | |
64 | cfg = Config(sys.argv[1], False) | |
65 | else: | |
66 | cfg = Config('bot.config', False) | |
67 | ||
68 | for s in cfg.config.sections(): | |
69 | for k, v in cfg.items(s): | |
70 | print("[%r][%r] = %r" % (s, k, v)) |