-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
688 lines (537 loc) · 23.2 KB
/
main.py
File metadata and controls
688 lines (537 loc) · 23.2 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# deep space network assistant bot for 17776 server
# author Nicky (@starmaid#6925)
# created 05/06/2020
# edited 05/07/2020
# edited 11/27/2020: added aternos functions
# edited 2/20/2021: reformatted server permissions, added rss feeding
# version 2.0
import discord
from discord.ext import commands
import asyncio
import logging
logging.basicConfig(level=logging.ERROR)
from datetime import datetime
from dateutil import parser
import random
from random import choice
import json
import feedparser
import shutil
import requests
#from connect_and_launch import get_status, get_number_of_players
#from connect_and_launch import connect_account, quitBrowser, get_server_info
#from connect_and_launch import start_server, stop_server
from dsnquery import DSNQuery
import control
server_conf = None
rss_conf = None
ARDUINO = None
class Bot(commands.Bot):
activity = 'comms monitor ./help'
logoff_msg = '`logging off`'
def __init__(self):
# This is the stuff that gets run at startup
super().__init__(command_prefix='./',self_bot=False,activity=discord.Game(self.activity))
self.remove_command('help')
self.add_command(self.help)
self.add_command(self.dsn)
self.add_command(self.add)
self.add_command(self.ls)
self.add_command(self.rm)
self.add_command(self.refresh)
self.add_command(self.about)
self.add_command(self.quit)
self.add_command(self.launch)
self.add_command(self.players)
self.add_command(self.status)
self.add_command(self.stop)
self.add_command(self.info)
self.add_command(self.cam)
self.add_command(self.tvb)
self.add_command(self.pan)
self.add_command(self.initArduino)
self.add_command(self.p)
self.read_token()
self.load_config()
if self.token is None or server_conf is None or rss_conf is None:
print(str(datetime.now()) + ': Could not start server due to missing files')
pass
else:
super().run(self.token)
def read_token(self):
self.token = None
try:
with open('./token.txt','r') as fp:
self.token = fp.readlines()[0].strip('\n')
except:
print(str(datetime.now()) + ': Token file not found')
def load_config(self):
global server_conf
global rss_conf
try:
with open('./server_conf.json', 'r') as fp:
server_conf = json.load(fp)
except:
print(str(datetime.now()) + ': Server conf file not found')
try:
with open('./rss_conf.json', 'r') as fp:
rss_conf = json.load(fp)
except:
print(str(datetime.now()) + ': RSS conf file not found')
return
async def on_ready(self):
#connect_account() # logs into aternos
await asyncio.sleep(2)
print(str(datetime.now()) + ': Logged on with aternos')
@commands.command(pass_context=True)
async def help(ctx):
#this is the help command.
cmd = ctx.message.content.lower().split()
l = len(cmd)
if l == 1:
# no params, just plain help
help_msg = '```<./> DSN BOT <./>\n' + \
'a discord bot to communicate with space probes ' + \
'at lightpseed' + \
'\nusage: ./command [params]*' + \
'\n --- availible commands ---' + \
'\n./help shows this message' + \
'\n./dsn queries the Deep Space Network' + \
'\n./ls [all, active] lists all feeds, or active feeds in this server' + \
'\n./add [params]* adds a feed. See ./help add' + \
'\n./rm [channel] [name] removes a feed from the server. use ./ls to find names' + \
'\n./refresh refreshes the files in memory. for debug purposes.' + \
'\n./about shows an about message for the bot' + \
'\n./quit shuts down the bot (only works for starmaid)'
if str(ctx.guild.id) in server_conf.keys() and 'minecraft' in server_conf[str(ctx.guild.id)]['permissions']:
help_msg += \
'\n./info gives mc server information' + \
'\n./launch starts the aternos minecraft server' + \
'\n./status shows status of aternos minecraft server' + \
'\n./players shows current players in aternos minecraft server' + \
'\n./stop stops aternos minecraft server'
elif l == 2:
# we had a second param
if cmd[1] == 'add':
help_msg = '```<./> DSN BOT <./>' + \
'\nAdd a notification feed to a channel. Omit hard brackets when invoking.' + \
'\nIf you already know the name of the feed, via "./ls all", you can add ' + \
'it directly by name.' + \
'\n ./add [#channel] [name]' + \
'\nIf you want to create a new custom feed using default settings, add ' + \
'it directly with the link. STILL BEING DEVELOPED - IT MIGHT NOT WORK' + \
'\n ./add [#channel] rss [link to rss feed]'
else:
help_msg = '```help parameters not recognized.'
help_msg += '```'
await ctx.send(help_msg)
return
@commands.command(pass_context=True)
async def about(ctx):
"""send an about message"""
global server_conf
global rss_conf
msg = '```<./> DSN BOT <./>' + \
'\nInspired by the Deep Space Network, run by JPL in Pasadena, CA.' + \
'\nMade by @starmaid#6925. Contact me with questions.' + \
'\nGithub: https://github.com/starmaid/dsnbot' + \
'\nCurrently in ' + str(len(server_conf.keys())) + ' servers' + \
'\nWatching ' + str(len(rss_conf['rss'].keys())) + ' rss feeds and ' + \
str(len(rss_conf['custom'].keys())) + ' custom feeds' + \
'```'
await ctx.send(msg)
return
# async def on_guild_join(guild):
# would love to say hi hehe
@commands.command(pass_context=True)
async def p(ctx):
"""Proxy the message through dsnbot. gives me a cool leg up on the roleplay"""
if str(ctx.message.author) == 'starmaid#6925':
await ctx.send(" ".join(ctx.message.content.split()[1:]))
await ctx.message.delete()
else:
await ctx.send("`I DIDNT SAY THAT`")
return
### ========== UPDATE COMMANDS ========== ###
@commands.command(pass_context=True)
async def add(ctx):
"""add an update to a channel"""
global server_conf
global rss_conf
# read the message
cmd = ctx.message.content.lower().split()
l = len(cmd)
guild_name = ctx.guild.name
guild_id = ctx.guild.id
chan_name = ctx.channel.name
chan_id = ctx.channel.id
new_chan = None
err = False
newrss = False
# check arguments
if l < 2:
msg = '`too few arguments provided. See ./help add`'
err = True;
# parse arguments
# send error message
elif l == 3:
# its just adding an already created one
new_name = cmd[2]
new_chan = cmd[1].replace('<','').replace('>','').replace('#','')
all_ids = []
for ch in ctx.guild.channels:
all_ids.append(str(ch.id))
if new_chan not in all_ids:
err = True
msg = '`Channel not valid. Make sure that the link is blue.`'
elif new_name not in rss_conf['rss'].keys() and new_name not in rss_conf['custom'].keys():
msg = '`premade feed not found`'
err = True
else:
if str(guild_id) in server_conf.keys():
if new_chan in server_conf[str(guild_id)].keys():
server_conf[str(guild_id)][new_chan].append(new_name)
else:
server_conf[str(guild_id)][new_chan] = [new_name]
else:
server_conf[str(guild_id)] = {'permissions': ['rss'], new_chan: [new_name]}
elif l == 4:
new_chan = cmd[1].replace('<','').replace('>','').replace('#','')
all_ids = []
for ch in ctx.guild.channels:
all_ids.append(str(ch.id))
if new_chan not in all_ids:
err = True
msg = '`Channel not valid. Make sure that the #channel link is blue.`'
elif cmd[2] != "rss":
msg = '`Improperly formed command. see ./help add`'
err = True
else:
try:
feed = feedparser.parse(cmd[3])
title = feed['feed']['title'].replace(' ','').lower()
shortname = ''.join([c for c in title if c.isalnum()])
new_name = shortname[0:20]
rss_conf['rss'][new_name] = {'url': cmd[3],
'field':'title',
'last_url':'',
'last_val':'',
'last_time':'',
'msg_template': '`Update for ' + new_name + ':` '}
newrss = True
if str(guild_id) in server_conf.keys():
if new_chan in server_conf[str(guild_id)].keys():
server_conf[str(guild_id)][new_chan].append(new_name)
else:
server_conf[str(guild_id)][new_chan] = [new_name]
else:
server_conf[str(guild_id)] = {'permissions': ['rss'], new_chan: [new_name]}
except:
msg = '`failed to import. make sure the link is correct, or contact an administrator`'
err = True
if not err:
# open and write to files to save changes
with open('./server_conf.json', 'w') as fp:
json.dump(server_conf, fp)
if newrss:
with open('./rss_conf.json', 'w') as fp:
json.dump(rss_conf, fp)
# the most recent update will be sent to the server at [time]
msg = '`update feed for "' + guild_name + '"` <#' + new_chan + '> `"' + new_name + '" added successfully`'
# send confirmation message
print(str(datetime.now()) + ': ' + msg)
await ctx.send(msg)
return
@commands.command(pass_context=True)
async def ls(ctx):
"""list updates"""
# read the message
global server_conf
global rss_conf
cmd = ctx.message.content.lower().split()
l = len(cmd)
guild_name = ctx.guild.name
guild_id = ctx.guild.id
chan_name = ctx.channel.name
chan_id = ctx.channel.id
err = False
if l > 2:
err = True
msg = '`Too many arguments for ls. see ./help`'
else:
if l == 1 or cmd[1] == 'active':
# list active feeds for this server
if str(guild_id) not in server_conf.keys():
msg = '`Server not registered, no active feeds. see ./ls all`'
err = True
else:
msg = '`List of active feeds and their channels:`'
for c in ctx.guild.channels:
loop_chan_id = str(c.id)
if loop_chan_id in server_conf[str(guild_id)].keys():
msg += '\n<#' + loop_chan_id + '>'
for feed in server_conf[str(guild_id)][loop_chan_id]:
msg += '\n `' + feed + '`'
elif cmd[1] == 'all':
# list all feeds known by the rss thing
msg = '```'
msg += '\nList of all feeds updated via DSNbot:'
msg += '\nRSS'
for feed in rss_conf['rss'].keys():
msg += '\n ' + feed.ljust(30) + ' ' + rss_conf['rss'][feed]['url']
msg += '\nCUSTOM'
for feed in rss_conf['custom'].keys():
msg += '\n ' + feed + ' "' + rss_conf['custom'][feed]['desc'] + '"'
msg += '```'
else:
err = True
msg = '`invalid args. see ./help`'
# send to channel
print(str(datetime.now()) + ': ' + msg)
await ctx.send(msg)
return
@commands.command(pass_context=True)
async def rm(ctx):
"""remove an enabled update"""
global server_conf
global rss_conf
# read the message
cmd = ctx.message.content.lower().split()
l = len(cmd)
guild_name = ctx.guild.name
guild_id = ctx.guild.id
chan_name = ctx.channel.name
chan_id = ctx.channel.id
err = False
# check arguments
# parse arguments
# send error message
if l > 3:
err = True
msg = '`Too many arguments for rm. see ./help`'
elif l < 3:
err = True
msg = '`Too few arguments for rm. see ./help`'
else:
del_feed = cmd[2]
del_chan = cmd[1].replace('<','').replace('>','').replace('#','')
all_ids = []
for ch in ctx.guild.channels:
all_ids.append(str(ch.id))
if del_chan not in all_ids:
# make sure channel exists
err = True
msg = '`Channel not valid. Make sure that the link is blue.`'
else:
if str(guild_id) in server_conf.keys():
if del_chan in server_conf[str(guild_id)].keys():
try:
server_conf[str(guild_id)][del_chan].remove(del_feed)
msg = '`update feed for "' + guild_name + '"` <#' + del_chan + '> `"' + del_feed + '" deleted successfully`'
except:
msg = '`premade feed not recognized. make sure you are using the exact spelling given in ./ls active`'
err = True
else:
msg = '`selected channel not registered. good news is, theres nothing to delete!`'
err = True
else:
msg = '`server not registered. good news is, theres nothing to delete!`'
err = True
# open and save file
if not err:
# open and write to files to save changes
with open('./server_conf.json', 'w') as fp:
json.dump(server_conf, fp)
# send confirmation message
print(str(datetime.now()) + ': ' + msg)
await ctx.send(msg)
return
@commands.command(pass_context=True)
async def refresh(ctx):
"""refresh files in memory"""
global server_conf
global rss_conf
msg = '`'
try:
with open('./server_conf.json', 'r') as fp:
server_conf = json.load(fp)
except:
print(str(datetime.now()) + ': Server conf file not found')
msg += 'error with server configuration, '
try:
with open('./rss_conf.json', 'r') as fp:
rss_conf = json.load(fp)
except:
print(str(datetime.now()) + ': RSS conf file not found')
msg += 'error with rss configuration, '
msg += 'refreshed`'
await ctx.send(msg)
return
@commands.command(pass_context=True)
async def dsn(ctx):
"""dsn current communication poll"""
msg = DSNQuery().poll()
await ctx.send(msg)
@commands.command(pass_context=True)
async def cam(ctx):
"""grab some cam footage"""
# read the message
cmd = ctx.message.content.lower().split()
l = len(cmd)
if l == 2:
if cmd[1] == "printer":
url = "http://octopi.local/webcam/?action=snapshot"
else:
url = "http://plants.local:8080/?action=snapshot"
else:
url = "http://plants.local:8080/?action=snapshot"
async with ctx.channel.typing():
imagefilename = "./" + str(datetime.now()).replace(" ","_").replace(":","")[0:15] + ".jpg"
try:
r = requests.get(url, stream=True, timeout=10)
r.raw.decode_content = True
with open(imagefilename,'wb') as f:
shutil.copyfileobj(r.raw, f)
image = discord.File(imagefilename, filename="plants.png")
await ctx.send(content="", file=image)
except:
await ctx.send("`CAMERA OFFLINE`")
async def on_command_error(self, ctx, error):
"""Handle commands that are not recognized so it stops printing to console"""
if type(error) is commands.CommandNotFound:
msg = "`command not recognized.`"
await ctx.send(msg)
@commands.command(pass_context=True)
async def tvb(ctx):
"""react to the message"""
emote = None
for e in ctx.guild.emojis:
if e.name == "TiVoglioBene":
emote = e
print(emote)
await ctx.message.add_reaction(emote)
@commands.command(pass_context=True)
async def initArduino(ctx):
global ARDUINO
async with ctx.channel.typing():
ARDUINO = control.ArduinoController()
await asyncio.sleep(5)
if ARDUINO.ready == True:
msg = "ARDUINO INITIALIZED"
else:
msg = "INITIALIZATION FAILED"
msg = "`" + msg + "`"
await ctx.send(msg)
return
@commands.command(pass_context=True)
async def pan(ctx):
global ARDUINO
if ARDUINO is None or ARDUINO.ready == False:
msg = "ARDUINO NOT INITIALIZED. USE ./initArduino"
else:
cmd = ctx.message.content.lower().split()
l = len(cmd)
if l == 2:
angle = int(cmd[1])
if angle <= 90 and angle >= -90:
# do it
async with ctx.channel.typing():
ARDUINO.pan(angle)
msg = "MOVE COMPLETE"
else:
msg = "PLEASE ENTER AN ANGLE BETWEEN -90 AND 90"
else:
msg = "INVALID COMMAND. ENTER A VALUE"
msg = "`" + msg + "`"
await ctx.send(msg)
return
@commands.command(pass_context=True)
async def quit(ctx):
# quits the bot.
if str(ctx.message.author) == 'starmaid#6925':
await ctx.send(ctx.bot.logoff_msg)
await ctx.bot.close()
quitBrowser()
else:
await ctx.send('`you do not have permission to shut me down.`')
print(str(datetime.now()) + ': Shutting down')
return
### ========== MINECRAFT COMMANDS ========== ###
@commands.command(pass_context=True)
async def launch(ctx):
# launches aternos
if not (str(ctx.guild.id) in server_conf.keys() and 'minecraft' in server_conf[str(ctx.guild.id)]['permissions']):
msg = '`sorry, your server does not have minecraft permissions`'
await ctx.send(msg)
return
await ctx.send("`Launching Server...`")
status = get_status()
if status == "Offline":
await start_server()
author = ctx.author
# loops until server has started and pings person who launched
while True:
await asyncio.sleep(5)
if get_status() == "Online":
await ctx.send(f"{author.mention}, `the "
f"server has started!`")
break
elif status == "Online":
await ctx.send("`The server is already Online`")
elif status == 'Starting ...' or status == 'Loading ...':
text = "`The server is already starting...`"
await ctx.send(text)
elif status == 'Stopping ...' or status == 'Saving ...':
text = "`The server is stopping. Please wait.`"
await ctx.send(text)
else:
text = "`An error occurred.\nTrying to launch the server anyways.`"
await ctx.send(text)
await start_server()
@commands.command(pass_context=True)
async def status(ctx):
"""status of aternos"""
if not (str(ctx.guild.id) in server_conf.keys() and 'minecraft' in server_conf[str(ctx.guild.id)]['permissions']):
msg = '`sorry, your server does not have minecraft permissions`'
await ctx.send(msg)
return
await ctx.send("`Getting status...`")
status = get_status()
await ctx.send("`The server is {}`".format(status))
@commands.command(pass_context=True)
async def players(ctx):
# launches aternos
if not (str(ctx.guild.id) in server_conf.keys() and 'minecraft' in server_conf[str(ctx.guild.id)]['permissions']):
msg = '`sorry, your server does not have minecraft permissions`'
await ctx.send(msg)
return
await ctx.send("`Getting players...`")
text = f"`There are {get_number_of_players()} players online.`"
await ctx.send(text)
@commands.command(pass_context=True)
async def info(ctx):
if not (str(ctx.guild.id) in server_conf.keys() and 'minecraft' in server_conf[str(ctx.guild.id)]['permissions']):
msg = '`sorry, your server does not have minecraft permissions`'
await ctx.send(msg)
return
ip, status, players, software, version = get_server_info()
text = f"**IP:** {ip} \n**Status:** {status} \n**Players: " \
f"**{players} \n**Version:** {software} {version}"
embed = discord.Embed()
embed.add_field(name="Server Info", value=text, inline=False)
await ctx.send(embed=embed)
@commands.command(pass_context=True)
async def stop(ctx):
# stops aternos
if not (str(ctx.guild.id) in server_conf.keys() and 'minecraft' in server_conf[str(ctx.guild.id)]['permissions']):
msg = '`sorry, your server does not have minecraft permissions`'
await ctx.send(msg)
return
await ctx.send("`Stopping the server.`")
status = get_status()
if status != 'Stopping ...' or status != 'Saving ...':
await stop_server()
else:
await ctx.send("`The server is already Offline.`")
if __name__ == '__main__':
Bot()