#!/usr/bin/python3
# imports #
import asyncio
from pathlib import Path
from discord.errors import HTTPException
from os import walk,listdir,path,remove
dirs = {
"characters":"./notes/characters",
"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():
"""
Loops through all files in a directory, and
Yields *text file* name, and path.
"""
for dirpath,_,file_names in walk(Path(currentDirectory)):
for file_name in file_names:
# if the file is a text file #
if file_name.endswith(".txt"):
yield file_name,f"{dirpath}/{file_name}"
# 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()}
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):
if directory in dirs:
global currentDirectory
currentDirectory = dirs[directory]
await msg.channel.send(f"Changed drectory to {currentDirectory}")
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():
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}") 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 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,*text):
fileEditing = {currentDirectory}/{fileToEdit}
# If the file exists #
pass