-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplebot.py
234 lines (210 loc) · 7.55 KB
/
simplebot.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
import discord
from importlib import import_module, reload
import os
class Bot(discord.Client):
def __init__(self):
self._bltList = {}
self._builtin()
self.pref = str()
ModMgr.getInst()
assert ModMgr is not None
return super().__init__()
async def on_ready(self):
"""
before getting into main loop
implement this function
"""
print('Logged on as {0}!'.format(self.user))
assert ModMgr.getInst() is not None
async def on_message(self, msg):
"""
if msg mentioned this bot,
check if msg called builtin function
if msg called builtin function
call the function here
otherwise pass msg to mods through
loop with msg through mod lists
pass mod over msgs
if mod returns true
end this function here
"""
#ignore bot msg
if self.user == msg.author :
return
#check who mentioned this bot
mention = str()
if msg.guild.get_member(self.user.id).nick is None :
mention = "<@{}>".format(self.user.id)
else :
mention = "<@!{}>".format(self.user.id)
if msg.content.startswith(mention) :
cmd = str.lstrip(msg.content[len(mention):]).split()[0]
if cmd in self._bltList :
await self._bltList[cmd](self,msg)
return
assert len(self.pref)>0 and self.pref != ' '
#district channels
if msg.content.startswith(self.pref) is False :
return
ModMgr.msgProc(self,msg)
pass
def getPref(self): return self.pref
def _builtin(self):
async def loadMod(bot, msg):
mention = str()
if msg.guild.get_member(self.user.id).nick is None :
mention = "<@{}>".format(self.user.id)
else :
mention = "<@!{}>".format(self.user.id)
line = msg.content[len(mention):].split()
#cmd = line[0]
args = line[1:]
for i in args :
if ModMgr._isloaded(i) :
await msg.channel.send("already loaded module {}".format(i))
return
if ModMgr.loadMod(i):
await msg.channel.send("succeed to load {}".format(i))
else :
await msg.channel.send("failed to load {}".format(i))
pass
self._bltList['load'] = loadMod
async def unloadMod(bot,msg):
#core Proc
mention = '<@!{}>'.format(self.user.id)
line = msg.content[len(mention):].split()
#cmd = line[0]
args = line[1:]
#if msg had modname check if modlist has this name
for i in args :
if ModMgr.unloadMod(i) :
await msg.channel.send("unloaded Module:{}".format(i))
else :
await msg.channel.send('i could not find module:{}'.format(i))
pass
self._bltList['unload'] = unloadMod
async def setPref(bot,msg):
pass
async def debug(bot,msg):
print(msg)
print(msg.content)
self._bltList['debug'] = debug
async def show(bot,msg):
async for i in msg.channel.history(limit=20):
print(i.content)
print(i.attachments)
for a in i.attachments :
print(a.height , end = '\t')
print(a.width, end = '\t')
print(a.proxy_url)
self._bltList['logs'] = show
async def imgdown(bot,msg):
async for m in msg.channel.history(limit=20):
if len(m.attachments) > 0 :
for a in m.attachments :
if a.height is not None and a.width is not None :
ext = 0
for i in range(len(a.filename)) :
if a.filename[-(i)] == '.' :
ext = i
fn = 'sample' + a.filename[-ext:]
file = os.path.join(os.getcwd(),'attach',fn)
os.access(file,mode = os.W_OK)
await a.save(file, use_cached=True)
return
self._bltList['down'] = imgdown
async def modList(bot,msg):
moddir = os.path.join(os.getcwd(),'modules')
files = []
for f in os.listdir(moddir) :
if f.startswith('__') is False and f.endswith('.py'):
files.append(f)
await msg.channel.send(f)
await msg.channel.send(files) #fix with embed
pass
self._bltList['modfiles'] = modList
async def modView(bot,msg):
for mod in bot.mList :
txt = mod.name + ' : '
for i in mod.getEvents():
txt += i
txt += ', '
txt = txt.rstrip(', ')
await msg.channel.send(txt)
#self._bltList['modlist'] = modView
pass
class ModMgr:
_instance = None
mDir ='modules'
def __init__(self):
self.mods = []
self.loaded = []
@classmethod
def getInst(cls):
if cls._instance is None :
cls._instance = ModMgr()
return cls._instance
@classmethod
def loadMod(cls,modName):
files = os.listdir( os.path.join(os.getcwd(),ModMgr.mDir))
#if file exist, check this file has syntax error
if '{}.py'.format(modName) in files :
if not modName in ModMgr.getModList() :
try :
mInst = import_module('.{}'.format(modName),ModMgr.mDir)
if ModMgr._isloaded(modName):
mInst = reload(mInst)
m = mInst.connect()
m.setModule(modName, mInst)
ModMgr._addMod(m)
return True
except SyntaxError as e:
print("syntax")
print(e)
return False
except :
print("unknown")
return False
else :
print('already loaded module name')
return False
else :
print('no file')
return False
@classmethod
def unloadMod(cls,modName):
for mod in cls.getModList() :
try :
if mod == modName :
ModMgr.getModList().remove(mod)
del mod
return True
except ValueError as e:
print('no value in list')
print(e)
return False
except :
print('unknown')
print('have not loaded yet')
return False
@classmethod
def getModList(cls):
return cls._instance.mods
@classmethod
def _addMod(cls,module) :
assert module is not None
cls._instance.mods.append(module)
cls._instance.loaded.append(module.name)
@classmethod
def _isloaded(cls,modName) :
if modName in cls._instance.loaded :
return True
else :
return False
@classmethod
async def msgProc(cls,bot,msg):
for mod in mods :
result = await mod.modProc(bot,msg)
if result is True :
return mod
return False