API: https://github.com/satom99/litcord
How can I check my valiable if its a valid ID?
local cmd, serverID, channelID, arg = string.match(message.content, '(%S+) (%d+) (%d+) (%S+.*)')
local server = client.servers:get('id', serverID)
serverID is the variable and I need to check if the serverID is a valid ID Otherwise I will get an error that server is a nil value.
I am trying days to finish one command and this is a part of it. If you need more contents then please tell me, I will link it to you.
Full Code:
client:on(
'message',
function(message)
local userID = message.author.id
local cmd, serverID, channelID, arg = string.match(message.content, '(%S+) (%d+) (%d+) (%S+.*)')
local server = client.servers:get('id', serverID)
local channel = server.channels:get('id', channelID)
local cmd = cmd or message.content
if (cmd == "!say") and message.parent.is_private then
if (userID == "187590758360940545") then
if not server then
return
end
if (server == servers) then
if (channel == channels) then
message.channel:sendMessage(arg)
else
message:reply("I don't know this channel.")
return
end
message:reply("I don't know this server.")
end
else
message:reply(":sob: Stop!!!!")
end
end
end
)
And how I can let it write in the channel I want with functions message.channel:sendMessage(arg) this is like message:reply it replies back where the message came from.
Let's forget about validating the serverID for one moment.
Of course you should always handle the case client.servers:get('id', serverID)
returing nil
.
Simply validating serverID
somehow and hoping that you will get a valid server handle back is not an option.
So either use Luas error handling features https://www.lua.org/manual/5.3/manual.html#2.3
or simply check server
with an if statement so you won't use server
if it is nil
.
Simplified:
local server = client.servers:get('id', serverID)
if not server then
print("No server with id '" .. serverID .. "' found.")
return -- or do something clever here, show a message box or whatever...
end
-- server won't be nil from here
Unless you know for sure that there is no other way for nil being returned you should handle that possibility properly.