]> jfr.im git - erebus.git/blob - modules/help.py
change to use str.startswith
[erebus.git] / modules / help.py
1 # Erebus IRC bot - Author: Erebus Team
2 # help module
3 # This file is released into the public domain; see http://unlicense.org/
4
5 # module info
6 modinfo = {
7 'author': 'Erebus Team',
8 'license': 'public domain',
9 'compatible': [1,2],
10 'depends': [],
11 'softdeps': [],
12 }
13
14 # preamble
15 import modlib
16 lib = modlib.modlib(__name__)
17 modstart = lib.modstart
18 modstop = lib.modstop
19
20 # module code
21 import os.path
22 helps = {}
23 cmds = {}
24
25 # ! this is part of this module's API, called from modlib.help()
26 def reghelp(func, *args, **kwargs):
27 syntax = None
28 shorthelp = None
29 longhelps = []
30
31 if len(args) > 0:
32 syntax = args[0]
33 if len(args) > 1:
34 shorthelp = args[1]
35 if len(args) > 2:
36 longhelps = args[2:]
37
38 if 'syntax' in kwargs:
39 syntax = kwargs['syntax']
40 if 'shorthelp' in kwargs:
41 shorthelp = kwargs['shorthelp']
42 if 'longhelps' in kwargs:
43 longhelps = kwargs['longhelps']
44
45 if syntax is None: syntax = ""
46 if shorthelp is None: shorthelp = ""
47
48 func.syntax = syntax
49 func.shorthelp = shorthelp
50 func.longhelps = longhelps
51 helps[func] = func
52 for c in func.cmd:
53 cmds[c] = func
54
55 def dereghelp(func, *args, **kwargs):
56 for c in func.cmd:
57 del cmds[c]
58 del helps[func]
59
60 class HelpLine(object):
61 def __init__(self, cmd, syntax, shorthelp, admin, glevel, module, clevel):
62 self.cmd = cmd
63 self.syntax = syntax
64 self.shorthelp = shorthelp
65 self.admin = admin
66 self.glevel = glevel
67 self.module = module
68 self.clevel = clevel
69
70 def __cmp__(self, other):
71 if self.glevel == other.glevel:
72 return cmp(self.cmd, other.cmd)
73 else:
74 return cmp(self.glevel, other.glevel)
75
76
77 def __str__(self):
78 if self.admin:
79 ret = "%-35s(%3s) - %-10s - " % (self.cmd+' '+self.syntax, self.glevel, self.module)
80 else:
81 ret = "%-40s - " % (self.cmd+' '+self.syntax)
82 if self.clevel != 0:
83 ret += "(%s) " % (lib.clevs[self.clevel])
84 ret += str(self.shorthelp)
85 return ret
86
87 def _mkhelp(level, func):
88 lines = []
89 if level >= func.reqglevel:
90 lines.append(HelpLine(func.cmd[0], func.syntax, func.shorthelp, (level > 0), func.reqglevel, func.module, func.reqclevel))
91 if len(func.cmd) > 1:
92 for c in func.cmd[1:]:
93 lines.append(HelpLine(c, "", "Alias of %s" % (func.cmd[0]), (level > 0), func.reqglevel, func.module, func.reqclevel))
94 return lines
95
96 def _genhelp(bot, user, chan, realtarget, *args):
97 module = None
98 minlevel = -1
99 maxlevel = 100
100 filepath = bot.parent.cfg.get('help', 'path', default='./help/%d.txt')
101 for arg in args:
102 if arg.startswith("@"):
103 module = arg[1:]
104 elif arg.startswith("#") and user.glevel >= lib.ADMIN:
105 minlevel = maxlevel = int(arg[1:])
106 else:
107 filepath = arg
108 if minlevel != maxlevel:
109 minlevel = maxlevel
110 print "%r %r %r %r" % (module, minlevel, maxlevel, filepath)
111 for level in range(minlevel, maxlevel+1):
112 if '%d' in filepath:
113 filename = filepath % (level)
114 else:
115 filename = filepath
116 fo = open(filename, 'w')
117 lines = []
118 for func in helps.itervalues():
119 if module is not None and func.module != module:
120 continue
121 lines += _mkhelp(level, func)
122 for line in sorted(lines):
123 fo.write(str(line)+"\n")
124 fo.close()
125 return True
126
127 @lib.hook(glevel=1, needchan=False)
128 @lib.help("[@<module>] [#<level>] [file]", "generates help file", "arguments are all optional and may be specified in any order", "default file: ./help/<level>.txt", "config as: [help]", "path = ./help/%d.txt")
129 def genhelp(bot, user, chan, realtarget, *args):
130 try:
131 _genhelp(bot, user, chan, realtarget, *args)
132 except Exception as e:
133 bot.msg(user, "Failed writing help. %s" % (e))
134 return
135 bot.msg(user, "Help written.")
136
137 @lib.hook(needchan=False)
138 @lib.help("<command>", "describes a command")
139 @lib.argsGE(1)
140 def help(bot, user, chan, realtarget, *args):
141 cmd = str(' '.join(args)).lower()
142 if cmd in cmds and user.glevel >= cmds[cmd].reqglevel:
143 func = cmds[cmd]
144 bot.slowmsg(user, str(HelpLine(func.cmd[0], func.syntax, func.shorthelp, (user.glevel > 0), func.reqglevel, func.module, func.reqclevel)))
145 for line in func.longhelps:
146 bot.slowmsg(user, " %s" % (line))
147 bot.slowmsg(user, "End of help for %s." % (func.cmd[0]))
148 if len(func.cmd) > 1:
149 bot.slowmsg(user, " Aliases: %s" % (' '.join(func.cmd[1:])))
150 else:
151 bot.slowmsg(user, "No help found for %s" % (cmd))
152
153 @lib.hook(needchan=False)
154 @lib.help(None, "provides command list")
155 def showcommands(bot, user, chan, realtarget, *args):
156 if bool(int(bot.parent.cfg.get('help', 'autogen', default=0))):
157 try:
158 _genhelp(bot, user, chan, realtarget, *args)
159 except: pass
160
161 url = bot.parent.cfg.get('help', 'url', default=None)
162 if url is None:
163 try:
164 import urllib2
165 myip = urllib2.urlopen("https://api.ipify.org").read()
166 url = "http://%s/help/%%d.txt (maybe)" % (myip)
167 except: url = None
168 if url is not None:
169 url = url % (user.glevel)
170 bot.msg(user, "Help is at: %s" % (url))
171 else:
172 bot.msg(user, "I don't know where help is. Sorry. Contact my owner.")
173
174 """#DISABLED
175 @lib.hook(needchan=False)
176 @lib.help('[@<module>|<command>]', 'lists commands or describes a command', 'with @<module>, lists all commands in <module>')
177 def help(bot, user, chan, realtarget, *args):
178 if len(args) == 0: # list commands
179 lines = []
180 for func in helps.itervalues():
181 lines += _mkhelp(user, func)
182 for line in sorted(lines):
183 bot.slowmsg(user, str(line))
184 bot.slowmsg(user, "End of command listing.")
185 elif args[0].startswith("@"):
186 lines = []
187 mod = args[0][1:].lower()
188 for func in helps.itervalues():
189 if func.module == mod:
190 lines += _mkhelp(user, func)
191 for line in sorted(lines):
192 bot.slowmsg(user, str(line))
193 bot.slowmsg(user, "End of command listing.")
194 else: # help for a specific command/topic
195 cmd = str(' '.join(args)).lower()
196 if cmd in cmds and user.glevel >= cmds[cmd].reqglevel:
197 func = cmds[cmd]
198 bot.slowmsg(user, str(HelpLine(func.cmd[0], func.syntax, func.shorthelp, (user.glevel > 0), func.reqglevel, func.module)))
199 for line in func.longhelps:
200 bot.slowmsg(user, " %s" % (line))
201 bot.slowmsg(user, "End of help for %s." % (func.cmd[0]))
202
203 if len(func.cmd) > 1:
204 bot.slowmsg(user, " Aliases: %s" % (' '.join(func.cmd[1:])))
205 else:
206 bot.slowmsg(user, "No help found for %s" % (cmd))
207 """
208 pass