Explorar o código

Clean delete cmd

Lucas Villeneuve %!s(int64=5) %!d(string=hai) anos
pai
achega
f74ebb2e3c
Modificáronse 2 ficheiros con 92 adicións e 50 borrados
  1. 28 38
      src/myanimebot.py
  2. 64 12
      src/utils.py

+ 28 - 38
src/myanimebot.py

@@ -252,46 +252,36 @@ async def info_cmd(message):
 async def delete_user_cmd(words, message):
 	''' Processes the command "delete" and remove a registered user '''
 
-	if len(words) >= 4:
-		if (len(words) == 4):
-			try:
-				service = utils.Service.from_str(words[2])
-			except NotImplementedError:
-				await message.channel.send('Incorrect service. Use **"{}"** or **"{}"** for example'.format(globals.SERVICE_MAL, globals.SERVICE_ANILIST))
-				return
-
-			user = words[3]
-			
-			cursor = globals.conn.cursor(buffered=True, dictionary=True)
-			cursor.execute("SELECT servers FROM t_users WHERE LOWER({})=%s AND service=%s".format(globals.DB_USER_NAME), [user.lower(), service.value])
-			data = cursor.fetchone()
-			
-			print('data = {}'.format(data))
-			print("SELECT servers FROM t_users WHERE LOWER({})={} AND service={}".format(globals.DB_USER_NAME, user.lower(), service.value))
+	# Check if command is valid
+	if len(words) != 4:
+		if (len(words) < 4):
+			return await message.channel.send("Usage: {} delete **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
+		return await message.channel.send("Too many arguments! You have to specify only one username.")
+	try:
+		service = utils.Service.from_str(words[2])
+	except NotImplementedError:
+		return await message.channel.send('Incorrect service. Use **"{}"** or **"{}"** for example'.format(globals.SERVICE_MAL, globals.SERVICE_ANILIST))
+	user = words[3]
+	server_id = str(message.guild.id)
+	
+	user_servers = utils.get_user_servers(user, service)
+	print('User servers = {}'.format(user_servers))
+	# If user is not present in the database
+	if user_servers is None:
+		return await message.channel.send("The user **" + user + "** is not in our database for this server!")
+
+	# Else if present, update the servers for this user
+	srv_string = utils.remove_server_from_servers(server_id, user_servers)
+	
+	if srv_string is None: # Server not present in the user's servers
+		return await message.channel.send("The user **" + user + "** is not in our database for this server!")
 
-			# If user is present in the database
-			if data is not None:
-				srv_string = ""
-				present = False
-				
-				for server in data['servers'].split(','):
-					if server != str(message.guild.id):
-						if srv_string == "": srv_string = server
-						else: srv_string += "," + server
-					else: present = True
-				
-				if present == True:
-					if srv_string == "": cursor.execute("DELETE FROM t_users WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME), [user.lower(), service.value])
-					else: cursor.execute("UPDATE t_users SET servers = %s WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME), [srv_string, user.lower(), service.value])
-					globals.conn.commit()
-					
-					await message.channel.send("**" + user + "** deleted from the database for this server.")
-				else: await message.channel.send("The user **" + user + "** is not in our database for this server!")
-			else: await message.channel.send("The user **" + user + "** is not in our database for this server!")
+	if srv_string == "":
+		utils.delete_user_from_db(user, service)
+	else:
+		utils.update_user_servers_db(user, service, srv_string)
 
-			cursor.close()
-		else: await message.channel.send("Too many arguments! You have to specify only one username.")
-	else: await message.channel.send("Usage: {} delete **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
+	return await message.channel.send("**" + user + "** deleted from the database for this server.")
 
 
 @globals.client.event

+ 64 - 12
src/utils.py

@@ -149,9 +149,12 @@ def truncate_end_show(show):
 	return show
 
 
-def get_channels(server_id: int):
+def get_channels(server_id: int) -> dict:
 	''' Returns the registered channels for a server '''
 
+	if server_id is None:
+		return None
+
 	# TODO Make generic execute
 	cursor = globals.conn.cursor(buffered=True, dictionary=True)
 	cursor.execute("SELECT channel FROM t_servers WHERE server = %s", [server_id])
@@ -160,9 +163,12 @@ def get_channels(server_id: int):
 	return channels
 
 
-def is_server_in_db(server_id) -> bool:
+def is_server_in_db(server_id : str) -> bool:
 	''' Checks if server is registered in the database '''
 
+	if server_id is None:
+		return False
+
 	cursor = globals.conn.cursor(buffered=True)
 	cursor.execute("SELECT server FROM t_servers WHERE server=%s", [server_id])
 	data = cursor.fetchone()
@@ -170,10 +176,8 @@ def is_server_in_db(server_id) -> bool:
 	return data is not None
 
 
-def get_users():
+def get_users() -> List[dict]:
 	''' Returns all registered users '''
-    # Refresh database
-	# globals.conn.commit()
 
 	cursor = globals.conn.cursor(buffered=True, dictionary=True)
 	cursor.execute('SELECT {}, service, servers FROM t_users'.format(globals.DB_USER_NAME))
@@ -181,14 +185,62 @@ def get_users():
 	cursor.close()
 	return users
 
+def get_user_servers(user_name : str, service : Service) -> str:
+	''' Returns a list of every registered servers for a user of a specific service, as a string '''
 
-def get_user(user_id):
-	''' Returns the user from an id '''
-    # Refresh database
-	# globals.conn.commit()
+	if user_name is None or service is None:
+		return
 
 	cursor = globals.conn.cursor(buffered=True, dictionary=True)
-	cursor.execute('SELECT {}, service, servers FROM t_users WHERE '.format(globals.DB_USER_NAME))
-	users = cursor.fetchall()
+	cursor.execute("SELECT servers FROM t_users WHERE LOWER({})=%s AND service=%s".format(globals.DB_USER_NAME),
+					 [user_name.lower(), service.value])
+	user_servers = cursor.fetchone()
 	cursor.close()
-	return users
+
+	if user_servers is not None:
+		return user_servers["servers"]
+	return None
+
+
+def remove_server_from_servers(server : str, servers : str) -> str:
+	''' Removes the server from a comma-separated string containing multiple servers '''
+
+	servers_list = servers.split(',')
+	print('Trying to remove {} in {}'.format(server, servers_list))
+
+	# If the server is not found, return None
+	if server not in servers_list:
+		return None
+
+	# Remove every occurence of server
+	servers_list = [x for x in servers_list if x != server]
+	print('New list {}'.format(servers_list))
+	# Build server-free string
+	return ','.join(servers_list)
+
+
+def delete_user_from_db(user_name : str, service : Service) -> bool:
+	''' Removes the user from the database '''
+
+	if user_name is None or service is None:
+		return False
+
+	cursor = globals.conn.cursor(buffered=True)
+	cursor.execute("DELETE FROM t_users WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME),
+						 [user_name.lower(), service.value])
+	globals.conn.commit()
+	cursor.close()
+	return True
+
+
+def update_user_servers_db(user_name : str, service : Service, servers : str) -> bool:
+	if user_name is None or service is None or servers is None:
+		return False
+
+	cursor = globals.conn.cursor(buffered=True)
+	cursor.execute("UPDATE t_users SET servers = %s WHERE LOWER({}) = %s AND service=%s".format(globals.DB_USER_NAME),
+	 					 [servers, user_name.lower(), service.value])
+	globals.conn.commit()
+	cursor.close()
+	return True
+