Example #1
0
    async def age(self, ctx, *, timespec: str = None):
        """
        Set the maximum age of non-art posts
        """
        channel = ctx.message.channel

        if not timespec:
            sec = self.settings_for(channel)["EXPIRATION"]
            await self.bot.say("Current maximum age is %s." % _generate_timespec(sec))
        else:
            try:
                sec = _parse_time(timespec)
            except BadTimeExpr as e:
                await self.bot.say(error(e.args[0]))
                return

            if sec >= (14 * 24 * 60 * 60):
                await self.bot.say(error(
                    "Discord limits bulk deletes to messages posted within two weeks. "
                    "Please choose a maximum age shorter than that."
                ))
                return

            self.update_setting(channel, "EXPIRATION", sec)
            msg = "Maximum post age set to %s." % _generate_timespec(sec)

            if sec < POLL_INTERVAL:
                poll_spec = _generate_timespec(POLL_INTERVAL)
                msg += "\n\n" + warning("Note: this cog only checks message history every %s." % poll_spec)

            await self.bot.say(msg)
Example #2
0
    async def removelib(self, ctx):
        "Delete your library"

        user = ctx.message.author

        await self.bot.say(warning("Are you sure you want to delete your library? (yes/no)"))
        response = await self.bot.wait_for_message(author=user, timeout=15, check=check_response)

        if response:
            response = response.content.strip().lower()

            if response in "yes":
                delete_key(user.id)
                await self.bot.say("{}, you are way out of this league.".format(user.mention))
            elif response in "no":
                await self.bot.say("Well, that was close!")
        else:
            await self.bot.say("Yeah, that's what I thought.")
Example #3
0
    async def _add_centralized(self,
                               ctx,
                               name,
                               interval,
                               command,
                               repeat,
                               start=None,
                               start_in=None):
        channel = ctx.message.channel
        server = ctx.message.server
        author = ctx.message.author
        name = name.lower()
        now = datetime.now(tz=timezone.utc)

        min_time = 30 if repeat else 5

        prefix = await self.get_prefix(ctx.message)
        command = command.lstrip(prefix)

        try:
            interval = _parse_time(interval)
        except BadTimeExpr as e:
            await self.bot.say(error(e.args[0]))
            return

        if start_in:
            try:
                start_in = _parse_time(start_in)
            except BadTimeExpr as e:
                await self.bot.say(error(e.args[0]))
                return
            start = now + timedelta(seconds=start_in)
        elif start:
            try:
                start = self._get_start(start, now)
            except ValueError:
                await self.bot.say(error('Invalid timestamp format!'))
                return
        else:
            start = now

        if interval < min_time:
            await self.bot.say("I'm sorry, {}, I can't let you do that. "
                               "Your time interval is waaaay too short and "
                               "I'll likely get rate limited. Try going above"
                               " {} seconds.".format(author.name, min_time))
            return
        elif name in self.events.get(server.id, {}):
            if repeat:
                msg = warning("An event with that name already exists!")
            else:
                msg = warning("That command is already scheduled to run!")
            await self.bot.say(msg)
            return

        if repeat:
            logmsg = 'add {} "{}" to {} on {} every {}s starting {}'
            msg = '"{}" will run `{}` every {}, starting at {} ({}).'
        else:
            logmsg = 'add {} "{}" to {} on {} in {}s'
            msg = 'I will run `{1}` in {2}.'

        log.info(
            logmsg.format(name, command, channel.name, server.name, interval,
                          start.timestamp()))

        await self._add_event(name, command, server, channel, author, interval,
                              repeat, start)

        timeexpr = _generate_timespec(interval)

        delta = self._format_start(start, now)

        msg = msg.format(name, command, timeexpr, start, delta)
        await self.bot.say(msg)
