From 51e79e7b33b74ab42541663e91afa0e6e22b144b Mon Sep 17 00:00:00 2001 From: realtradam Date: Fri, 24 Apr 2020 18:23:35 -0400 Subject: Cleaned up variable names and some code close #2 --- FelicityBot.py | 166 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 84 insertions(+), 82 deletions(-) (limited to 'FelicityBot.py') diff --git a/FelicityBot.py b/FelicityBot.py index 59f0bfa..b07f9a1 100644 --- a/FelicityBot.py +++ b/FelicityBot.py @@ -9,53 +9,51 @@ import re #regular expression from mcstatus import MinecraftServer #Use 'python3 -m pip install mcstatus' to install, required for minecraft capabilities from dotenv import load_dotenv #Substitues the API key variable -storedStats = {} -#{userid : {hp : num, damage : num, death: num}, etc.} #This is the generic conversion that works on any server. #Uses generic messages -storedEmoji2 = {"!cheer": "", +storedEmojiUniversal = {"!cheer": "", "!stress": "", "!dance": "", "🦜": "", "!trash": "", "!jojo": "", "!bongo": ""} -#The second emoji set will work on any server, but uses generic commands load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN')# You need to set up a .env file which holds your token EMOJI_SET = os.getenv('EMOJI_SET')#get your custom made emoji set specifically for a server -IP = os.getenv('IP') -PORT = int(os.getenv('PORT')) -UNIQUE_SERVER = os.getenv('UNIQUE_SERVER') -MC_FOLDER = os.getenv('MC_FOLDER') -MC_RUNNABLE_SCRIPT = os.getenv('MC_RUNNABLE_SCRIPT') -PID_TXT = os.getenv('PID_TXT') -BOT_ID = os.getenv('BOT_ID') +IP = os.getenv('IP')#IP of your minecraft server +PORT = int(os.getenv('PORT'))#Port of your minecraft server +UNIQUE_SERVER = os.getenv('UNIQUE_SERVER')#ID of your unique server, that can handle special emoji's +MC_FOLDER = os.getenv('MC_FOLDER')#Folder of where you minecraft server/script resides +MC_RUNNABLE_SCRIPT = os.getenv('MC_RUNNABLE_SCRIPT')#Name of your script/server file +PID_TXT = os.getenv('PID_TXT')#Where the PID of your server is stored(to shut it down when you want to) client = discord.Client() #Sets up the bot, its variables, etc. when the bot is initially run @client.event async def on_ready(): - global storedStats, storedEmoji1 - print('{} is connected to the following servers:'.format(client.user)) + global storedStats, storedEmojiUnique + print('{}(id: {}) is connected to the following servers:'.format(client.user,client.user.id)) for guild in client.guilds: print('\t- {} (id: {})'.format(guild.name,guild.id)) await client.change_presence(status = 'None', activity=discord.Game('you like a damn fiddle')) #Loads up the statistics of players using the !attack command - json1_file = open('attacks.json') - json1_str = json1_file.read() - storedStats = json.loads(json1_str) + jsonFile = open('attacks.json') + jsonStr = jsonFile.read() + storedStats = json.loads(jsonStr) + #Format of the json data: + # {userid : {hp : num, damage : num, death: num}, etc.} #This sets up another emoji set that can be used on a specific server that # has specific replacable emojis set up - json_file = open(EMOJI_SET) - json_str = json_file.read() - storedEmoji1 = json.loads(json_str) + jsonFile = open(EMOJI_SET) + jsonStr = jsonFile.read() + storedEmojiUnique = json.loads(jsonStr) print("save data loaded") print('Bot is live!') @@ -65,10 +63,7 @@ async def on_ready(): @client.event async def on_message(message): #Variable set up - global storedStats, storedEmoji1, storedEmoji2 - temp = 0 - temp1 = 0 - temp2 = 0 + global storedStats, storedEmojiUnique, storedEmojiUniversal #Used for user identification isVerified = "false" isAdmin = "false" @@ -88,9 +83,9 @@ async def on_message(message): #Depending on which server the message was in: what emoji set should be used if str(message.guild.id) == str(UNIQUE_SERVER): - animatedEmoji = storedEmoji1 + animatedEmoji = storedEmojiUnique else: #All other servers use the generic set - animatedEmoji = storedEmoji2 + animatedEmoji = storedEmojiUniversal #Show info about the minecraft server if message.content.lower() == "!mc": @@ -143,63 +138,67 @@ async def on_message(message): await message.channel.send("You do not have permission to do that") #Splits the message, so the first word can be matched to a command, and use the rest of the words as parameters - temp = message.content.lower().split() - if (len(temp) == 2): #If the command has a parameter - if (temp[0] == "!react") and (len(temp) == 2): - for key in animatedEmoji: - if temp[1] == key: + splitMessage = message.content.lower().split() + if (len(splitMessage) == 2): #If the command has a parameter + if (splitMessage[0] == "!react"): + for emoji in animatedEmoji: + if splitMessage[1] == emoji: await message.delete() async for react in message.channel.history(limit=1): - await react.add_reaction(animatedEmoji[key]) + await react.add_reaction(animatedEmoji[emoji]) return return - if (temp[0] == "!delete") and (len(temp) == 2) and (isAdmin == "true"): - #This can be optimized by sending a batch delete rather then increment once - #It's somehwere in the discord.py api - async for delete in message.channel.history(limit=(int(temp[1])+1)): - await delete.delete() - return + if (splitMessage[0] == "!delete"): + if (isAdmin == "true"): + #This can be optimized by sending a batch delete rather then increment once + #It's somehwere in the discord.py api + async for delete in message.channel.history(limit=(int(splitMessage[1])+1)): + await delete.delete() + return + else: + message.channel.send('You do not have permission to do that') + return - if (temp[0] == '!attack') and (len(temp) == 2): + if (splitMessage[0] == '!attack'): #A little game where users can attack eachother #These variable names NEED to be cleaned up - temp1 = temp[1] - temp2 = [temp1[:2],temp1[2:-1],temp1[-1:]] - if temp2[1][:1] == '!': - temp2[1] = temp2[1][1:] - if temp2[0] == '<@' and temp2[2] == '>': - temp = random.randint(1,29) - if str(message.author.id) not in storedStats: - storedStats[str(message.author.id)] = {'hp' : 50, 'damage' : 0, 'deaths' : 0} - if str(temp2[1]) == BOT_ID: + messageParameter = splitMessage[1] + targetUserID = [messageParameter[:2],messageParameter[2:-1],messageParameter[-1:]]#This isolates just the ID number of the targeted user + if targetUserID[1][:1] == '!':#Sometimes discord leaves an ! in the id, but sometimes not. Not sure why but this purges it as it causes bugs with storing data(duplicated users) + targetUserID[1] = targetUserID[1][1:] + if targetUserID[0] == '<@' and targetUserID[2] == '>':#After formatting the code, if it is correctly formatted + if int(targetUserID[1]) == int(client.user.id):#Checks if it was the bot that was targeted in the attack await message.channel.send('') return - elif str(temp2[1]) not in storedStats: - storedStats[str(temp2[1])] = {'hp' : 50, 'damage' : 0, 'deaths' : 0} + damage = random.randint(1,29) + if str(message.author.id) not in storedStats: + storedStats[str(message.author.id)] = {'hp' : 50, 'damage' : 0, 'deaths' : 0} + elif str(targetUserID[1]) not in storedStats: + storedStats[str(targetUserID[1])] = {'hp' : 50, 'damage' : 0, 'deaths' : 0} - storedStats[str(temp2[1])]['hp'] -= temp - if storedStats[str(temp2[1])]['hp'] <= 0: - storedStats[str(temp2[1])]['deaths'] += 1 - storedStats[str(temp2[1])]['hp'] = 50 - if str(message.author.id) == str(temp2[1]): + storedStats[str(targetUserID[1])]['hp'] -= damage + if storedStats[str(targetUserID[1])]['hp'] <= 0: + storedStats[str(targetUserID[1])]['deaths'] += 1 + storedStats[str(targetUserID[1])]['hp'] = 50 + if str(message.author.id) == str(targetUserID[1]): await message.channel.send('') await message.channel.send('<@{}> killed themselves'.format(message.author.id)) return await message.channel.send('<:killed:690998665686548483>') - await message.channel.send('<@{}> dealt {} damage, killing {}!'.format(message.author.id,'{:,}'.format(temp),temp1)) - storedStats[str(message.author.id)]['damage'] += temp + await message.channel.send('<@{}> dealt {} damage, killing {}!'.format(message.author.id,'{:,}'.format(damage),messageParameter)) + storedStats[str(message.author.id)]['damage'] += damage else: - await message.channel.send('You dealt {0} damage to {1}\n{1} has {2} HP remaining'.format('{:,}'.format(temp),temp1,'{:,}'.format((storedStats[str(temp2[1])]['hp'])))) - storedStats[str(message.author.id)]['damage'] += temp + await message.channel.send('You dealt {0} damage to {1}\n{1} has {2} HP remaining'.format('{:,}'.format(damage),messageParameter,'{:,}'.format((storedStats[str(targetUserID[1])]['hp'])))) + storedStats[str(message.author.id)]['damage'] += damage return - if temp[0] == '!roll': - if len(temp) > 1: - await message.channel.send("<@{}> rolled a {}".format(message.author.id, random.randint(1, int(temp[1])))) - else: - await message.channel.send("Type a space and a number after !roll to roll a dice that size") - return + if splitMessage[0] == '!roll': + if len(splitMessage) == 2: + await message.channel.send("<@{}> rolled a {}".format(message.author.id, random.randint(1, int(splitMessage[1])))) + else: + await message.channel.send("Type a space and a number after !roll to roll a dice that size") + return if message.content.lower() == '!stats': @@ -214,9 +213,9 @@ async def on_message(message): await message.channel.send("data saved to server") if message.content.lower() == '!load' and (isAdmin == "true"): - json1_file = open('attacks.json') - json1_str = json1_file.read() - storedStats = json.loads(json1_str) + jsonFile = open('attacks.json') + jsonStr = jsonFile.read() + storedStats = json.loads(jsonStr) print("save data loaded") await message.channel.send("save data loaded") @@ -229,28 +228,31 @@ async def on_message(message): if message.content.lower() == '!list': - temp = "" + listedEmoji = ''#initializes the variable so that values can be 'added' into it for key in animatedEmoji: - temp += '{} --> {}\n'.format(key,animatedEmoji[key]) - await message.channel.send(temp) + listedEmoji += '{} --> {}\n'.format(key,animatedEmoji[key]) + await message.channel.send(listedEmoji) return #The following searches the user's message to see if any of the custom emoji set matches #If it does then it will replace it, and resend the message on behalf of the user # while also deleting the original users message #To identify the original user who sent the message, it also @'s them - temp2 = message.content - switchFlag = 0 - for key in animatedEmoji: - temp = re.search(re.escape(key), message.content, flags=re.I) - if (str(temp) != "None"): - temp2 = re.sub(re.escape(key), animatedEmoji[key], temp2, flags=re.I) - switchFlag = 1#sets a flag that a match was made, and should replace the message - if switchFlag == 1:#ONLY replace if a match was found - await message.channel.send('<@{}>:'.format(message.author.id)) - await message.delete() - await message.channel.send(temp2) - + #To prevent the bot from unintentionally hijacking messages on others servers, set it + # to only work on your unique server + if str(message.guild.id) == str(UNIQUE_SERVER): + modifiedMessage = message.content + switchFlag = 0 #A flag that determines of a match was made, and if the users message should be replaced + for key in animatedEmoji: + matchCheck = re.search(re.escape(key), message.content, flags=re.I)#Check if the message has a replacable emoji + if (str(matchCheck) != "None"): + modifiedMessage = re.sub(re.escape(key), animatedEmoji[key], modifiedMessage, flags=re.I) + switchFlag = 1#sets a flag that a match was made, and should replace the message + if switchFlag == 1:#ONLY replace if a match was found + await message.channel.send('<@{}>:'.format(message.author.id)) + await message.delete() + await message.channel.send(modifiedMessage) + -- cgit v1.2.3