Skip to content
Permalink
Browse files
Added comments
  • Loading branch information
hollan84 committed May 20, 2020
1 parent ed6cdcc commit 1e015ff4137af2fe76e18a8ff81b3a2c70e48ec9
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 108 deletions.
@@ -13,43 +13,50 @@ import settings
import developer
import bot_functions as functions

copyfile(".env", "lib/.env")
copyfile(".env", "lib/.env") #Copies the env file to the lib directory

from dotenv import load_dotenv
load_dotenv()

token = os.environ['TOKEN']
client = discord.Client()

load_dotenv() #Loads the environment variable

token = os.environ['TOKEN'] #Loads the bot token
client = discord.Client() #Sets the client for Discord

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
status = "{} different servers".format(database.get_total("*"))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=status))
print(f'{client.user} has connected to Discord!')
status = "{} different servers".format(database.get_total("*")) #Gets the total number of servers that the bot has a database of
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=status)) #Sets the status to how many servers the bot is tracking

@client.event
async def on_message(message):

guild_id = str(hash(message.guild))
guild_id = str(hash(message.guild)) #Gets the numerical ID of the server

if database.guild_check(guild_id) == False:
guild_name = str(message.guild)
database.new_guild(guild_id, guild_name)
status = "{} different servers".format(database.get_total("*"))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=status))
if database.guild_check(guild_id) == False: #Checks to see if there is no record of the server that has just sent a message
guild_name = str(message.guild) #Gets the name of the guild from the message
database.new_guild(guild_id, guild_name) #Adds a blank guild to the servers database
status = "{} different servers".format(database.get_total("*")) #Gets how many servers the bot has a record of
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=status)) #Changes the status

prefix = database.read_database("command_prefix", guild_id)
prefix = database.read_database("command_prefix", guild_id) #Reads the prefix that the server has set, ? by default

if not message.content.startswith(prefix):
return
if not message.content.startswith(prefix): #Checks to see if the message starts with the prefix
return #No point checking the rest of the message if the message doesn't start with the prefix

user_message = functions.language(message.content, guild_id) #Splits the message up to be read easier later
message_command = user_message.split()
message_command = message_command[0] #Gets the command to be checked which increases speed of the checks

user_message = functions.language(message.content, guild_id)
message_command = user_message.split()
message_command = message_command[0]
sites = { #Sets the sites that may be used later in the program
"support" : "http://devchat.alastairserver.co.uk/",
"paypal" : "http://donate.alastairserver.co.uk/",
"custom_github" : "http://customminecraftbotgithub.alastairserver.co.uk/",
"hosted_github" : "http://minecraftbotgithub.alastairserver.co.uk/",
"normal_bot" : "http://minecraftbot.alastairserver.co.uk",
"developer_bot" : "http://minecraftbotdev.alastairserver.co.uk/"
}