Example #4
0
    async def _add_centralized(self, ctx, name, interval, command, repeat, start=None, start_in=None):
        channel = ctx.message.channel
        server = ctx.message.server
        author = ctx.message.author
        name = name.lower()
        now = datetime.now(tz=timezone.utc)

        min_time = 30 if repeat else 5

        prefix = await self.get_prefix(ctx.message)
        command = command.lstrip(prefix)

        try:
            interval = _parse_time(interval)
        except BadTimeExpr as e:
            await self.bot.say(error(e.args[0]))
            return

        if start_in:
            try:
                start_in = _parse_time(start_in)
            except BadTimeExpr as e:
                await self.bot.say(error(e.args[0]))
                return
            start = now + timedelta(seconds=start_in)
        elif start:
            try:
                start = self._get_start(start, now)
            except ValueError:
                await self.bot.say(error('Invalid timestamp format!'))
                return
        else:
            start = now

        if interval < min_time:
            await self.bot.say("I'm sorry, {}, I can't let you do that. "
                               "Your time interval is waaaay too short and "
                               "I'll likely get rate limited. Try going above"
                               " {} seconds.".format(author.name, min_time))
            return
        elif name in self.events.get(server.id, {}):
            if repeat:
                msg = warning("An event with that name already exists!")
            else:
                msg = warning("That command is already scheduled to run!")

            await self.bot.say(msg)
            return

        if repeat:
            logmsg = 'add {} "{}" to {} on {} every {}s starting {}'
            msg = '"{}" will run `{}` every {}, starting at {} ({}).'
        else:
            logmsg = 'add {} "{}" to {} on {} in {}s'
            msg = 'I will run `{1}` in {2}.'

        log.info(logmsg.format(name, command, channel.name, server.name, interval, start.timestamp()))

        await self._add_event(name, command, server, channel, author, interval, repeat, start)

        timeexpr = _generate_timespec(interval)

        delta = self._format_start(start, now)

        msg = msg.format(name, command, timeexpr, start, delta)
        await self.bot.say(msg)
