def delete_file(request): if request.method == 'POST': response = HttpResponse() if request.user.is_authenticated(): if request.POST['directory'] == '': filename = request.POST['file'] else: filename = request.POST['directory'] + '/' + request.POST['file'] try: file = UserFiles.objects.filter(user__username=request.user.username).get(file=('users/'+ str(request.user.username)+ '/'+filename)) file.delete() json_helper.delete_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/', filename, settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+filename) json_helper.logger(settings.MEDIA_ROOT+'log.txt', request.user.username, 'deleted file: ', filename) response.content = json.dumps(json_helper.read_json(settings.MEDIA_ROOT+'users/'+ str(request.user.username)+'/file_list.txt')) response['Content-Type'] = 'application/json' response.status_code = 200 except UserFiles.DoesNotExist: response.content = "File does not exist" response.status_code = 495 else: response.content = "Failed to authenticate user" response.status_code = 497 return response else : return HttpResponse()
async def update_data(self): self.bot.total_server = len(self.bot.guilds) self.bot.total_user = len([u for u in self.bot.users if not u.bot]) async with asyncio.Lock(): data = json_helper.read_json("stats") data["executed_commands"] = self.bot.total_executed_commands json_helper.write_json("stats", data)
def upload_file(request): if request.method == 'POST': if request.user.is_authenticated(): print "-------------------------upload file" form = Form(request.POST, request.FILES) if form.is_valid(): print "file valid" print request.FILES directory = request.POST['directory'] instance = UserFiles(user=request.user, directory=directory, file=request.FILES['file']) if directory == '': json_helper.update_file( settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/', instance.file.name, settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/' + instance.file.name) else: json_helper.update_file( settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/', directory + '/' + instance.file.name, settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/' + directory + '/' + instance.file.name) instance.save() json_helper.logger(settings.MEDIA_ROOT + 'log.txt', request.user.username, 'updated file: ', instance.file.name) response = HttpResponse() response.content = json.dumps( json_helper.read_json(settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/file_list.txt')) response['Content-Type'] = 'application/json' response.status_code = 200 return response else: response = HttpResponse() response.content = "User not authenticated" response.status_code = 497 return response else: form = Form() if request.user.is_authenticated: documents = UserFiles.objects.filter( user__username=request.user.username) else: documents = {} return render_to_response('file_demo/upload_file.html', { 'documents': documents, 'form': form }, context_instance=RequestContext(request))
async def _reload(self, ctx: discord.ext.commands.context.Context): """ Reloads the config file into the bot instance. """ self.bot.config = json_helper.read_json("config") await ctx.send(embed=discord.Embed( title="Successfully reloaded the config!", colour=int(self.bot.config["embed-colours"]["default"], 16) ))
def json_request(request): response = HttpResponse() if request.user.is_authenticated(): response.content = json.dumps(json_helper.read_json(settings.MEDIA_ROOT+'users/'+ str(request.user.username)+'/file_list.txt')) response['Content-Type'] = 'application/json' response.status_code = 200 else: response.content = "Failed to authenticate user" response.status_code = 497 return response
def json_request(request): response = HttpResponse() if request.user.is_authenticated(): response.content = json.dumps( json_helper.read_json(settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/file_list.txt')) response['Content-Type'] = 'application/json' response.status_code = 200 else: response.content = "Failed to authenticate user" response.status_code = 497 return response
async def prefix(self, ctx: discord.ext.commands.context.Context, *, prefix='-'): """ Changes the bot prefix for this server. The prefix is used for all commands for this bot. """ async with asyncio.Lock(): data = json_helper.read_json("prefixes") data[str(ctx.message.guild.id)] = prefix json_helper.write_json("prefixes", data) await ctx.send(embed=discord.Embed( title= f"The server prefix has been set to `{prefix}`. To change it again use `{prefix}prefix <prefix>`!", colour=int(self.bot.config["embed-colours"]["default"], 16)))
def upload_file(request): if request.method == 'POST': if request.user.is_authenticated(): print "-------------------------upload file" form = Form(request.POST, request.FILES) if form.is_valid(): print "file valid" print request.FILES directory = request.POST['directory'] instance = UserFiles(user=request.user,directory=directory, file=request.FILES['file']) if directory == '': json_helper.update_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/', instance.file.name, settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+ instance.file.name) else: json_helper.update_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/', directory+'/'+instance.file.name, settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+ directory + '/' + instance.file.name) instance.save() json_helper.logger(settings.MEDIA_ROOT+'log.txt', request.user.username, 'updated file: ', instance.file.name) response = HttpResponse() response.content = json.dumps(json_helper.read_json(settings.MEDIA_ROOT+'users/'+ str(request.user.username)+'/file_list.txt')) response['Content-Type'] = 'application/json' response.status_code = 200 return response else: response = HttpResponse() response.content = "User not authenticated" response.status_code = 497 return response else: form = Form() if request.user.is_authenticated: documents = UserFiles.objects.filter(user__username=request.user.username) else: documents = {} return render_to_response( 'file_demo/upload_file.html', {'documents': documents, 'form': form}, context_instance=RequestContext(request) )
def register(request): if request.method == 'POST': response = HttpResponse() username = request.POST['username'] password = request.POST['password'] user = User.objects.create_user(username, '',password) user.save() user = authenticate(username=username, password=password) json_helper.create_user_folder(settings.MEDIA_ROOT+'users/'+str(user.username)+'/') json_helper.create_json(settings.MEDIA_ROOT+'users/'+str(user.username)+'/') if user is not None: if user.is_active: login(request, user) response.set_cookie('mfusername', username) response.content = json.dumps(json_helper.read_json(settings.MEDIA_ROOT+ 'users/'+str(user.username)+'/file_list.txt')) response.status_code = 200 return response else: return HttpResponse()
async def add(self, ctx: discord.ext.commands.context.Context, user: discord.Member): """ Blacklists users from the bot. The blacklisted users cannot use any commands from this bot. """ if user.id in self.bot.blacklisted_users: await ctx.send(embed=discord.Embed( title=f"`{user.display_name}` was already in the blacklist.", colour=int(self.bot.config["embed-colours"]["error"], 16) )) return self.bot.blacklisted_users.append(user.id) async with asyncio.Lock(): data = json_helper.read_json("blacklist") data["commandBlacklistedUsers"].append(user.id) json_helper.write_json("blacklist", data) await ctx.send(embed=discord.Embed( title=f"`{user.display_name}` has been added to the blacklist.", colour=int(self.bot.config["embed-colours"]["default"], 16) ))
def delete_file(request): if request.method == 'POST': response = HttpResponse() if request.user.is_authenticated(): if request.POST['directory'] == '': filename = request.POST['file'] else: filename = request.POST['directory'] + '/' + request.POST[ 'file'] try: file = UserFiles.objects.filter( user__username=request.user.username).get( file=('users/' + str(request.user.username) + '/' + filename)) file.delete() json_helper.delete_file( settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/', filename, settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/' + filename) json_helper.logger(settings.MEDIA_ROOT + 'log.txt', request.user.username, 'deleted file: ', filename) response.content = json.dumps( json_helper.read_json(settings.MEDIA_ROOT + 'users/' + str(request.user.username) + '/file_list.txt')) response['Content-Type'] = 'application/json' response.status_code = 200 except UserFiles.DoesNotExist: response.content = "File does not exist" response.status_code = 495 else: response.content = "Failed to authenticate user" response.status_code = 497 return response else: return HttpResponse()
def register(request): if request.method == 'POST': response = HttpResponse() username = request.POST['username'] password = request.POST['password'] user = User.objects.create_user(username, '', password) user.save() user = authenticate(username=username, password=password) json_helper.create_user_folder(settings.MEDIA_ROOT + 'users/' + str(user.username) + '/') json_helper.create_json(settings.MEDIA_ROOT + 'users/' + str(user.username) + '/') if user is not None: if user.is_active: login(request, user) response.set_cookie('mfusername', username) response.content = json.dumps( json_helper.read_json(settings.MEDIA_ROOT + 'users/' + str(user.username) + '/file_list.txt')) response.status_code = 200 return response else: return HttpResponse()
async def remove(self, ctx: discord.ext.commands.context.Context, user: discord.Member): """ Removes users from blacklist for bot commands. """ if user.id not in self.bot.blacklisted_users: await ctx.send(embed=discord.Embed( title=f"`{user.display_name}` was not found in the blacklist and therefore could not be removed from it.", colour=int(self.bot.config["embed-colours"]["error"], 16) )) await ctx.send( f"{user.display_name} was not found in the blacklist and therefore could not be removed from it.") return self.bot.blacklisted_users.remove(user.id) async with asyncio.Lock(): data = json_helper.read_json("blacklist") data["commandBlacklistedUsers"].remove(user.id) json_helper.write_json("blacklist", data) await ctx.send(embed=discord.Embed( title=f"`{user.display_name}` has been removed from the blacklist.", colour=int(self.bot.config["embed-colours"]["default"], 16) ))
class MyBot(commands.Bot): __version__ = 1.0 __author__ = "Jona Wessendorf" blacklisted_users = json_helper.read_json( "blacklist")["commandBlacklistedUsers"] total_executed_commands = json_helper.read_json( "stats")["executed_commands"] channel_ids = json_helper.read_json("channel") total_user = "******" total_server = "Unknown" total_lines_code = get_code_lines() cwd = str(Path(__file__).parent) emoji = {"repeat": "\U0001F501"} config = json_helper.read_json("config") token = json_helper.read_json("token") active_games = {} reaction_listener = [] def get_my_prefix(self, bot, ctx): if ctx.guild: prefix = json_helper.get_prefix(ctx.guild.id, bot) else: prefix = self.config["default-prefix"] return prefix def __init__(self): intents = discord.Intents.default() intents.presences = False intents.typing = False intents.members = True super().__init__(command_prefix=self.get_my_prefix, owner_ids=self.config["owner-ids"], help_command=None, case_insensitive=True, intents=intents) def run(self, t): cog_types = ["events", "commands", "tasks"] for cog_type in cog_types: for file in os.listdir(f"{self.cwd}/cogs/{cog_type}"): if file.endswith(".py"): self.load_extension(f"cogs.{cog_type}.{file[:-3]}") super().run(t) async def add_reaction_listener(self, listener_function, message: discord.Message, emoji: str = None, add_reaction: bool = False, remove_reactions: bool = True): async def listener(reaction: discord.Reaction, user: discord.User): if reaction.message.id != message.id: return if emoji and reaction.emoji != emoji: if remove_reactions: await reaction.remove(user) return await listener_function(reaction, user) if emoji and add_reaction: await message.add_reaction(emoji) self.reaction_listener.append(listener) @commands.Cog.listener() async def on_ready(self): print(f"---------\nlogged in as <{self.user}>\n---------") async def check_message_reply(self, message, main_instance: bool): # ignore messages from the bot itself if message.author == self.user: return False # ignore commands that are not in bot-commands channel if isinstance(message.channel, discord.TextChannel ) and message.channel.name != "bot-commands": return False # ignore dm messages if isinstance(message.channel, discord.DMChannel): pass # ignore messages form blacklisted users if message.author.id in self.blacklisted_users: return False # ignoring messages form users if devmode is turned on if self.config["devmode"]: if not await self.is_owner(message.author): # if the methode was run by the main on_message event if main_instance: if isinstance(message.channel, discord.TextChannel): pref = json_helper.get_prefix(message.guild.id, self) if message.content.startswith(pref): await message.channel.send( "```diff\n- The developer only mode is currently turned on! Therefore I will only process messages form the developer(s) of this bot.```" ) else: await message.channel.send( "```diff\n- The developer only mode is currently turned on! Therefore I will only process messages form the developer(s) of this bot.```" ) return False return True @commands.Cog.listener() async def on_message(self, message): if not await self.check_message_reply(message, True): return await self.process_commands(message)
def test_read_json(self): expected = self._json_stubs[0] file_path = os.path.join('./', 'data', 'super_smash_bros', 'mario.json') actual = json_helper.read_json(file_path) self.assertEqual(expected, actual)