-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchatterbox.py
executable file
·586 lines (426 loc) · 20.5 KB
/
chatterbox.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
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
#!/usr/bin/python3 -u
import logging
import json
import os
import codecs
import stat
import time
import random
import re
import requests
import sys
import discord
from discord.ext import tasks, commands
import uuid
from mcrcon import MCRcon
import lib.showandtellraw as showandtellraw
import lib.littlepod as littlepod
import lib.turtlesin as turtlesin
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
datafolder = os.environ.get('DATAFOLDER', "/data/")
serverType = os.environ.get('TYPE', "java")
serverVersion = os.environ.get('MCVERSION', "Unknown")
URL = os.environ.get('SERVERURL', "https://localhost/")
servername = os.environ.get('SERVERNAME', "Littlepod")
updateRoles = os.environ.get("UPDATEROLES", False)
webfolder = os.environ.get('WEBFOLDER', "/web")
discordChannel = int(os.environ.get("DISCORDCHANNEL", ""))
discordPrivChannel = int(os.environ.get("DISCORDPRIVCHANNEL", ""))
discordToken = os.environ.get("DISCORDTOKEN", "")
discordBannerChannel = int(os.environ.get("DISCORDBANNERCHANNEL", ""))
discordInfoChannel = int(os.environ.get("DISCORDINFOCHANNEL", ""))
if not all([discordChannel, discordPrivChannel, discordToken, discordBannerChannel, discordInfoChannel]):
logging.critical("Not all env variables are set")
sys.exit(1)
serverFormat = "§9\<§a{}§9\>§r"
playerFormat = "§9\<§f{}§9\>§r"
patronFormat = "§9\<§c{}§9\>§r"
mcTellraw = "tellraw {selector} {json}"
bdsTellraw = 'tellraw {selector} {{"rawtext":{json}}}'
if serverType == "java":
tellrawCommand = mcTellraw
elif serverType == "bds":
tellrawCommand = bdsTellraw
if not discordToken:
print("Discord token not set")
sys.exit()
dimColors = {"4e7b44": "minecraft:overworld", "minecraft:overworld": "4e7b44", "3E1A19": "minecraft:the_nether", "minecraft:the_nether": "3E1A19", "C2C688": "minecraft:the_end", "minecraft:the_end": "C2C688"}
worlddict = { "o" : "minecraft:overworld", "n" : "mimecraft:the_nether", "e" : "monecraft:the_end" }
channelobject = discord.Object(id=discordChannel)
privchannelobject = discord.Object(id=discordPrivChannel)
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='$', intents=intents)
brailleOrds = [chr(58)] + [chr(x) for x in range(10241, 10241 + 255)]
currentPlayers = []
def toBraille( inputuuid ):
uuidBytes = uuid.UUID("{{{}}}".format(inputuuid))
ords = [ord(brailleOrds[x]) for x in uuidBytes.bytes]
#print(ords)
return "".join([chr(x) for x in ords])
def fromBraille( braille ):
ords = [brailleOrds.index(x) for x in braille]
#print(ords)
uuidBytes = bytes(ords)
# print(uuidBytes)
return str(uuid.UUID(bytes=uuidBytes))
def telllinks( links ):
for each in links:
logging.info("Found link: %s", each)
littlepod.send(tellrawCommand.format(selector="@a", json=showandtellraw.tojson((serverFormat + " [_Link_|{}]").format(servername, each))))
def coordsmessage( reCoords, reDim ):
for each in reCoords:
logging.info("Coords, %s, %s", each[0], each[1])
x, z = each
message = "Map: {dimtext} {x}, {z}\n{URL}#20/{x}/{z}/{dim}".format(dimtext=worlddict[reDim], dim=reDim.upper(), x=x, z=z, URL=URL)
return message
def tellcoords( reCoords, reDim ):
for each in reCoords:
x, z = each
littlepod.send(tellrawCommand.format(selector="@a",
json=showandtellraw.tojson(serverFormat.format(servername) + " [Map: _{dimtext} {x}, {z}_|{URL}/#20/{x}/{z}/{dim}]".format(dimtext=worlddict[reDim], dim=reDim.upper(), x=x, z=z, URL=URL))))
class serverLoop(commands.Cog):
def __init__(self, bot):
logging.info("Init server loop")
self.server = bot.get_guild(140194383118073856)
s = littlepod.minecraftConsole()
s.connect()
self.events = s.events
self.serverTask.start()
self.bot = bot
self.discordchannelobject = bot.get_channel(discordChannel)
self.privchannelobject = bot.get_channel(discordPrivChannel)
@tasks.loop(seconds=1)
async def serverTask(self):
def getgeo(ip):
FREEGEOPIP_URL = 'http://ip-api.com/json/'
url = '{}/{}'.format(FREEGEOPIP_URL, ip)
response = requests.get(url)
response.raise_for_status()
return response.json()
async def eventIp(data):
name = data[1]
ip = data[2].split(':')[0]
try:
hostaddr = socket.gethostbyaddr( ip )[0]
except:
hostaddr = "none"
ipinfo = getgeo( ip )
if not ipinfo["status"] == "fail":
ipstat = " ".join( [ip, hostaddr, ipinfo.get("countryCode", "??"), str(ipinfo.get("regionName", "??")), str(ipinfo.get("city", "??")), str(ipinfo.get("as", "??")) ] )
else:
ipstat = " ".join([ip, hastaddr])
await self.privchannelobject.send("`{}` !!!DENIED!!! {}".format(name, ipstat))
async def eventDeath1(data):
player = data[1]
player = re.sub(r"\?\d(.*)\?r",r"\1", player)
message = data[2:]
await self.discordchannelobject.send("\u2297 `{}` {}".format(player, "".join(message)))
async def eventDeath2(data):
player = data[1]
player = re.sub(r"\?\d(.*)\?r",r"\1", player)
message = list(data[2:])
message[1] = "`{}`".format(message[1])
await self.discordchannelobject.send("\u2297 `{}` {}".format(player, "".join(message)))
async def eventDeath3(data):
player = data[1]
player = re.sub(r"\?\d(.*)\?r",r"\1", player)
message = list(data[2:])
message[1] = "`{}`".format(message[1])
message[1] = re.sub(r"\?\d(.*)\?r",r"\1", message[1])
message[3] = "`{}`".format(message[3])
await self.discordchannelobject.send("\u2297 `{}` {}".format(player, "".join(message)))
async def eventLogged(data):
server = bot.get_guild("140194383118073856")
player = data[1]
player = re.sub(r"\?\d(.*)\?r",r"\1", player)
await self.discordchannelobject.send("\u2295 `{}` joined the game".format(player), delete_after=15)
ip = data[2].split(':')[0]
if ip:
message = "joined"
try:
hostaddr = socket.gethostbyaddr( ip )[0]
except:
hostaddr = "none"
ipinfo = getgeo( ip )
cc = ipinfo.get("countryCode", "XX")
ipstat= u" ".join( [ip, hostaddr, cc, str(ipinfo.get("regionName", "??")), str(ipinfo.get("city", "??")), str(ipinfo.get("as", "??")) ] )
await self.privchannelobject.send("`{}` {}".format(player, ipstat))
async def eventWhitelistAdd(data):
player = data[1]
await self.privchannelobject.send("`{}` {}".format(player, "added to whitelist"))
async def eventWhitelistRemove(data):
player = data[1]
await self.privchannelobject.send("`{}` {}".format(player, "removed from whitelist"))
async def eventServerChat(data):
await self.privchannelobject.send(data[1])
async def eventUUID(data):
player = data[1]
UUID = data[2]
async def eventLeft(data):
player = data[1]
player = re.sub(r"\?\d(.*)\?r",r"\1", player)
await self.discordchannelobject.send("\u2296 `{}` left the game".format(player), delete_after=15)
async def eventLost(data):
player = data[1]
reason = data[2]
await self.discordchannelobject.send("\u2296 `{}` lost connection: {}".format(player, reason), delete_after=15)
async def eventChat(data):
player = data[1]
message = data[2]
if player == "greener_ca" and message == "die":
assert False
for each in re.findall("@\S+", message):
memberfrommc = each.lstrip("@")
# print(memberfrommc)
member = discord.utils.find(lambda m: m.name == memberfrommc, bot.get_all_members())
if member:
membermention = member.mention
message = message.replace( each, membermention)
# print(message)
if not player.startswith("?7"):
player = re.sub(r"\?\d(.*)\?r",r"\1", player)
finalmessage = "`<{}>` {}".format(player, message)
# print(repr(finalmessage))
await self.discordchannelobject.send(finalmessage)
reCoords = re.findall( "(-?\d+), ?(-?\d+)", message)
logging.info("Found coords: %s", reCoords)
if reCoords:
reDim = re.findall("nether|end|over| o | e | n ", message)
if reDim:
if reDim[0] in ["over", " o "]:
dim = "o"
elif reDim[0] in ["nether", " n "]:
dim = "n"
elif reDim[0] in ["end", " e "]:
dim = "e"
else:
dim = "o"
await self.discordchannelobject.send(coordsmessage( reCoords, dim ))
tellcoords(reCoords, dim)
while self.events:
event, data = self.events.pop()
print("events:", event)
if event == "UUID":
await eventUUID(data)
if event == "serverchat":
await eventServerChat(data)
if event == "chat":
await eventChat(data)
if event in ["logged", "loggedbds"]:
await eventLogged(data)
if event == "ip":
await eventIp(data)
if event.startswith("deathWeapon"):
await eventDeath3(data)
elif event.startswith("deathEnemy"):
await eventDeath2(data)
elif event.startswith("death"):
await eventDeath1(data)
elif event.startswith("whitelistAdd"):
await eventWhitelistAdd(data)
elif event.startswith("whitelistRemove"):
await eventWhitelistRemove(data)
elif event in ["left", "leftbds"]:
await eventLeft(data)
if event in ["lost"]:
await eventLost(data)
class mainLoop(commands.Cog):
def __init__(self, bot):
logging.info("Init main loop")
self.server = bot.get_guild(140194383118073856)
self.emojis = {e.name: e for e in bot.emojis}
print(self.emojis)
self.bot = bot
self.infochannelobject = bot.get_channel(discordInfoChannel)
self.privchannelobject = bot.get_channel(discordPrivChannel)
self.mainTask.start()
def cog_unload(self):
self.mainTask.cancel()
@tasks.loop(minutes=1)
async def mainTask(self):
logging.info("Running main loop")
info = open(datafolder + "/info.md", "r").read()
activityFinal = "__Player Activity__\n\n" + turtlesin.getActivity()
infoFinal = info
allMessages = await self.infochannelobject.history( limit=200, after=None).flatten()
if allMessages:
for message in allMessages:
if message.author == self.bot.user and message.content.startswith("__About__"):
await message.edit(content=infoFinal)
break
else:
await self.infochannelobject.send(infoFinal)
for message in allMessages:
if message.author == self.bot.user and message.content.startswith("__Player Activity__"):
await message.edit(content=activityFinal)
break
else:
await self.infochannelobject.send(activityFinal)
'''
allroles = [r for r in server.roles if len(r.name) == 32]
allmembers = list(bot.get_all_members())
for r in allroles:
for m in allmembers:
if r in m.roles:
if m.nick:
if len(m.nick) < 17:
print(m.nick + toBraille(r.name))
await bot.change_nickname(m, m.nick + toBraille(r.name))
elif len(m.name) < 17:
print(m.name + toBraille(r.name))
await bot.change_nickname(m, m.name + toBraille(r.name))
'''
if serverType == "java":
discordWhitelistedPlayers = {}
discordWhitelistedPlayersIGN = {}
mcWhitelistedPlayersUUID = littlepod.getWhitelist()
mcWhitelistedPlayersIGN = littlepod.getWhitelistByIGN()
for member in self.server.members:
if "whitelisted" in [role.name for role in member.roles]:
brailleUUID = member.nick[-16:]
#print(member.nick, brailleUUID)
memberUUID = fromBraille(brailleUUID)
#print(memberUUID)
discordWhitelistedPlayers[memberUUID] = member.id
discordWhitelistedPlayersIGN[mcWhitelistedPlayersUUID.get(memberUUID, "").lower()] = member
mcWhitelistedPlayersUUID = littlepod.getWhitelist()
mcWhitelistedPlayersIGN = littlepod.getWhitelistByIGN()
add = set(discordWhitelistedPlayers) - set(mcWhitelistedPlayersUUID)
remove = set(mcWhitelistedPlayersUUID) - set(discordWhitelistedPlayers)
playerStatus = littlepod.getPlayerStatus(whitelist=discordWhitelistedPlayers)
if updateRoles:
for each in playerStatus["expired"]:
logging.info("Expired %s %s", each, mcWhitelistedPlayersUUID.get(each,""))
for each in add:
addIGN = littlepod.getNameFromAPI(each)
logging.info("Adding %s from the whitelist", addIGN)
littlepod.send("/whitelist add {}".format(addIGN))
for each in remove:
removeIGN = mcWhitelistedPlayersUUID.get(each,"")
logging.info("Removing %s from the whitelist", removeIGN)
littlepod.send("/whitelist remove {}".format(removeIGN))
bannerChannel = bot.get_channel(discordBannerChannel)
try:
with open(os.path.join(webfolder, "banners.json"), "r") as bannerFile:
bannerJson = json.load(bannerFile)
papyriBanners = {"{URL}/#20/{X}/{Z}/{dim}-{dim}_banners".format(URL=URL, X=b["X"], Z=b["Z"], dim=b["dimension"]): b for b in bannerJson}
except:
logging.info(sys.exc_info()[0])
papyriBanners = {}
# logging.info("json: %s", papyriBanners)
allChannelBanners = {message async for message in bannerChannel.history(limit=200, after=None) if message.author == bot.user}
channelBanners = {}
for each in allChannelBanners:
for embed in each.embeds:
#print(embed)
match = re.search("\[[0-9 \-,]*\]\((.*)\)", embed.description)
coords = match.group(1)
channelBanners.update({coords: each})
# logging.info("channel: %s", channelBanners)
dupes = allChannelBanners - set(channelBanners.values())
addBanners = set(papyriBanners) - set(channelBanners)
removeBanners = set(channelBanners) - set(papyriBanners)
def IGNtoMention( match ):
return discordWhitelistedPlayersIGN[match.group(1).lower()].mention
for each in addBanners:
logging.info("adding banner %s", each)
b = papyriBanners[each]
X = b["X"]
Z = b["Z"]
dim = b["dimension"]
title = b["name"]
title = re.sub("@([a-zA-Z0-9_]*)", IGNtoMention, title)
mapLink = each
description = "{} {} [{}, {}]({})".format(str(self.emojis[b["color"] + "banner"]), title, X, Z, mapLink)
colour = int(dimColors[dim], 16)
embed = discord.Embed(description=description, colour=colour)
logging.info(description)
await bannerChannel.send(embed=embed)
for each in removeBanners:
logging.info("removing banner %s", each)
await channelBanners[each].delete()
for each in dupes:
logging.info("removing dup banner %s", each.embeds[0]["description"])
await each.delete()
versionDict = {"java": "mc:je", "bds": "mc"}
version = versionDict[serverType] + " " + serverVersion
if serverType == "java":
players = littlepod.getOnlinePlayers()
playerList = " ".join(players) if players else ""
topicLine = "{} w/ {}".format(version, playerList)
elif serverType == "bds":
topicLine = version
# print(playerList)
await bot.change_presence(activity=discord.Game(name=topicLine))
@mainTask.after_loop
async def restartMainTask(self):
if self.mainTask.is_being_cancelled():
logging.info("Task was cancelled, restarting")
await self.mainTask.start()
@bot.event
async def on_status(member, old_game, old_status):
logging.info("%s %s %s", old_status, member.name, member.status)
@bot.event
async def on_message(message):
logging.info("Message: %s", message)
# we do not want the bot to reply to itself
if message.author == bot.user:
return
# print(message.author.display_name, message.clean_content.encode("utf-8"), message.attachments)
# print("mentioned", message.author)
if message.author.id == 140194230168453120 and message.channel.type == discord.ChannelType.private:
logging.info("Admin message")
if message.content.startswith("/"):
logging.info("Sending command %s", message.content)
with MCRcon("0.0.0.0", "secret") as rcon:
resp = rcon.command(message.clean_content)
chunks, chunk_size = len(resp), 2000
respList = [ resp[i:i+chunk_size] for i in range(0, chunks,
chunk_size) ]
print(resp)
for r in respList:
await message.channel.send(r)
if message.channel.id == int(discordPrivChannel):
adds = re.findall( "(\d*) link (.*)", message.content)
if adds:
logging.info("adding player: %s", adds)
addDiscordID, addIGN = adds[0]
r = requests.get('https://api.mojang.com/users/profiles/minecraft/{}'.format(addIGN))
print(str(r))
rDict = r.json()
UUID = rDict["id"]
UUIDBraille = toBraille(UUID)
newNickname = rDict["name"] + UUIDBraille
logging.info("nicknameing: %s %s", rDict, newNickname)
member = message.guild.get_member(int(addDiscordID))
await member.edit(nick=newNickname)
whitelistedRole = [role for role in message.guild.roles if role.name == "whitelisted"][0]
newMemberRoles = member.roles + [whitelistedRole]
await member.edit(roles=newMemberRoles)
await message.channel.send(str(rDict) + newNickname)
if message.channel.id == discordChannel:
display_name = str(message.author.display_name)
discordName = str(message.author)
messagetext = str(message.clean_content)
# messagetext = messagetext.replace('"', r"\"")
discordtext = u'{"text" : "\u2689 ", "color" : "blue" }'
if message.author.bot:
nameFormat = '§9\<{{§a{}~{}}}§9\>§r '
mcplayer, mcmessage = messagetext.split(" ", 1)
messagetext = mcplayer.strip('`') + " " + mcmessage
elif "patrons" in [a.name for a in message.author.roles]:
nameFormat = '§9\<{{§c{}~{}}}§9\>§r '
else:
nameFormat = '§9\<{{§f{}~{}}}§9\>§r '
#finalline = '/tellraw @a[team=!mute] {{"text" : "", "extra" : [{}, {{"color" : "gold", "text" : "{} "}}, {{"text" : "{}"}}]}}'.format(discordtext, display_name, messagetext)
tellrawText = nameFormat.format(display_name.replace("_", "\_").replace("~",""), discordName.replace("_", "\_").replace("@","\@").replace("~",""))
finalline = tellrawCommand.format(selector="@a", json=showandtellraw.tojson(tellrawText, noparse=messagetext))
logging.info(finalline)
littlepod.send(finalline)
@bot.event
async def on_ready():
logging.info('Logged in as %s %s', bot.user.name, bot.user.id)
bot.add_cog(mainLoop(bot))
bot.add_cog(serverLoop(bot))
bot.run(discordToken)