]>
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, os | |
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(delimiters=('=',)) | |
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 getint(self, section, key, default=0): | |
44 | try: | |
45 | return int(self.config.get(section, key)) | |
46 | except: | |
47 | return default | |
48 | def getboolean(self, section, key, default=False): | |
49 | val = self.get(section, key, default) | |
50 | if type(val) is bool: | |
51 | return val | |
52 | elif val == "0" or val.lower() == "false": | |
53 | return False | |
54 | else: | |
55 | return True | |
56 | ||
57 | def set(self, section, key, value): | |
58 | if not self.config.has_section(section): | |
59 | self.config.add_section(section) | |
60 | self.config.set(section, key, str(value)) | |
61 | if self.writeout: self.write() | |
62 | ||
63 | def delete(self, section, key): | |
64 | if self.config.has_section(section): | |
65 | self.config.remove_option(section, key) | |
66 | if self.writeout: self.write() | |
67 | ||
68 | def write(self): | |
69 | with open(self.filename+'.tmp', 'w') as configfile: | |
70 | self.config.write(configfile) | |
71 | os.rename(configfile.name, self.filename) | |
72 | ||
73 | def __del__(self): | |
74 | if self.writeout: self.write() | |
75 | ||
76 | if __name__ == '__main__': | |
77 | import sys | |
78 | if len(sys.argv) > 1: | |
79 | cfg = Config(sys.argv[1], False) | |
80 | else: | |
81 | cfg = Config('bot.config', False) | |
82 | ||
83 | for s in cfg.config.sections(): | |
84 | for k, v in cfg.items(s): | |
85 | print("[%r][%r] = %r" % (s, k, v)) |