#!/usr/bin/python3
# imports #
import asyncio
from pathlib import Path
from discord.errors import HTTPException
from os import walk,listdir,path,remove,mkdir
dirs = {
"characters" : "./notes/characters",
"timeline" : "./notes/timeline",
"root" : "./notes",
}
currentDirectory = dirs["root"]
# internal functions #
def parseMsg(msg):
cmd,args = "",[]
# find the first occurance of a space, to measure where the command is #
space_index = msg.find(" ")
# msg.find() returns -1 if it can't find something #
if space_index >= 0:
cmd = msg[0:space_index]
args = msg[space_index+1:len(msg)].split(" ")
# if it can't find a space, that means the command has no arguments, so leave args empty. #
else:
cmd = msg
return cmd,args
def getTxtFiles(dirToGet):
"""
Loops through all files in a directory, and
Yields *text file* name, and path.
"""
for dirpath,_,file_names in walk(Path(dirToGet)):
for file_name in file_names:
yield file_name,f"{dirpath}/{file_name}"
break
# bot commands #
async def search(msg,fileToFind):
"""
Searches all files from generator getTxtFiles(),
and checks if searchQuery is in their name.
Returns string with each file.
"""
file_list = "I found these files:\n"
file_data = {fname:fpath for fname,fpath in getTxtFiles(currentDirectory)}
for file_name,_ in file_data.items():
if fileToFind in file_name:
file_list += f"{file_name}\n"
await msg.channel.send(file_list)
async def ls(msg):
# make sure the directory requested is an allowed one #
file_list = f"Files in '{currentDirectory}':\n"
for file_name in listdir(currentDirectory):
file_list += f"{file_name}\n"
await msg.channel.send(file_list)
async def chdir(msg,directory):
global currentDirectory
dirToSwitch = f"{currentDirectory}/{directory}"
print(dirToSwitch)
# If it's a global directory #
if directory in dirs:
currentDirectory = dirs[directory]
await msg.channel.send(currentDirectory)
elif path.isdir(dirToSwitch):
currentDirectory = f"{currentDirectory}/{directory}"
await msg.channel.send(f"{currentDirectory}/{directory}")
async def pwd(msg):
await msg.channel.send(f"Current directory: {currentDirectory}")
# File Editing #
async def read(msg,fileToRead):
for file_name,file_path in getTxtFiles(currentDirectory):
if file_name == fileToRead:
with open(file_path,"r") as opened_file:
try:
await msg.channel.send(opened_file.read())
except HTTPException:
await msg.channel.send(f"File '{fileToRead}' is empty.")
opened_file.close()
async def create(msg,fileName):
# Check if the file doesnt exist. #
if not path.isfile(f"{currentDirectory}/{fileName}"):
with open(f"{currentDirectory}/{fileName}","x") as openedFile:
openedFile.close()
await msg.channel.send(f"Sucessfully created file '{fileName}'")
else:
await msg.channel.send(f"File already exists in directory {currentDirectory}")
async def nDir(msg,dirName):
# Check if there's already no directory with that name #
if not path.isdir(f"{currentDirectory}/{dirName}"):
mkdir(f"{currentDirectory}/{dirName}")
await msg.channel.send(f"Sucessfully created directory '{dirName}'")
else:
await msg.channel.send(f"Directory '{dirName}' already exists.")
async def rm(msg,fileToRemove):
filePath = f"{currentDirectory}/{fileToRemove}"
if path.isfile(filePath):
remove(filePath)
await msg.channel.send(f"Removed file '{filePath}'")
else:
await msg.channel.send("File does not exist.")
async def append(msg,fileToEdit,*paragraphs):
fileToOpen = f"{currentDirectory}/{fileToEdit}"
# If the file exists #
if path.isfile(fileToOpen):
with open(fileToOpen ,"a") as fileEditing:
for text in paragraphs:
fileEditing.write(text + " ")
fileEditing.close()
await msg.channel.send("Sucessfully appended to file!")
else:
await msg.channel.send("File does not exist.")