async def store_channel_in_file(channel: discord.TextChannel, file_path: str): """ Adds given text channel's id to file with given path if the channel id is not already contained in the file. Returns True if the channel id was added to the file. Returns False if the channel id was already contained in the file. """ util.create_file(file_path) with open(file_path, 'a+') as f: # Start reading from the beginning of the file. Note: file *writes* # will happen at the end of the file no matter what. f.seek(0) # The \n has to be here because: # - the lines in the file include the \n character at the end # - f.write(str) does not insert a new line after writing id_to_add = f"{channel.id}\n" for channel_id in f: if channel_id == id_to_add: return False f.write(id_to_add) return True
def decode(self, message): mask = int(message[0]) #mascara filename = message[2] #nome do arquivo path = message[3] #caminho if mask == notify.CREATE_DIR: #se for uma mensagem de criar pasta, chama a função que cria pasta, e assim por diante, para todas as máscaras util.create_folder(path, filename) elif mask == notify.DELETE_DIR: util.delete_folder(path, filename) elif mask == notify.CREATE_FILE: util.create_file(path, filename) elif mask == notify.DELETE_FILE: util.delete_file(path, filename) elif mask == notify.MODIFY_FILE: BkpSync.flag_send = 1 time.sleep(0.5) util.modify_file(path, filename, self.conn) time.sleep(1) BkpSync.flag_send = 0 elif mask == notify.DIR_MOVED_FROM: util.delete_folder(path, filename) elif mask == notify.DIR_MOVED_TO: util.create_folder(path, filename) elif mask == notify.FILE_MOVED_FROM: util.delete_file(path, filename) elif mask == notify.FILE_MOVE_TO: BkpSync.flag_send = 1 time.sleep(0.5) util.modify_file(path, filename, self.conn) time.sleep(1) BkpSync.flag_send = 0
def add_file(): error, conf = "", "" if "create_file_submit" in request.form: if request.form["file_name"] == "": error = messages.name_file_err; else: util.create_file(request.form["file_name"], request.form["file_content"]) conf = messages.file_created_conf elif "upload_file_submit" in request.form: if not request.files.get("file", None): error = messages.choose_file_err else: util.upload_file(request.files["file"]) conf = messages.file_uploaded_conf elif "sync_files_submit" in request.form: protocol.epidemic_sync_files() conf = messages.sync_files_conf elif "listen_sw_submit" in request.form: conf = messages.listen_sw_conf; protocol.sw_listen() elif "wlan0_submit" in request.form: protocol.interface = "wlan0" print protocol.interface elif "wlan1_submit" in request.form: protocol.interface = "wlan1" print protocol.interface return main(error=error, conf=conf)
def edit_multiline(what, args): with util.TemporaryDirectory(basedir=args.tempdir) as tempdir: filepath = tempdir + '/' + what util.create_file(filepath) edit_command = args.editor + ' ' + filepath if os.system(edit_command) == 0: res = util.slurp(filepath) return res return ''
async def delete_channel_from_file(channel: discord.TextChannel, file_path: str): """ Removes given text channel's id from file with given path if the channel id is contained in the file. Returns True if the channel id was deleted to the file. Returns False if the channel id could not be found in the file. """ util.create_file(file_path) with open(file_path, 'r') as f: channel_ids = f.readlines() id_to_remove = f"{channel.id}\n" id_found = False with open(file_path, 'w') as f: for channel_id in channel_ids: if channel_id != id_to_remove: f.write(channel_id) else: id_found = True return id_found
def force_global_dotfile(): dotfile = global_dotfile() if not os.path.isfile(dotfile): util.create_file(dotfile) return dotfile
def force_custom_dotfile(): dotfile = custom_dotfile() if not dotfile: dotfile = os.path.join(os.getcwd(), _dotfile) util.create_file(dotfile) return dotfile
elif path == '쿠팡': order_file, row_index = coupang(order_list) elif path == '인터파크': order_file, row_index = interpark(order_list) elif path == '네이버페이': order_file, row_index = naverpay(order_list) elif path == '지마켓' or path == '옥션': order_file, row_index = gmarket(order_list) elif path == '위메프': order_file, row_index = wemape(order_list) elif path == '김약사': order_file, row_index = kim(order_list) elif path == '와우김약사': order_file, row_index = wow_kim(order_list) elif path == '임박몰': order_file, row_index = imbak(order_list) else: order_file = {} exec(close_str) create_file(order_file, order_ws, row_index) # 금일 날짜로 파일 이름 만들기 from datetime import datetime result_file_name = datetime.today().strftime("%Y_%m_%d.xlsx") print(result_file_name) # 엑셀 파일 저장 order_wb.save(filename=result_file_name) order_wb.close()
def create( self ): create_dir( '/app' ) model_dir = create_dir( '/model' ) full_name = model_dir + '/' + self.name + '.py' create_file( full_name, self.value() )
async def track(self, ctx, *args): """ `!track <enable | disable> <course_id>` Configure the current text channel to receive an update when a course module is published on Canvas. """ if len(args) != 2: await ctx.send("Usage: `!track <enable | disable> <course_id>`") elif args[0] != "enable" and args[0] != "disable": await ctx.send("Usage: `!track <enable | disable> <course_id>`") else: modules_file = f"{periodic_tasks.COURSES_DIRECTORY}/{args[1]}/modules.txt" watchers_file = f"{periodic_tasks.COURSES_DIRECTORY}/{args[1]}/watchers.txt" try: if not periodic_tasks.CANVAS_INSTANCE: await ctx.send("Error: No Canvas instance exists!") return course = periodic_tasks.CANVAS_INSTANCE.get_course(args[1]) if args[0] == "enable": # The watchers file contains all the channels watching the course added = await self.store_channel_in_file( ctx.channel, watchers_file) util.create_file(modules_file) if added: await ctx.send( f"This channel is now tracking {course.name}.") # We will only update the modules if modules_file is empty. if os.stat(modules_file).st_size == 0: CanvasUtil.write_modules( modules_file, CanvasUtil.get_modules(course)) else: await ctx.send( f"This channel is already tracking {course.name}.") else: # this is the case where args[0] is "disable" deleted = await self.delete_channel_from_file( ctx.channel, watchers_file) if os.stat(watchers_file).st_size == 0: shutil.rmtree( f"{periodic_tasks.COURSES_DIRECTORY}/{args[1]}") if deleted: await ctx.send( f"This channel is no longer tracking {course.name}." ) else: await ctx.send( f"This channel is already not tracking {course.name}." ) except canvasapi.exceptions.ResourceDoesNotExist: await ctx.send("The given course could not be found.") except canvasapi.exceptions.Unauthorized: await ctx.send("Unauthorized request.") except canvasapi.exceptions.InvalidAccessToken: await ctx.send("Your Canvas token is invalid.")
async def check_canvas(bot: Bot): """ For every folder in COURSES_DIRECTORY we will: - get the modules for the Canvas course with ID that matches the folder name - compare the modules we retrieved with the modules found in COURSES_DIRECTORY/{course_id}/modules.txt - use the given bot to send the names of any modules not in the above file to all channels in COURSES_DIRECTORY/{course_id}/watchers.txt - update COURSES_DIRECTORY/{course_id}/modules.txt with the modules we retrieved from Canvas NOTE: the Canvas API distinguishes between a Module and a ModuleItem. In our documentation, though, the word "module" can refer to both; we do not distinguish between the two types. """ def get_field_value(module: Union[Module, ModuleItem]) -> str: """ This function returns a string that can be added to a Discord embed as a field's value. The returned string contains the module's name/title attribute (depending on which one it has), as well as a hyperlink to the module (if the module has the html_url attribute). If the module's name/title exceeds MAX_IDENTIFIER_LENGTH characters, we truncate it and append an ellipsis (...) so that the name/title has exactly MAX_IDENTIFIER_LENGTH characters. """ if hasattr(module, "title"): field = module.title else: field = module.name if len(field) > MAX_IDENTIFIER_LENGTH: field = f"{field[:MAX_IDENTIFIER_LENGTH - 3]}..." if hasattr(module, "html_url"): field = f"[{field}]({module.html_url})" return field def update_embed(embed: discord.Embed, module: Union[Module, ModuleItem], embed_list: List[discord.Embed]): """ Adds a field to embed containing information about given module. The field includes the module's name or title, as well as a hyperlink to the module if one exists. If the module's identifier (its name or title) has over MAX_IDENTIFIER_LENGTH characters, we truncate the identifier and append an ellipsis (...) so that the length does not exceed the maximum. The embed object that is passed in must have at most 24 fields. A deep copy of the embed object is appended to embed_list in two cases: - if adding the new field will cause the embed to exceed EMBED_CHAR_LIMIT characters in length - if the embed has 25 fields after adding the new field, we append embed to embed_list. In both cases, we clear all of the original embed's fields after adding the embed copy to embed_list. NOTE: changes to embed and embed_list will persist outside this function. """ field_value = get_field_value(module) # Note: 11 is the length of the string "Module Item" if 11 + len(field_value) + len(embed) > EMBED_CHAR_LIMIT: embed_list.append(copy.deepcopy(embed)) embed.clear_fields() embed.title = f"New modules found for {course.name} (continued):" if isinstance(module, Module): embed.add_field(name="Module", value=field_value, inline=False) else: embed.add_field(name="Module Item", value=field_value, inline=False) if len(embed.fields) == 25: embed_list.append(copy.deepcopy(embed)) embed.clear_fields() embed.title = f"New modules found for {course.name} (continued):" def get_embeds( modules: List[Union[Module, ModuleItem]]) -> List[discord.Embed]: """ Returns a list of Discord embeds to send to live channels. """ embed = discord.Embed(title=f"New modules found for {course.name}:", color=RED) embed_list = [] for module in modules: update_embed(embed, module, embed_list) if len(embed.fields) != 0: embed_list.append(embed) return embed_list async def send_embeds(course_directory: str, embed_list: List[discord.Embed]): """ Sends all embeds in embed_list to all valid Discord text channels listed in the watchers file inside the given course directory. We remove any line in the watchers file that is not a valid Discord text channel ID. If the watchers file does not contain any valid text channel IDs, we also delete the course directory since the course has no valid "watchers". This function assumes that the given directory actually contains a watchers file. """ watchers_file = f"{course_directory}/watchers.txt" with open(watchers_file, "r") as f: channel_ids = f.read().splitlines() with open(watchers_file, "w") as f: for channel_id in channel_ids: channel = bot.get_channel(int(channel_id)) if channel: f.write(channel_id + "\n") for element in embed_list: await channel.send(embed=element) if os.stat(watchers_file).st_size == 0: shutil.rmtree(course_directory) if os.path.exists(COURSES_DIRECTORY): courses = [name for name in os.listdir(COURSES_DIRECTORY)] # each folder in the courses directory is named with a course id (which is a positive integer) for course_id_str in courses: if course_id_str.isdigit(): course_id = int(course_id_str) course_dir = f"{COURSES_DIRECTORY}/{course_id}" modules_file = f"{course_dir}/modules.txt" watchers_file = f"{course_dir}/watchers.txt" try: course = CANVAS_INSTANCE.get_course(course_id) print(f"Downloading modules for {course.name}", flush=True) util.create_file(modules_file) util.create_file(watchers_file) with open(modules_file, 'r') as m: existing_modules = set(m.read().splitlines()) all_modules = CanvasUtil.get_modules(course) differences = list( filter( lambda module: str(module.id) not in existing_modules, all_modules)) embeds_to_send = get_embeds(differences) await send_embeds(course_dir, embeds_to_send) CanvasUtil.write_modules(modules_file, all_modules) except (canvasapi.exceptions.InvalidAccessToken, canvasapi.exceptions.Unauthorized, canvasapi.exceptions.Forbidden): with open(watchers_file, 'r') as w: for channel_id in w: channel = bot.get_channel(int(channel_id.rstrip())) if channel: await channel.send( f"Removing course with ID {course_id} from courses " f"being tracked; course access denied.") # Delete course directory if we no longer have permission to access the Canvas course. shutil.rmtree(course_dir) except Exception: print(traceback.format_exc(), flush=True)