This subroutine will (or should) be able to fit properly within any bot's code, since this is all 100% Perl code and is just a subroutine.
This subroutine will scan a folder and return the file paths of a given extension, and (if specified) will go on a recursive loop to also search subdirectories.
For example, if you have a directory tree like this:
So it scans the directory for a given file type (in this case, "pl") and also scan all the folders it finds inside of that folder, and returns a full path to your command's files.
And, unless your commands need proper names within the bot (i.e. "alert", "block", etc) you can make a command loading code in just a couple lines:
Code:
my @commands = &scanDir('./commands',1,'.pl');<br />foreach my $file (@commands) {<br /> require $file;<br />}
And then all your commands have been loaded.
Anyway, this kind of code has all kinds of purposes. Now finally, here's the code:
Code:
sub scanDir {<br /> # Directory data.<br /> my ($dir,$recurse,@ext) = @_;<br /><br /> # $dir = directory to scan<br /> # $recurse = recursion (1 or 0)<br /> # @ext = list of file extensions.<br /><br /> # List of all files.<br /> my @list = ();<br /><br /> # Open the directory.<br /> opendir (DIR, "$dir");<br /> foreach my $file (sort(grep(!/^\./, readdir(DIR)))) {<br /> # Is this another directory?<br /> if (-d "$dir/$file") {<br /> # Recursing?<br /> if ($recurse) {<br /> # Get this directory too.<br /> my @subs = &scanDir("$dir/$file",1,@ext);<br /> push (@list,@subs);<br /> next;<br /> }<br /> else {<br /> next;<br /> }<br /> }<br /><br /> my $good = 0;<br /><br /> # Check the file type.<br /> foreach my $type (@ext) {<br /> if ($file =~ /$type$/i) {<br /> $good = 1;<br /> }<br /> }<br /><br /> if (!@ext) {<br /> $good = 1;<br /> }<br /><br /> # Good file?<br /> if ($good == 1) {<br /> push (@list,"$dir/$file");<br /> }<br /> }<br /> closedir (DIR);<br /><br /> # Return the list.<br /> return @list;<br />}
DIRECTORY = The initial folder to scan. RECURSION = 1 or 0 -- If 1, it will also scan subdirectories within the initial DIRECTORY and return a list of those files as well. EXTENSIONS = An array of file extensions to search for (or omit and it will return ALL non-directory files).