Skip to content
Permalink
Browse files
init commit
  • Loading branch information
hollan84 committed May 3, 2020
0 parents commit b304932988d16f478d88694fecdaeb0be76c9545
Show file tree
Hide file tree
Showing 28 changed files with 363 additions and 0 deletions.
@@ -0,0 +1 @@
.env
@@ -0,0 +1,70 @@
import os

import discord
import status
from mcstatus import MinecraftServer
from datetime import datetime
from datetime import timedelta
from discord.ext import commands, tasks
import difflib
import asyncio
server = MinecraftServer("192.168.0.89", 25565)

status = server.status()
print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
query = server.query()
print("The server has the following players online: {0}".format(", ".join(query.players.names)))


client = discord.Client()

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')

async def checkLogin():
server = MinecraftServer("192.168.0.89", 25565)
oldPlayers = ""
while not client.is_closed():
msg = ""
query = server.query()
currentPlayers = "".join(query.players.names)
print(currentPlayers)
msg = currentPlayers
checkNicknames = msg.split("\n - ")
for i in checkNicknames:
path = "nicknames/" + i
try:
n = open(path, "r")
nick = i + " [" + n.read() + "]"
msg = msg.replace(i, nick)
n.close()
except:
msg = msg
login = msg
logout = msg
for i,s in enumerate(difflib.ndiff(msg, oldPlayers)):
if s[0] == ' ':
continue
elif s[0]=="-":
logout = logout + (u'"{}"'.format(s[-1])) + "\n"
elif s[0]=="+":
login = login + (u'"{}"'.format(s[-1])) + "\n"
for i in login:
msg = msg + i
msg = msg + " logged in"
for i in logout:
msg = msg + i
msg = msg + " logged out"
oldPlayers = currentPlayers
if msg == "":
print("Nobody logged in")
else:
channel = client.get_channel(694572684566331473)
await channel.send(msg)
await asyncio.sleep(10)


client.loop.create_task(checkLogin())
client.run(token)

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
109 bot.py
@@ -0,0 +1,109 @@
import os
import discord
import status
from mcstatus import MinecraftServer
from datetime import datetime
from datetime import timedelta

server = MinecraftServer(os.environ['SERVER'], int(os.environ['PORT']))

status = server.status()
print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
query = server.query()
print("The server has the following players online: {0}".format(", ".join(query.players.names)))

token = os.environ['TOKEN']

client = discord.Client()

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')

global oldauthor
global oldcommand
global oldmsg
global messagetime
oldcommand = ""
oldauthor = ""
oldmsg = ""
messagetime = datetime.now().time()