Example #5
0
    async def promptRestart(self, serverID):    
        serverIDPath = dataPath + "/" + serverID
        channel = -1
        prompts = {}
        priPrompts = []
        promptsToUse = {}
        newPrompt = {}
        canidatePrompts = []
        channelObject = None
        prompts = {}
        
        #if this bot isn't even logged in yet, don't bother
        if not self.bot.is_logged_in:
            return True
        
        #see if busy file exists for this server. If so, promptRestart is already running and this instance should abort
        if os.path.isdir(serverIDPath + busyFile):
            print("Crap, promptRestart is already running!")
            return False
        else:
            os.makedirs(serverIDPath + busyFile)
        
        if not os.path.isfile(serverIDPath + '/settings.txt'):
            #remove busyfile        
            if os.path.isdir(serverIDPath + busyFile):
                shutil.rmtree(serverIDPath + busyFile)
            return True
        
        #get settings information from JSON file
        with open(serverIDPath + '/settings.txt', 'r') as file:
            try:
                settings = json.load(file)
                settings = settings['settings']
            except ValueError:
                print("could not get settings from global settings")
                await self.bot.say("ERROR: Composeprompt: promptRestart: Could not get data from globalsettings.txt JSON file!")
                return True
       
        print("checking if promptrun is in settings")
        #check to see if composeprompt is supposed to be running in this server
        if "promptrun" in settings:
            if settings["promptrun"] is False:
                return True
        else:
            return True     
       
        #if it gets to this point, then it is supposed to be running this this server
      
        #get which channel composeprompt should run in for this server
        if "channel" in settings:
            channel = settings["channel"]
            channelObject = self.bot.get_channel(settings["channel"])
        else:
            channel = self.bot.get_server(serverID)
            channelObject = channel
            await self.bot.send_message(channel, 'Error. Bot does not have channel to run in. Using default channel')    
     
        with open(serverIDPath + '/entries.txt', 'r') as file:    
            try:
                entries = json.load(file)
            except ValueError:
                await self.bot.say("ERROR: Composeprompt: promptRestart: Could not get data from entires.txt JSON file!")
                return True
                
        #get prompts from file
        with open(serverIDPath + '/prompts.txt', 'r') as file:
            try:
                prompts = json.load(file)
            except ValueError:
                await self.bot.say("ERROR: Composeprompt: promptRestart: Could not get data from prompts.txt JSON file!")
                return True
       
        #get if there was a prompt for the previous week. If so, show it and what was submitted last week.
        if "prompt" in settings:
            userMention = await self.bot.get_user_info(settings["prompt"]["author"])  
            await self.bot.send_message(self.bot.get_channel(channel), bold("Last week's prompt was:\n") + box(settings["prompt"]["prompt"]) + "Submitted by " + userMention.mention)  
 
            #see if list of entries is empty
            if len(entries["entries"]) > 0:
                #if not empty, print out all the entires
                await self.bot.send_message(self.bot.get_channel(channel), bold("Here's what people submitted!:\n"))

                for entry in entries["entries"]:
                    userMention = await self.bot.get_user_info(entry["author"])   
                    await self.bot.send_message(self.bot.get_channel(channel), "Submission by " + userMention.mention + " :\n" + entry["entry"])   

                # delete entries
                with open(serverIDPath + '/entries.txt', 'w+') as file:
                    json.dump(newEntriesList, file, indent=4)
                
            else:
                #state that there were no entries
                await self.bot.send_message(self.bot.get_channel(channel), warning('There were no submitted entries this week. Gosh darn it!'))
               
        #see if there are any priority prompts
        with open(serverIDPath + '/priorityprompts.txt', 'r') as file:    
            try:
                priPrompts = json.load(file)
            except ValueError:
                await self.bot.say("ERROR: Composeprompt: promptRestart: Could not get data from prompts.txt JSON file!")
                return True
        
        #see if priority list is empty. If it has stuff in it, use that first. Else, use regular prompts
        
        if len(priPrompts["priprompts"]) > 0:
            promptsToUse = priPrompts["priprompts"][0]
            priPrompts["priprompts"].pop(0)

            with open(serverIDPath + '/priorityprompts.txt', 'w+') as file:
                json.dump({"priprompts": priPrompts["priprompts"]}, file, indent=4)
              
        else:  #use regular prompts     
            #see if candidate exist if so, choose winner. Otherwise, randomly choose a prompt from all available prompts           
            candidatePrompts = [];
            settings = {}
            with open(serverIDPath + '/settings.txt', 'r') as file:
                try:
                    settings = json.load(file)
                except ValueError:
                    await self.bot.say("ERROR: Composeprompt: promptRestart: Could not get data from settigns.txt JSON file!")
                    return True
                     
            #see if there are condidate prompts
            if 'candidateprompts' in settings['settings']:
                #see which prompt has the most votes on it.  
                topReacted = settings['settings']['candidateprompts']
                highestNum = 0;
                authors = []
                server = self.bot.get_server(serverID)
                for candidatePrompt in settings['settings']['candidateprompts']:
                    channelObject = server.get_channel(settings['settings']["channel"])  
                    candidateMessage = await self.bot.get_message(channelObject, candidatePrompt['id'])

                    #count the number of stars on each reaction
                    for reaction in candidateMessage.reactions:
                        if(type(reaction.emoji) is str and str(ord(reaction.emoji[0])) == str(likeEmoji) and reaction.count >= highestNum):                          
                            if reaction.count > highestNum:
                                topReacted = []
                            highestNum = reaction.count
                            topReacted.append(candidatePrompt)
                    
                promptsToUse = topReacted[randint(0, len(topReacted) - 1)]               
            else:             
                if len(prompts["prompts"]) >= minPrompts:
                    #randomly choose a new prompt to set for this week's prompt
                    #ensure the chosen prompt is placed at the front of the list
                    #do not consider last week's chosen prompt for this week
                    index = randint(1, len(prompts["prompts"]) - 1)
                    promptsToUse = prompts["prompts"][index]
                    prompts["prompts"][index], prompts["prompts"][0] = prompts["prompts"][0], prompts["prompts"][index] #swap prompts
                    settings["prompt"] = promptsToUse
                    
                else:
                    promptsToUse["prompt"] = "There are not enough prompts. Please submit some!"
                    promptsToUse["author"] = self.bot.user.id
                    settings.pop("prompt", None)
     
            try:
                promptToRemove = promptsToUse
                promptToRemove.pop("id", None)
                prompts["prompts"].remove(promptToRemove)
            except Exception as e:
                print("Exception:")
                print(str(e))
       
            with open(serverIDPath + '/prompts.txt', 'w+') as promptFile:
                json.dump({'prompts': prompts["prompts"]}, promptFile, indent=4)  # rewrite prompts.txt with updated list of prompts

        #print out new prompt
        userMention = await self.bot.get_user_info(promptsToUse["author"])       
        await self.bot.send_message(self.bot.get_channel(channel), bold("This week's prompt:\n") + box(promptsToUse["prompt"]) + "Submitted by " + userMention.mention)     

        if(len(priPrompts["priprompts"]) <= 0):
            settings = {}
            with open(serverIDPath + '/settings.txt', 'r') as file:
                try:
                    settings = json.load(file)
                except ValueError:
                    print("couldn't write settings!")
                    await self.bot.say("ERROR: Composeprompt: promptRestart: Could not get data from settings.txt JSON file!")
                    return True
        
            #if there are enough promtps, choose 5 canidate prompts
            print(str(len(prompts["prompts"])) + " " + str(minPrompts))
            if len(prompts["prompts"]) >= minPrompts:
                #choose 5 more prompts
                index = randint(0, len(prompts["prompts"]) - 1)
                await self.bot.send_message(self.bot.get_channel(channel), bold("This week's canidate prompts"))
            
                for i in range(1, 6):
                    canidatePrompts.append(prompts["prompts"][(index + i) % len(prompts["prompts"])])
                    message = await self.bot.send_message(self.bot.get_channel(channel), box(canidatePrompts[i-1]["prompt"]))
                    canidatePrompts[i-1]["id"] = message.id
                    
                await self.bot.send_message(self.bot.get_channel(channel), bold("Please vote for the prompt you'd like to do next week by reacting to it with a " +  str(chr(likeEmoji)) + "!"))
                #re-write settings              
                settings['settings']['candidateprompts'] = canidatePrompts;               
            else:
                #at this point, you are running out of prompts
                await self.bot.send_message(self.bot.get_channel(channel), bold("No canidate prompts for this week. Please submit some ideas for new ones."))
                settings['settings'].pop('candidateprompts', None)
            
            #set new prompt and re-write settings
            settings['settings']['prompt'] = promptsToUse
            with open(serverIDPath + '/settings.txt', 'w+') as file: 
                json.dump({'settings': settings['settings']}, file, indent=4)
        else:
            await self.bot.send_message(self.bot.get_channel(channel), "Next week's prompt has already been decided...");
            
            #re-write settings to remove canidateprompts...since there are none
            settings = {}
            with open(serverIDPath + '/settings.txt', 'r') as file:
                try:
                    settings = json.load(file)
                except ValueError:
                    print("Had trouble writing to settings!")
                    await self.bot.say("ERROR: Composeprompt: promptRestart: Could not write data to settings.txt JSON file!")
                    return True
            
            settings['settings'].pop('candidateprompts', None)
            settings['settings']['prompt'] = promptsToUse
            
            with open(serverIDPath + '/settings.txt', 'w+') as file: 
                json.dump({'settings': settings['settings']}, file, indent=4)
              
        #restart prompt timer 
        with open(dataPath + '/globalsettings.txt', 'r') as file:  
            try:
                globalSettings = json.load(file)
            except ValueError:
                await self.bot.say("ERROR: Composeprompt: promptRestart: Could not get data from globalsettings.txt JSON file!")
                print("globalsettings not working")
                return True

        isInList = False     
        for x in globalSettings["globalsettings"]["promptstarttimes"]:
            if x == serverID:
                isInList = True
                break

        #record new time and start new timer
        if isInList:
            newTimeStruct = self.convertToStructTime(globalSettings["globalsettings"]["promptstarttimes"][serverID])
            globalSettings["globalsettings"]["nextpromptreset"][serverID] = [newTimeStruct.year, newTimeStruct.month, newTimeStruct.day, newTimeStruct.hour, newTimeStruct.minute]
        
            with open(dataPath + "/globalsettings.txt", "w+") as settingsFile:
                json.dump(globalSettings, settingsFile, indent=4)
        
        #remove busyfile   
        if os.path.isdir(serverIDPath + busyFile):
            shutil.rmtree(serverIDPath + busyFile)
            
        return True