-
Notifications
You must be signed in to change notification settings - Fork 0
/
moira.py
385 lines (321 loc) · 11.5 KB
/
moira.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
#!/usr/bin/env python3
from argparse import ArgumentParser
from asyncio import sleep
from os import environ as env
from random import choice
from discord import DMChannel, TextChannel
from dotenv import load_dotenv
from sys import path
from logs import status
from phrases.default import busyState as busyPhrase, ha, initialPrompt, misc, nevermindedThen
from phrases.default import subroutineUnreachable as currentlyNot, unsureAboutQualifiedTopic as unsure, zerosidedBye
import phrases.system as syx
from sessions.core import MOIRA
from sessions.exceptions import MoiraTypeError
from sessions.royub import Event, RoyUB
from sessions.session import MoiraSession
from sessions.situation import SessionSituation, Situation
from sessions.tism import MoiraInfamousStateMachine as MISM
from sessions.users import SessionAdmin, SessionUser
from settings import prefs
from utils.administration import mindThoseArgs
from utils.commands import handleCommandError
from utils.db import DBSetup
from utils.eonet import handleEonet
from utils.logging import Loggers, TerminalLogger
from utils.prompts import handleResponse, parsePrompt, waitForAuthorisedPrompt
from utils.qualification import qualifyInput, waitForQualificationInput
from utils.startup import logStartup, noteExceptions, readyUp, retrieveDbMeta, setStates, runTests
from utils.wsys import handleWsys
load_dotenv()
noColour = env.get('NO_COLOR')
moira_hooks_logs_id = str(env.get('MOIRA_WEBHOOKS_LOGS_ID'))
moira_hooks_logs_token = str(env.get('MOIRA_WEBHOOKS_LOGS_TOKEN'))
moira_hooks_open_logs_id = str(env.get('MOIRA_WEBHOOKS_OPEN_LOGS_ID'))
moira_hooks_open_logs_token = str(env.get('MOIRA_WEBHOOKS_OPEN_LOGS_TOKEN'))
moira_nickname = str(env.get('MOIRA_NICKNAME'))
moira_patience = int(env.get('MOIRA_MAX_PROMPT_LOOPS'))
moira_prefix = str(env.get('MOIRA_PREFIX'))
moira_administrator_role = str(env.get('MOIRA_ADMIN_ROLE'))
moira_user_role = str(env.get('MOIRA_USER_ROLE'))
mongodb_cluster_domain = env.get('MONGODB_CLUSTER_DOMAIN')
mongodb_cluster_name = env.get('MONGODB_CLUSTER_NAME')
mongodb_cluster_username = env.get('MONGODB_CLUSTER_USERNAME')
mongodb_cluster_userpass = env.get('MONGODB_CLUSTER_USERPASS')
mongodb_db_general = env.get('MONGODB_DB_GENERAL')
mongodb_collection_general = env.get('MONGODB_DB_GENERAL_COLLECTION')
openai_api_token = str(env.get('OPENAI_API_TOKEN'))
nasa_api_token = str(env.get('NASA_API_KEY'))
thisPath = path[0]
paths = {
'assets': f'{thisPath}/assets/',
'reports': f'{thisPath}/reports/'
}
parser = ArgumentParser()
parser.add_argument(
'-d',
action='store_true',
help='Launches Moira in debug mode with heavy logging.',
)
args = parser.parse_args()
globals = Situation(
noColour=noColour
)
loggers = Loggers(
log_level=0
)
if args.d:
loggers.log_level=1
tLogger = TerminalLogger(
situation = globals
)
loggers.registerLogger(tLogger)
moira = MOIRA(
moira_prefix,
moira_nickname,
moira_administrator_role,
moira_user_role,
moira_patience,
subroutines = {
'AI': openai_api_token,
'DB': '',
'EONET': nasa_api_token,
'WSYS': []
},
webhook = {
'id': moira_hooks_logs_id,
'token': moira_hooks_logs_token
}
)
moira.db = DBSetup(
mongodb_cluster_domain,
mongodb_cluster_name,
mongodb_cluster_username,
mongodb_cluster_userpass,
mongodb_db_general,
mongodb_collection_general
)
moira.mQ = []
moira.tism = MISM(
busyKey = 'busy',
promptHistoryKey = 'promptHistory',
sessionKey = 'busyWith',
systemsKey = 'subroutines'
)
moira.tism.setState(
moira.tism.systemsKey, {
'AI': 'DOWN',
'DB': 'DOWN',
'EONET': 'DOWN',
'WSYS': 'SILENT'
})
roy = RoyUB(
moira,
'verbal',
moira_hooks_open_logs_id,
moira_hooks_open_logs_token
)
moira.remove_command('help')
roy.manageEvent('stormoff', roy.emitMemberTimeout)
roy.manageEvent('memberTimeout', roy.memberTimeout)
@moira.event
async def on_ready():
readyUp(moira, globals)
setStates(moira, globals, loggers)
await runTests(moira, globals, loggers)
noteExceptions(moira, openai_api_token, globals, loggers)
await retrieveDbMeta(moira, globals, loggers)
await logStartup(
moira.webhook,
globals
)
globals.resetAll()
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_onready_ontestslogged.format(moira))
globals.status.appendMessage(status.discord_moira_onready_onglobalsreset.format(moira))
@moira.event
async def on_command_error(ctx, err):
await handleCommandError(moira, ctx, globals, err, loggers)
@moira.event
async def on_error(eventName):
errorMessage = syx.error_on_event.format(eventName)
globals.errors.appendMessage(errorMessage)
await globals.log(webhook=moira.webhook)
globals.resetAll()
@moira.event
async def on_message(message):
if message.author == moira.user:
return
if not message.content.startswith(moira_prefix):
if str.lower(moira.nickname) in str.lower(message.content):
await sleep(2)
await message.add_reaction(prefs.mPref_reaction_meta)
await moira.process_commands(message)
# COMMANDS
@moira.command(
name=moira.nickname,
pass_context=True
)
async def initialPrompting(ctx):
m = ctx.message
chad = ctx.author.id
chid = ctx.channel.id
sessionUser = None
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_called.format(moira, ctx.author))
if moira.administrator:
for entry in ctx.author.roles:
if str(moira.administrator) in str(entry.name):
sessionUser = SessionAdmin(chad)
break
if not sessionUser and moira.regularUser:
for entry in ctx.author.roles:
if str(moira.regularUser) in str(entry.name):
sessionUser = SessionUser(chad)
break
if not sessionUser:
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_not_a_sessionuser.format(ctx.author, moira))
return
sit = SessionSituation(
handler=moira,
channelId=chid,
noColour=noColour,
sessionUser=sessionUser,
userMessage=m,
errors=[],
exceptions=[],
status=[],
warnings=[]
)
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_sit_created.format(ctx.author, chid))
try:
if isinstance(sessionUser, SessionAdmin):
outcome = await mindThoseArgs(moira, ctx, sit, globals, loggers)
except Exception as e:
sit.exceptions.appendMessage(e)
await sit.logIfNecessary(
title='',
webhook=moira.webhook
)
sit.resetAll()
else:
if outcome == 'DONE':
return
angryState = ctx.author.id in moira.tism.state['angryAt'] and len(moira.tism.state['angryAt'][ctx.author.id]) > 0
if angryState:
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_angered.format(moira, ctx.author, chid))
return
busyState = moira.tism.getBusyState(chid)
if busyState != 'FALSE':
await moira.send(ctx, choice(busyPhrase))
moira.tism.queue('promptQueue', chid, m)
moira.mQ.append(m.id)
return
if type(ctx.channel) == DMChannel:
await moira.send(ctx, misc['notInDMs'])
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_called_in_dms.format(moira, ctx.author))
return
elif type(ctx.channel) == TextChannel:
session = MoiraSession(ctx, moira, sessionUser)
await session.createSession(phrase=choice(initialPrompt))
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_created.format(moira, ctx.author, chid))
session.userMessage = await waitForQualificationInput(session.handler, session.ctx)
if not session.userMessage:
await session.exitSession()
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
return
try:
await qualifyInput(moira, chid, session.userMessage)
except InterruptedError:
await session.exitSession(response=choice(nevermindedThen))
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
return
except ModuleNotFoundError:
if sessionUser.role == 'admin':
await session.exitSession(response=choice(currentlyNot))
else:
await session.exitSession(response=choice(unsure))
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
return
except NotImplementedError:
await session.exitSession(response=choice(unsure))
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
return
except MoiraTypeError:
if sessionUser.role == 'regular':
reason = prefs.mPref_wrongType
duration = 4
await moira.send(ctx, choice(zerosidedBye), 2)
e = Event('stormoff')
await e.run(ctx, reason, duration)
else:
await session.exitSession(response=choice(ha))
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
return
except TimeoutError:
await session.exitSession()
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
return
except Exception as e:
errorMessage = syx.exception_qualifying_input.format(syx.exception, e)
globals.exceptions.appendMessage(errorMessage)
await globals.log(webhook=moira.webhook)
await session.exitSession()
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
return
sessionState = session.getState()
subroutine = sessionState['active_subroutine']
if subroutine == 'AI':
response = ''
prompt = await waitForAuthorisedPrompt(moira, ctx, sessionUser)
if prompt:
response = await parsePrompt(moira, ctx, prompt.content)
if response:
await handleResponse(moira, ctx, response)
else:
await moira.send(ctx, misc['failsafe'])
moira.tism.addToPromptHistory(chid, chad, prompt, response)
moira.tism.removeFromSessionState(chid, 'active_subroutine')
await session.exitSession()
elif subroutine == 'EONET':
await handleEonet(ctx, session, sit)
moira.tism.removeFromSessionState(chid, 'active_subroutine')
await session.exitSession()
elif subroutine == 'WSYS':
await handleWsys(ctx, session, sit, paths)
moira.tism.removeFromSessionState(chid, 'active_subroutine')
await session.exitSession()
if m.id in moira.mQ:
moira.tism.dequeue('promptQueue', chid, m)
moira.mQ.remove(m.id)
await sit.logIfNecessary(
title=syx.session_log,
webhook=moira.webhook
)
sit.resetAll()
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_session_ended.format(moira, ctx.author, chid))
else:
await moira.send(ctx, misc['notInOther'])
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_called_other_channel.format(moira, ctx.author, chid))
if loggers.log_level > 0:
globals.status.appendMessage(status.discord_moira_command_executed.format(moira, ctx.author, chid))
globals.logToTerm(
title=syx.command_log,
webhook=moira.webhook
)
globals.resetAll()
moira.run(str(env.get('DISCORD_API_TOKEN')))