@client.event
async def on_message(message):
server = MinecraftServer(os.environ['SERVER'], int(os.environ['PORT']))
print(message.content)
'''Anti Spam Variables'''
global oldauthor
global oldcommand
global oldmsg
global messagetime
msg = ""
'''Checking which command has been issued'''
if message.author == client.user: #Make sure that the bot doesn't reply to itself
return
#elif message.content.startswith('?status'):
# query = server.query()
# msg = ("The server has the following players online: {0}".format(", ".join(query.players.names)))
elif message.content.startswith('?map'):
msg = "http://map.alastairserver.co.uk"
elif message.content.startswith('?servername'):
msg = "http://minecraft.alastairserver.co.uk \nhttp://server.alastairserver.co.uk"
elif message.content.startswith('?help'):
msg = "Commands: \n - ?help \n - ?servername \n - ?map\n - ?status\n - ?minecraftNickname [USERNAME] [NICKNAME]\n - ?download"
elif message.content.startswith('?download'):
msg = "http://server.alastairserver.co.uk/Public/Minecraft%20World%20Downloads/"
elif message.content.startswith('?status'):
try:
status = server.status()
query = server.query()
if status.players.online > 0:
msg = str("The server has {0} players and replied in {1} ms\nPlayers:\n - {2}".format(status.players.online, status.latency, "\n - ".join(query.players.names)))
else:
msg = str("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
except:
msg = "Server doesn't seem to be repsonding; please message Alastair for help"
checkNicknames = msg.split("\n - ")
#print("TESTING")
#print(checkNicknames)
for i in checkNicknames:
#print(i)
path = "nicknames/" + i
try:
n = open(path, "r")
nick = i + " [" + n.read() + "]"
msg = msg.replace(i, nick)
n.close()
except:
msg = msg
elif message.content.startswith('?minecraftNickname'):
splitMessage = message.content
splitMessage = splitMessage.split()
path = "nicknames/" + splitMessage[1]
f = open(path, "w")
f.write(splitMessage[2])
f.close()
msg = "Set " + splitMessage[1] + "'s nickname to " + splitMessage[2]
elif message.content.startswith('?'):
msg = "That is not a valid command, use ?help for help"
else:
return
if (message.content == oldcommand) and (message.author == oldauthor):
s1 = str(messagetime)
s2 =str(datetime.now().time())
FMT = '%H:%M:%S.%f'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
if tdelta.seconds < 60:
if "Please don't spam commands" in oldmsg:
return
else:
msg = "Please don't spam commands\nWait " + str(round(60-tdelta.seconds, 0)) + " seconds to use this command"
messagetime = datetime.now().time()
oldauthor = message.author
oldcommand = message.content
oldmsg = msg
channel = message.channel
await channel.send(msg)

client.run(token)

@@ -0,0 +1 @@
<@!326831993520390154>
@@ -0,0 +1 @@
Sarah
@@ -0,0 +1 @@
<@666679318277259287>
@@ -0,0 +1 @@
<@524611536686415892>
@@ -0,0 +1 @@
<@524611536686415892>
@@ -0,0 +1 @@
<@!268863996432482323>
@@ -0,0 +1 @@
<@!660177761540898822>
@@ -0,0 +1 @@
<@!193415718971244544>
@@ -0,0 +1 @@
<@!414882988183126037>
@@ -0,0 +1 @@
Harry
@@ -0,0 +1 @@
Harry
@@ -0,0 +1 @@
Alex
@@ -0,0 +1 @@
<@!326832103440252929>
@@ -0,0 +1 @@
<@!500377318041190404>
@@ -0,0 +1 @@
<@!660175523208757290>
@@ -0,0 +1 @@
<@!659788584857108480>
@@ -0,0 +1 @@
<@540176948580581409>
@@ -0,0 +1,98 @@
import time
import discord
import status
import difflib
from mcstatus import MinecraftServer
from datetime import datetime
from datetime import timedelta


server = MinecraftServer(os.environ['SERVER'], int(os.environ['PORT']))

status = server.status()
print("The server has {0} players and replied in {1} ms".format(status.players.online, status.latency))
query = server.query()
print("The server has the following players online: {0}".format(", ".join(query.players.names)))

token = os.environ['TOKEN']

client = discord.Client()

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
await players()

@client.event
async def players():
currentPlayers = []
server = MinecraftServer(os.environ['SERVER'], int(os.environ['PORT']))
while True:
try:
time.sleep(1)
query = server.query()
players = "-".join(query.players.names)
players = players.split("-")

if '' in players:
players.remove('')


print("CP = " + str(currentPlayers))
print("P = " + str(players))
print("LCP = " + str(len(currentPlayers)))
print("LP = " + str(len(players)))
if not currentPlayers == players:
print("CP = " + str(currentPlayers))
print("P = " + str(players))
print("LCP = " + str(len(currentPlayers)))
print("LP = " + str(len(players)))
if len(currentPlayers) < len(players):
print("NEW LOGIN")
for i in players:
if not i in currentPlayers:
name = i
endStr = " has logged in\n"
elif len(currentPlayers) > len(players):
print("NEW LOGOUT")
for i in currentPlayers:
if not i in players:
name = i
endStr = " has logged out\n"
else:
print("HELP")


print(name)

now = datetime.now()
dateTimeCurrent = now.strftime("%d/%m/%Y %H:%M:%S")

msg = ""

path = "nicknames/" + name
try:
n = open(path, "r")
nick = " [" + n.read() + "] "
n.close()
except:
nick = ""




if name is not '':
msg = dateTimeCurrent + " - " + name + nick + endStr
channel = client.get_channel(694572684566331473)
if msg:
await channel.send(msg)
currentPlayers = players
if '' in currentPlayers:
currentPlayers.remove('')
print("NCP = " + str(currentPlayers))
print("NP = " + str(players))
except KeyboardInterrupt:
exit()

client.run(token)

11 run.py
@@ -0,0 +1,11 @@
def run():

import setup
import bot
import online
import os

if not os.path.isfile('.env'):
setup.environment()
os.system("python3 bot.py")
run()
@@ -0,0 +1,37 @@
def environment():
import os.path

if os.path.isfile('.env'):
overwrite = input("Would you like to overwrite your current credentials? (y/n)")
overwrite = overwrite.lower()
if overwrite == "y" or overwrite == "yes":
print("Creating new credientials... \n")
else:
return

token = input("Input your bot token here > ")
serverIP = input("Input your server URL/IP here > ")
port = input("Input your bot port here (If you don't know it, leave blank) > ")
if port == "":
port = "25565"

'''Concantinate into a string'''
data = "TOKEN={}\nSERVER={}\nPORT={}".format(token,serverIP,port)

'''Write data to the .env file'''
creds = open(".env", "w")
creds.write(data)
creds.close()

'''Verify the data has been written'''
print("\nVerifying data..")
verify = open(".env")
if data == verify.read():
print("Data written successfully")
return
else:
tryAgain = ("Error writing data. \n Try again? (y/n) > ")
if tryAgain == "y" or tryAgain == "yes":
environment()
else:
return

0 comments on commit b304932

Please sign in to comment.