commands = {
commands = { #Sets the commands for the help
"server" : "Displays the saved server address",
"status" : "Gets the status of the server along with players (players only display if the server allows it)",
"minecraftNickname" : "Sets the nickname of a username to allow easy recognition when using the status command",
@@ -59,32 +66,35 @@ async def on_message(message):
"source" : "Gives the bot source code from Github",
"share" : "Add the bot to other servers",
"botinfo" : "Get information on the bot",
"version" : "Gives the bot release version"
"version" : "Gives the bot release version",
"donate" : "Allows you to donate to the development of this project"
}

server = MinecraftServer(database.read_database("minecraft_server", guild_id), int(database.read_database("server_port", guild_id)))
server = MinecraftServer(database.read_database("minecraft_server", guild_id), int(database.read_database("server_port", guild_id))) #Read the minecraft database

'''Checking which command has been issued'''
if message.author == client.user: #Make sure that the bot doesn't reply to itself
return
elif ('help') in message_command:
msg = ""
for command in commands:
if command in user_message:
msg = "{}{} - {}".format(prefix, command, commands[command])
if len(msg) == 0:
msg = "" #Sets a blank message to add to
for command in commands: #Iterates through the list of commands
if command in user_message: #Checks to see if the user is checking a specific command instead of the command list
msg = "{}{} - {}".format(prefix, command, commands[command]) #Sets msg to the help for that specific command
if len(msg) == 0: #Checks to see if msg has aleady been added to
msg = "Commands:\n"
for command in commands:
if command == "map" or command == "download":
if database.read_database(command, guild_id) is not None:
msg = "{}- {}{}\n".format(msg, prefix, command)
for command in commands: #Iterates over the commands
if command == "map" or command == "download": #Checks to see if the command to be listed is 'map' or 'download' (Removes 'map'/'download' if not set in settings)
if database.read_database(command, guild_id) is not None: #If there is a value assocated with the value 'map' or 'download' in the guild record
msg = "{}- {}{}\n".format(msg, prefix, command) #Add map or download to the msg
else:
msg = "{}- {}{}\n".format(msg, prefix, command)
msg = "{}If you want more information on a specific command use '{}help [command name]'".format(msg, prefix)
msg = "{}- {}{}\n".format(msg, prefix, command) #Add command to the message
msg = "{}If you want more information on a specific command use '{}help [command name]'".format(msg, prefix) #Additional help

'''Simple one line bot responses'''
elif ('source') in message_command:
msg = "Self Hosted: https://github.coventry.ac.uk/hollan84/MinecraftDiscord\nHosted: https://github.coventry.ac.uk/hollan84/NativeMinecraftDiscord"
msg = "Self Hosted: {}\nHosted: {}".format(sites["custom_github"], sites["hosted_github"])
elif ('share') in message_command:
msg = "Add to other servers!\nNormal Bot: http://minecraftbot.alastairserver.co.uk\nDeveloper Bot: http://minecraftbotdev.alastairserver.co.uk/\n(Don't add both bots to the same server due to command conflicts)"
msg = "Add to other servers!\nNormal Bot: {}\nDeveloper Bot: {}\n(Don't add both bots to the same server due to command conflicts)".format(sites["normal_bot"], sites["developer_bot"])
elif ('map') in message_command:
msg = database.read_database("map", guild_id)
elif ('server') in message_command:
@@ -93,6 +103,12 @@ async def on_message(message):
msg = database.read_database("download", guild_id)
elif ('version') in message_command:
msg = "Minecraft Bot - Version {}".format(str(os.environ['VERSION']))
elif ('donate') in message_command:
msg = "Donate to the development of this bot here:\n{}".format(sites["paypal"])
elif ('support') in message_command:
msg = "Join our support server here:\n{}".format(sites["support"])

'''More complex responses'''
elif ('botinfo') in message_command:
msg = "Minecraft Bot - Version {}\n".format(str(os.environ['VERSION']))
msg = "{}Total Discord Servers: {}\n".format(msg, database.get_total("*"))
@@ -120,27 +136,26 @@ async def on_message(message):
nick = "{} [{}]".format(player, database.read_player(player))
msg = msg.replace(player, nick)
elif ('settings') in message_command:
if not database.sql_guard(message.content):
return
if not database.sql_guard(message.content): #Checks to see if the message contains any words that could compromise data
return #Don't respond if the message contains anything dangerous
if "Minecraft Bot" in str(message.author.roles):
msg = settings.settings(message.content, guild_id)
else:
msg = "You need to have the role 'Minecraft Bot' to change these settings"
elif ('minecraftnickname') in message_command:
splitMessage = message.content
splitMessage = splitMessage.split()
if not database.sql_guard(user_message): #Checks to see if the message contains any words that could compromise data
return #Don't respond if the message contains anything dangerous
splitMessage = user_message.split() #Split the message into a list
database.add_player(splitMessage[1], splitMessage[2])
msg = "Set " + splitMessage[1] + "'s nickname to " + splitMessage[2]
elif message.content.startswith(prefix):
msg = "That is not a valid command, use {}help for help".format(prefix)
else:
return
else: #If the message is blank
msg = "That is not a valid command, use {}help for help\nIf this command conflicts with another bot, use '{}settings prefix [prefix]' to change it".format(prefix, prefix)

if msg == None:
msg = "This setting doesn't appear to be currently set, use {}settings to change this".format(prefix)

channel = message.channel
await channel.send(msg)
channel = message.channel #Gets the channel of the message
await channel.send(msg) #Send the message

client.run(token)

@@ -32,9 +32,9 @@ def help(user_message, prefix, guild_id):
msg = "{}If you want more information on a specific command use '{}help [command name]'".format(msg, prefix)

def language(user_message, guild_id):
if database.read_database("language", guild_id) != "en":
if database.read_database("language", guild_id) != "en": #If the server is not set as english
translator = Translator()
user_message = user_message[len(prefix):]
user_message = translator.translate(user_message, src=database.read_database("language", guild_id), dest='en')
user_message = "{}{}".format(prefix,user_message.text)
return user_message.lower()
user_message = translator.translate(user_message, src=database.read_database("language", guild_id), dest='en') #Translate the message to English
user_message = "{}{}".format(prefix,user_message.text) #Rebuild message
return user_message.lower() #Returns the lowercase message
@@ -1,4 +1,4 @@
def configure():
import setup
setup.environment()
setup.environment() #Start the setup
configure()
@@ -2,68 +2,61 @@ import sqlite3
from sqlite3 import Error
import os

def devs(user):
def database_read(sql):
conn = connect()
cur = conn.cursor()
cur.execute(sql)
return cur.fetchall()

def database_write(sql):
conn = connect()
sql = '''SELECT username
FROM developers'''
cur = conn.cursor()
cur.execute(sql)
for i in cur.fetchall():
conn.commit()

def devs(user):
sql = '''SELECT username
FROM developers'''
for i in database_read(sql):
user_value = i[0]
if str(user) in str(user_value):
return True
return False

def permission_check(command, user):
conn = connect()
sql = '''SELECT {}
FROM developers
WHERE username = "{}"'''.format(command, user)
cur = conn.cursor()
cur.execute(sql)
for i in cur.fetchall():
for i in database_read(sql):
user_value = i[0]
if str(user_value) == "1":
return True
return False

def devs_read(table):
conn = connect()
sql = '''SELECT *
FROM {}'''.format(table)
cur = conn.cursor()
cur.execute(sql)
return str(cur.fetchall())
return str(database_read(sql))

def add_dev(username):
conn = connect()
sql = '''INSERT INTO developers(username, data, deploy, add_dev, modify_dev, remove_dev, restart, start, stop)
VALUES("{}", FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)'''.format(username)
print(sql)
cur = conn.cursor()
cur.execute(sql)
conn.commit()
database_write(sql)

def remove_dev(username):
conn = connect()
sql = '''DELETE FROM developers
WHERE username = "{}"'''.format(username)
cur = conn.cursor()
cur.execute(sql)
conn.commit()
database_write(sql)

def modify_dev(username, permission, value):
if value == "true":
value = 1
else:
value = 0
conn = connect()
sql = '''UPDATE developers
SET {} = "{}"
WHERE username = "{}"'''.format(permission, value, username)
cur = conn.cursor()
cur.execute(sql)
conn.commit()
database_write(sql)

def sql_guard(message):
danger_commands = ["drop", "table", "delete", "from", "update", "insert", "into", "select", "truncate"]
@@ -82,13 +75,10 @@ def create_connection(db_file):
return conn

def modify_database(header_name, change, guild_id):
conn = connect()
sql = '''UPDATE servers
SET {} = "{}"
WHERE guild_id = "{}"'''.format(header_name, change, guild_id)
cur = conn.cursor()
cur.execute(sql)
conn.commit()
database_write(sql)

def add_player(player, nick):
if read_player(player) == "":
@@ -98,46 +88,34 @@ def add_player(player, nick):
sql = '''UPDATE players
SET nickname = "{}"
WHERE username = "{}"'''.format(nick, player)
conn = connect()
cur = conn.cursor()
cur.execute(sql)
conn.commit()
database_write(sql)

def read_player(player):
conn = connect()
sql = '''SELECT nickname
FROM players
WHERE username == "{}"'''.format(player)
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
data = database_read(sql)
if data:
data = data[0]
if data[0]:
return data[0]
return ""

def read_database(header_name, guild_id):
conn = connect()
sql = '''SELECT {}
FROM servers
WHERE guild_id == {}'''.format(header_name, guild_id)
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
database_read(sql)
if data:
data = data[0]
if data[0]:
return data[0]
return ""

def get_total(header_name):
conn = connect()
sql = '''SELECT {}
FROM servers'''.format(header_name)
cur = conn.cursor()
cur.execute(sql)
return len(cur.fetchall())
return len(read_database(sql))

def insert_new_guild(conn, sql_vars):
sql = '''INSERT INTO servers(guild_id, guild_name, server_port, command_prefix, antispam, language)
@@ -149,7 +127,6 @@ def insert_new_guild(conn, sql_vars):
def connect():
database = os.path.dirname(os.path.realpath("database/db.db"))
database = database + "/db.db"

return create_connection(database)

def new_guild(guild_id, guild_name):
@@ -1,19 +1,27 @@
import database
import os
import time
import sys

def developer_modify(message):
msg = ""
command = message[1]
if command == "deploy":
os.system("./deploy.sh")
os.system("git pull")
time.sleep(10)
path = os.path.dirname(os.path.realpath("developer.py"))
path = "{}{}".format(path.replace("lib/", "/"), "/run.py")
print(path)
os.execlp(path)
exit()
elif command == "start":
start = True
return "This is WIP and currently doesn't work"
elif command == "restart":
os.system("./start.sh")
exit()
path = os.path.dirname(os.path.realpath("developer.py"))
path = "{}{}".format(path.replace("lib/", "/"), "/run.py")
print(path)
os.execv(path, sys.argv)
if len(message) >= 2:
if command == "data":
if message[2] == "*":

0 comments on commit 1e015ff

Please sign in to comment.