usr bin python3 imports import asyncio from pathlib import Path from d

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/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.")