async def removeprofile(self, ctx, *, name=None):
        """Remove a profile from your profile list."""
        name = None if name == None else name.replace("\n", " ").replace(
            "\r", "").replace("\t", " ").strip()
        if name == None:
            msg = 'Usage: `{}removeprofile [profile name]`'.format(ctx.prefix)
            return await ctx.send(msg)

        itemList = self.settings.getUserStat(ctx.author, ctx.guild, "Profiles")
        if not itemList or itemList == []:
            msg = '*{}* has no profiles set!  They can add some with the `{}addprofile "[profile name]" [link]` command!'.format(
                DisplayName.name(ctx.author), ctx.prefix)
            return await ctx.send(msg)
        item = next((x for x in itemList if x["Name"].lower() == name.lower()),
                    None)
        if not item:
            return await ctx.send(
                Utils.suppressed(
                    ctx, "{} not found in {}'s profile list!".format(
                        Nullify.escape_all(name),
                        DisplayName.name(ctx.author))))
        itemList.remove(item)
        self.settings.setUserStat(ctx.author, ctx.guild, "Profiles", itemList)
        await ctx.send(
            Utils.suppressed(
                ctx, "{} removed from {}'s profile list!".format(
                    Nullify.escape_all(item["Name"]),
                    DisplayName.name(ctx.author))))
	async def _add_item(self,ctx,name,value,l_role="RequiredLinkRole",l_list="Links",l_name="Link",l_key="URL"):
		# Check if we're admin/bot admin first - then check for a required role
		if not self._has_privs(ctx,l_role): return await ctx.send("You do not have sufficient privileges to access this command.")
		# Remove tabs, newlines, and carriage returns and strip leading/trailing spaces from the name
		name = None if name == None else name.replace("\n"," ").replace("\r","").replace("\t"," ").strip()
		# Passed role requirements!
		if name == None or value == None:
			msg = 'Usage: `{}add[[name]] "[[[name]] name]" [[[key]]]`'.format(ctx.prefix).replace("[[name]]",l_name.lower()).replace("[[key]]",l_key.lower())
			return await ctx.send(msg)
		itemList = self.settings.getServerStat(ctx.guild, l_list)
		if not itemList:
			itemList = []
		currentTime = int(time.time())
		item = next((x for x in itemList if x["Name"].lower() == name.lower()),None)
		if item:
			msg = '{} updated!'.format(Nullify.escape_all(item["Name"]))
			item[l_key]       = value
			item['UpdatedBy'] = DisplayName.name(ctx.author)
			item['UpdatedID'] = ctx.author.id
			item['Updated']   = currentTime
		else:
			itemList.append({"Name" : name, l_key : value, "CreatedBy" : DisplayName.name(ctx.author), "CreatedID": ctx.author.id, "Created" : currentTime})
			msg = '{} added to {} list!'.format(Nullify.escape_all(name),l_name.lower())
		self.settings.setServerStat(ctx.guild, l_list, itemList)
		return await ctx.send(msg)
	async def _item_info(self,ctx,name,l_role="RequiredLinkRole",l_list="Links",l_name="Link",l_key="URL"):
		if name == None:
			msg = 'Usage: `{}info{} "[{} name]"`'.format(ctx.prefix,l_name.lower(),l_name.lower())
			return await ctx.send(msg)
		itemList = self.settings.getServerStat(ctx.guild, l_list)
		if not itemList or itemList == []:
			msg = 'No [[name]]s in list!  You can add some with the `{}add[[name]] "[[[name]] name]" [[[key]]]` command!'.format(ctx.prefix).replace("[[name]]",l_name.lower()).replace("[[key]]",l_key.lower())
			return await ctx.send(msg)
		item = next((x for x in itemList if x["Name"].lower() == name.lower()),None)
		if not item:
			return await ctx.send('{} not found in {} list!'.format(Nullify.escape_all(name),l_name.lower()))
		current_time = int(time.time())
		msg = "**{}:**\n".format(Nullify.escape_all(item["Name"]))
		# Get the info
		created_by = DisplayName.memberForID(item.get("CreatedID",0),ctx.guild)
		created_by = DisplayName.name(created_by) if created_by else item.get("CreatedBy","`UNKNOWN`")
		msg += "Created by: {}\n".format(created_by)
		created    = item.get("Created",None)
		if created:
			msg += "Created: {} ago\n".format(ReadableTime.getReadableTimeBetween(created, current_time, True))
		if item.get("Updated",None):
			updated_by = DisplayName.memberForID(item.get("UpdatedID",0),ctx.guild)
			updated_by = DisplayName.name(updated_by) if updated_by else item.get("UpdatedBy","`UNKNOWN`")
			msg += "Updated by: {}\n".format(updated_by)
			updated    = item.get("Updated",None)
			if created:
				msg += "Updated: {} ago\n".format(ReadableTime.getReadableTimeBetween(updated, current_time, True))
		return await ctx.send(msg)
 async def addprofile(self, ctx, name=None, *, link=None):
     """Add a profile to your profile list."""
     # Remove tabs, newlines, and carriage returns and strip leading/trailing spaces from the name
     name = None if name == None else name.replace("\n", " ").replace(
         "\r", "").replace("\t", " ").strip()
     if name == None or link == None:
         msg = 'Usage: `{}addprofile "[profile name]" [link]`'.format(
             ctx.prefix)
         return await ctx.send(msg)
     itemList = self.settings.getUserStat(ctx.author, ctx.guild, "Profiles")
     if not itemList:
         itemList = []
     currentTime = int(time.time())
     item = next((x for x in itemList if x["Name"].lower() == name.lower()),
                 None)
     if item:
         msg = Utils.suppressed(
             ctx, "{}'s {} profile was updated!".format(
                 DisplayName.name(ctx.author),
                 Nullify.escape_all(item["Name"])))
         item["URL"] = link
         item["Updated"] = currentTime
     else:
         itemList.append({
             "Name": name,
             "URL": link,
             "Created": currentTime
         })
         msg = Utils.suppressed(
             ctx, "{} added to {}'s profile list!".format(
                 Nullify.escape_all(name), DisplayName.name(ctx.author)))
     self.settings.setUserStat(ctx.author, ctx.guild, "Profiles", itemList)
     await ctx.send(msg)
Beispiel #5
0
    async def teleunblock(self, ctx, *, guild_name=None):
        """Unblocks all tele-numbers associated with the passed guild (bot-admin only)."""
        isAdmin = ctx.author.permissions_in(ctx.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.guild, "AdminArray")
            for role in ctx.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.send(
                'You do not have sufficient privileges to access this command.'
            )
            return

        if guild_name == None:
            await ctx.send("Usage: `{}teleunblock [guild_name]`".format(
                ctx.prefix))
            return

        block_list = self.settings.getServerStat(ctx.guild, "TeleBlock")
        if block_list == None:
            block_list = []

        if not len(block_list):
            await ctx.send("No blocked numbers - nothing to unblock!")
            return

        # Verify our guild
        found = False
        target = None
        for guild in self.bot.guilds:
            teleNum = self.settings.getServerStat(guild, "TeleNumber")
            if guild.name.lower() == guild_name.lower():
                found = True
                target = guild
                break
        if not found:
            await ctx.send("I couldn't find that guild...")
            return

        if not target.id in block_list:
            msg = "*{}* is not currently blocked.".format(
                Nullify.escape_all(target.name))
            await ctx.send(msg)
            return

        # Here, we should have a guild to unblock
        block_list.remove(target.id)
        self.settings.setServerStat(ctx.guild, "TeleBlock", block_list)

        msg = "You have unblocked *{}!*".format(Nullify.escape_all(
            target.name))
        await ctx.send(msg)
	async def adduserrole(self, ctx, *, role = None):
		"""Adds a new role to the user role system (admin only)."""
		
		author  = ctx.message.author
		server  = ctx.message.guild
		channel = ctx.message.channel

		usage = 'Usage: `{}adduserrole [role]`'.format(ctx.prefix)
		
		isAdmin = author.permissions_in(channel).administrator
		# Only allow admins to change server stats
		if not isAdmin:
			await channel.send('You do not have sufficient privileges to access this command.')
			return
		
		if role == None:
			await ctx.send(usage)
			return

		if type(role) is str:
			if role == "everyone":
				role = "@everyone"
			# It' a string - the hope continues
			roleCheck = DisplayName.roleForName(role, server)
			if not roleCheck:
				msg = "I couldn't find **{}**...".format(Nullify.escape_all(role))
				await ctx.send(msg)
				return
			role = roleCheck

		# Now we see if we already have that role in our list
		try:
			promoArray = self.settings.getServerStat(server, "UserRoles")
		except Exception:
			promoArray = []
		if promoArray == None:
			promoArray = []

		for aRole in promoArray:
			# Get the role that corresponds to the id
			if str(aRole['ID']) == str(role.id):
				# We found it - throw an error message and return
				msg = '**{}** is already in the list.'.format(Nullify.escape_all(role.name))
				await channel.send(msg)
				return

		# If we made it this far - then we can add it
		promoArray.append({ 'ID' : role.id, 'Name' : role.name })
		self.settings.setServerStat(server, "UserRoles", promoArray)

		msg = '**{}** added to list.'.format(Nullify.escape_all(role.name))
		await channel.send(msg)
		return
	async def _remove_item(self,ctx,name,l_role="RequiredLinkRole",l_list="Links",l_name="Link",l_key="URL"):
		if not self._has_privs(ctx,l_role): return await ctx.send("You do not have sufficient privileges to access this command.")
		if name == None:
			msg = 'Usage: `{}remove{} "[{} name]"`'.format(ctx.prefix,l_name.lower(),l_name.lower())
			return await ctx.send(msg)
		itemList = self.settings.getServerStat(ctx.guild, l_list)
		if not itemList or itemList == []:
			msg = 'No [[name]]s in list!  You can add some with the `{}add[[name]] "[[[name]] name]" [[[key]]]` command!'.format(ctx.prefix).replace("[[name]]",l_name.lower()).replace("[[key]]",l_key.lower())
			return await ctx.send(msg)
		item = next((x for x in itemList if x["Name"].lower() == name.lower()),None)
		if not item:
			return await ctx.send('{} not found in {} list!'.format(Nullify.escape_all(name),l_name.lower()))
		itemList.remove(item)
		self.settings.setServerStat(ctx.guild, l_list, itemList)
		return await ctx.send('{} removed from {} list!'.format(Nullify.escape_all(item["Name"]),l_name.lower()))
	async def nosleep(self, ctx):
		"""I hope you're not tired..."""
		msg = await self.getText('https://www.reddit.com/r/nosleep/top.json?sort=top&t=week&limit=100')
		if not msg: return await ctx.send("Whoops! I couldn't find a working link.")
		mess = '__**{}**__\n\n'.format(msg['title'])
		mess += msg['content']
		await Message.Message(message=Nullify.escape_all(mess,markdown=False)).send(ctx)
Beispiel #9
0
 async def _stream_message(self, member, message, dest, test=False):
     message = re.sub(self.regexUserName,
                      "{}".format(DisplayName.name(member)), message)
     message = re.sub(self.regexUserPing, "{}".format(member.mention),
                      message)
     message = re.sub(self.regexServer,
                      "{}".format(Nullify.escape_all(dest.guild.name)),
                      message)
     # Get the activity info
     act = next((x for x in list(member.activities)
                 if x.type is discord.ActivityType.streaming), None)
     try:
         name = act.name
     except:
         name = "Mystery Game"
     try:
         url = act.url
     except:
         url = "Mystery URL"
     if test:
         message = re.sub(self.regexUrl, "GameURL", message)
         message = re.sub(self.regexGame, "GameName", message)
         message = re.sub(self.regexHere, "@​here", message)
         message = re.sub(self.regexEveryone, "@​everyone", message)
     else:
         message = re.sub(self.regexUrl, "{}".format(url), message)
         message = re.sub(self.regexGame, "{}".format(name), message)
         message = re.sub(self.regexHere, "@here", message)
         message = re.sub(self.regexEveryone, "@everyone", message)
     await dest.send(message)
    async def getautotemp(self, ctx):
        """Gets the temp role applied to each new user that joins."""
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        isAdmin = ctx.message.author.permissions_in(
            ctx.message.channel).administrator
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.message.channel.send(
                'You do not have sufficient privileges to access this command.'
            )
            return

        temp_id = self.settings.getServerStat(ctx.guild, "TempRole")
        if temp_id == None:
            # No temp setup
            await ctx.send("There is no default temp role.")
            return

        temp_role = DisplayName.roleForName(temp_id, ctx.guild)
        if temp_role == None:
            # Not a role anymore
            await ctx.send(
                "The default temp role ({}) no longer exists.".format(temp_id))
            return
        role_time = self.settings.getServerStat(ctx.guild, "TempRoleTime")
        msg = "**{}** is the default temp role - will be active for *{}*.".format(
            Nullify.escape_all(temp_role.name),
            ReadableTime.getReadableTimeBetween(0, role_time * 60))
        await ctx.send(msg)
Beispiel #11
0
 async def on_message(self, message):
     if message.author.bot: return
     if not message.guild: return
     message_responses = self.settings.getServerStat(
         message.guild, "MessageResponses", {})
     if not message_responses: return
     # We have something to check
     ctx = await self.bot.get_context(message)
     if ctx.command: return  # Don't check if we're running a command
     # Check for matching response triggers here
     content = message.content.replace(
         "\n", " ")  # Remove newlines for better matching
     for trigger in message_responses:
         match = re.fullmatch(trigger, content)
         if not match: continue
         # Got a full match - build the message, send it and bail
         m = message_responses[trigger]
         m = re.sub(self.regexUserName,
                    "{}".format(DisplayName.name(message.author)), m)
         m = re.sub(self.regexUserPing, "{}".format(message.author.mention),
                    m)
         m = re.sub(self.regexServer,
                    "{}".format(Nullify.escape_all(ctx.guild.name)), m)
         m = re.sub(self.regexHere, "@here", m)
         m = re.sub(self.regexEveryone, "@everyone", m)
         return await ctx.send(m)
	async def urunblock(self, ctx, *, member = None):
		"""Unblocks a user from the UserRole system (bot-admin only)."""
		isAdmin = ctx.author.permissions_in(ctx.channel).administrator
		if not isAdmin:
			checkAdmin = self.settings.getServerStat(ctx.guild, "AdminArray")
			for role in ctx.author.roles:
				for aRole in checkAdmin:
					# Get the role that corresponds to the id
					if str(aRole['ID']) == str(role.id):
						isAdmin = True
						break
		# Only allow bot-admins to change server stats
		if not isAdmin:
			await ctx.send('You do not have sufficient privileges to access this command.')
			return
		# Get the target user
		mem = DisplayName.memberForName(member, ctx.guild)
		if not mem:
			await ctx.send("I couldn't find {}.".format(Nullify.escape_all(member)))
			return
		# At this point - we have someone to unblock - see if they're blocked
		block_list = self.settings.getServerStat(ctx.guild, "UserRoleBlock")
		if not mem.id in block_list:
			await ctx.send("{} is not blocked from the UserRole module.".format(DisplayName.name(mem)))
			return
		block_list.remove(mem.id)
		self.settings.setServerStat(ctx.guild, "UserRoleBlock", block_list)
		await ctx.send("{} has been unblocked from the UserRole module.".format(DisplayName.name(mem)))
Beispiel #13
0
    async def addresponse(self, ctx, regex_trigger=None, *, response=None):
        """Adds a new response for the regex trigger.  If the trigger has spaces, it must be wrapped in quotes (bot-admin only).
		Available Options:
		
		[[user]]     = user name
		[[atuser]]   = user mention
		[[server]]   = server name
		[[here]]     = @​here ping
		[[everyone]] = @​everyone ping
		
		Example:  $addresponse "(?i)(hello there|\\btest\\b).*" [[atuser]], this is a test!
		
		This would look for a message starting with the whole word "test" or "hello there" (case-insensitive) and respond by pinging the user and saying "this is a test!"
		"""

        if not await Utils.is_bot_admin_reply(ctx): return
        if not regex_trigger or not response:
            return await ctx.send(
                "Usage: `{}addresponse regex_trigger response`".format(
                    ctx.prefix))
        # Ensure the regex is valid
        try:
            re.compile(regex_trigger)
        except Exception as e:
            return await ctx.send(Nullify.escape_all(e))
        # Save the trigger and response
        message_responses = self.settings.getServerStat(
            ctx.guild, "MessageResponses", {})
        context = "Updated" if regex_trigger in message_responses else "Added new"
        message_responses[regex_trigger] = response
        self.settings.setServerStat(ctx.guild, "MessageResponses",
                                    message_responses)
        return await ctx.send("{} response trigger!".format(context))
    async def setvkchannel(self, ctx, *, channel=None):
        """Sets which channel then mention posts to when enough votes against a user are reached."""
        isAdmin = ctx.message.author.permissions_in(
            ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild,
                                                     "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send(
                'You do not have sufficient privileges to access this command.'
            )
            return

        if channel == None:
            self.settings.setServerStat(ctx.guild, "VoteKickChannel", None)
            await ctx.send("Removed the vote kick channel.")
            return

        check_channel = DisplayName.channelForName(channel, ctx.guild, "text")
        if check_channel:
            self.settings.setServerStat(ctx.guild, "VoteKickChannel",
                                        check_channel.id)
            await ctx.send("Vote kick will now be mentioned in *{}.*".format(
                check_channel.mention))
            return
        await ctx.send("I couldn't find *{}*...".format(
            Nullify.escape_all(channel)))
	async def lastonline(self, ctx, *, member = None):
		"""Lists the last time a user was online if known."""
		if not member:
			msg = 'Usage: `{}lastonline "[member]"`'.format(ctx.prefix)
			return await ctx.send(msg)
		if type(member) is str:
			memberName = member
			member = DisplayName.memberForName(memberName, ctx.guild)
			if not member:
				msg = 'I couldn\'t find *{}*...'.format(Nullify.escape_all(memberName))
				return await ctx.send(msg)
		name = DisplayName.name(member)
		# We have a member here
		if not member.status == discord.Status.offline:
			msg = '*{}* is here right now.'.format(name)
		else:
			lastOnline = self.settings.getUserStat(member, ctx.guild, "LastOnline")
			if lastOnline == "Unknown":
				self.settings.setUserStat(member, ctx.guild, "LastOnline", None)
				lastOnline = None
			if lastOnline:
				currentTime = int(time.time())
				timeString  = ReadableTime.getReadableTimeBetween(int(lastOnline), currentTime, True)
				msg = 'The last time I saw *{}* was *{} ago*.'.format(name, timeString)
			else:
				msg = 'I don\'t know when *{}* was last online.  Sorry.'.format(name)
		await ctx.send(msg)
Beispiel #16
0
	async def define(self, ctx, *, word : str = None):
		"""Gives the definition of the word passed."""

		if not word:
			msg = 'Usage: `{}define [word]`'.format(ctx.prefix)
			await ctx.channel.send(msg)
			return
		url = "http://api.urbandictionary.com/v0/define?term={}".format(quote(word))
		msg = 'I couldn\'t find a definition for "{}"...'.format(Nullify.escape_all(word))
		title = permalink = None
		theJSON = await DL.async_json(url, headers = {'User-agent': self.ua})
		theJSON = theJSON["list"]
		if len(theJSON):
			# Got it - let's build our response
			words = []
			for x in theJSON:
				value = x["definition"]
				if x["example"]:
					ex = x["example"].replace("*","")
					lines = ["*{}*".format(y.strip()) if len(y.strip()) else "" for y in ex.split("\n")]
					value += "\n\n__Example(s):__\n\n{}".format("\n".join(lines))
				words.append({
					"name":"{} - by {} ({} 👍 / {} 👎)".format(string.capwords(x["word"]),x["author"],x["thumbs_up"],x["thumbs_down"]),
					"value":value
				})
			return await PickList.PagePicker(title="Results For: {}".format(string.capwords(word)),list=words,ctx=ctx,max=1,url=theJSON[0]["permalink"]).pick()
		await ctx.send(msg)
Beispiel #17
0
    async def joinpos(self, ctx, *, member=None):
        """Tells when a user joined compared to other users."""
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        if member == None:
            member = ctx.author

        if type(member) is str:
            member_check = DisplayName.memberForName(member, ctx.guild)
            if not member_check:
                msg = "I couldn't find *{}* on this server...".format(
                    Nullify.escape_all(member))
                await ctx.send(msg)
                return
            member = member_check

        joinedList = []
        for mem in ctx.message.guild.members:
            joinedList.append({'ID': mem.id, 'Joined': mem.joined_at})

        # sort the users by join date
        joinedList = sorted(joinedList,
                            key=lambda x: x["Joined"].timestamp()
                            if x["Joined"] != None else -1)

        check_item = {"ID": member.id, "Joined": member.joined_at}

        total = len(joinedList)
        position = joinedList.index(check_item) + 1

        before = ""
        after = ""

        msg = "*{}'s* join position is **{:,}**.".format(
            DisplayName.name(member), position, total)
        if position - 1 == 1:
            # We have previous members
            before = "**1** user"
        elif position - 1 > 1:
            before = "**{:,}** users".format(position - 1)
        if total - position == 1:
            # There were users after as well
            after = "**1** user"
        elif total - position > 1:
            after = "**{:,}** users".format(total - position)
        # Build the string!
        if len(before) and len(after):
            # Got both
            msg += "\n\n{} joined before, and {} after.".format(before, after)
        elif len(before):
            # Just got before
            msg += "\n\n{} joined before.".format(before)
        elif len(after):
            # Just after
            msg += "\n\n{} joined after.".format(after)
        await ctx.send(msg)
Beispiel #18
0
    async def teleblocks(self, ctx):
        """Lists guilds with blocked tele-numbers."""

        block_list = self.settings.getServerStat(ctx.guild, "TeleBlock")
        if block_list == None:
            block_list = []

        if not len(block_list):
            await ctx.send("No blocked numbers!")
            return

        block_names = []
        for block in block_list:
            server = self.bot.get_guild(block)
            if not server:
                block_list.remove(block)
                continue
            block_names.append("*" + server.name + "*")
        self.settings.setServerStat(ctx.guild, "TeleBlock", block_list)

        msg = "__Tele-Blocked Servers:__\n\n"

        #msg += ", ".join(str(x) for x in block_list)
        msg += ", ".join(Nullify.escape_all(block_names))

        await ctx.send(msg)
Beispiel #19
0
    async def tz(self, ctx, *, member=None):
        """See a member's TimeZone."""
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        if member == None:
            member = ctx.message.author

        if type(member) == str:
            # Try to get a user first
            memberName = member
            member = DisplayName.memberForName(memberName, ctx.message.guild)
            if not member:
                msg = 'Couldn\'t find user *{}*.'.format(
                    Nullify.escape_all(memberName))
                await ctx.channel.send(msg)
                return

        # We got one
        timezone = self.settings.getGlobalUserStat(member, "TimeZone")
        if timezone == None:
            msg = '*{}* hasn\'t set their TimeZone yet - they can do so with the `{}settz [Region/City]` command.'.format(
                DisplayName.name(member), ctx.prefix)
            await ctx.channel.send(msg)
            return

        msg = '*{}\'s* TimeZone is *{}*'.format(DisplayName.name(member),
                                                timezone)
        await ctx.channel.send(msg)
    async def addtemprole(self, ctx, *, role: str = None):
        """Adds a new role to the temp role list (admin only)."""
        usage = 'Usage: `{}addtemprole [role]`'.format(ctx.prefix)
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        isAdmin = ctx.message.author.permissions_in(
            ctx.message.channel).administrator
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.message.channel.send(
                'You do not have sufficient privileges to access this command.'
            )
            return

        if role == None:
            await ctx.message.channel.send(usage)
            return

        roleName = role
        role = DisplayName.roleForName(roleName, ctx.guild)
        if not role:
            msg = 'I couldn\'t find *{}*...'.format(
                Nullify.escape_all(roleName))
            await ctx.send(msg)
            return

        # Now we see if we already have that role in our list
        promoArray = self.settings.getServerStat(ctx.guild, "TempRoleList")

        if role.id in [int(x["ID"]) for x in promoArray]:
            # We found it - throw an error message and return
            msg = '**{}** is already in the list.'.format(
                Nullify.escape_all(role.name))
            await ctx.send(msg)
            return

        # If we made it this far - then we can add it
        promoArray.append({'ID': role.id, 'Name': role.name})
        self.settings.setServerStat(ctx.guild, "TempRoleList", promoArray)

        msg = '**{}** added to list.'.format(Nullify.escape_all(role.name))
        await ctx.message.channel.send(msg)
        return
Beispiel #21
0
 async def question(self, ctx):
     """Spout out some interstellar questioning... ?"""
     infoDict = await self.getTitle(
         'https://www.reddit.com/r/NoStupidQuestions/top.json?sort=top&t=week&limit=100',
         True)
     self.settings.setServerStat(ctx.guild, "LastAnswer", infoDict["url"])
     msg = '{}'.format(infoDict["title"])
     await ctx.send(Nullify.escape_all(msg, markdown=False))
Beispiel #22
0
    async def responses(self, ctx):
        """Lists the response triggers and their responses (bot-admin only)."""

        if not await Utils.is_bot_admin_reply(ctx): return
        message_responses = self.settings.getServerStat(
            ctx.guild, "MessageResponses", {})
        if not message_responses:
            return await ctx.send(
                "No responses setup!  You can use the `{}addresponse` command to add some."
                .format(ctx.prefix))
        entries = [{
            "name": "{}. ".format(i) + Nullify.escape_all(x),
            "value": Nullify.escape_all(message_responses[x])
        } for i, x in enumerate(message_responses, start=1)]
        return await PickList.PagePicker(title="Current Responses",
                                         list=entries,
                                         ctx=ctx).pick()
    async def listtemproles(self, ctx):
        """Lists all roles for the temp role system."""

        server = ctx.message.guild
        channel = ctx.message.channel

        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(server, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        # Get the array
        try:
            promoArray = self.settings.getServerStat(server, "TempRoleList")
        except Exception:
            promoArray = []
        if promoArray == None:
            promoArray = []

        if not len(promoArray):
            msg = "There aren't any roles in the user role list yet.  Add some with the `{}addtemprole` command!".format(
                ctx.prefix)
            await ctx.channel.send(msg)
            return

        # Sort by XP first, then by name
        # promoSorted = sorted(promoArray, key=itemgetter('XP', 'Name'))
        promoSorted = sorted(promoArray, key=lambda x: x['Name'])

        roleText = "**__Current Temp Roles:__**\n\n"
        for arole in promoSorted:
            # Get current role name based on id
            foundRole = False
            for role in server.roles:
                if str(role.id) == str(arole['ID']):
                    # We found it
                    foundRole = True
                    roleText = '{}**{}**\n'.format(
                        roleText, Nullify.escape_all(role.name))
            if not foundRole:
                roleText = '{}**{}** (removed from server)\n'.format(
                    roleText, Nullify.escape_all(arole['Name']))

        await channel.send(roleText)
    async def setupComplete(self, ctx):
        channel = ctx.message.channel
        author = ctx.message.author
        server = ctx.message.guild

        await author.send(
            '__Setup Status for *{}*:__\n\n**COMPLETE**\n\nThanks, *{}*, for hanging out with me and getting things setup.\nIf you want to explore my other options - feel free to check them all out with `{}help`.\n\nAlso - I work best in an admin role and it needs to be listed *above* any roles you would like me to manage.\n\nThanks!'
            .format(Nullify.escape_all(server.name), DisplayName.name(author),
                    ctx.prefix))
	async def dirtyjoke(self, ctx):
		"""Let's see if reddit can be dir-... oh... uh.. funny... (bot-admin only)"""
		# NSFW - check admin
		if not await Utils.is_bot_admin_reply(ctx,message="You do not have sufficient privileges to access nsfw subreddits."): return
		msg = await self.getText('https://www.reddit.com/r/DirtyJokes/top.json?sort=top&t=week&limit=100')
		if not msg: return await ctx.send("Whoops! I couldn't find a working link.")
		mess = '*{}*\n\n'.format(msg['title'])
		mess += msg['content']
		await Message.Message(message=Nullify.escape_all(mess,markdown=False)).send(ctx)
    async def vkinfo(self, ctx):
        """Lists the vote-kick info."""

        mute_votes = self.settings.getServerStat(ctx.guild, "VotesToMute")
        ment_votes = self.settings.getServerStat(ctx.guild, "VotesToMention")
        mute_time = self.settings.getServerStat(ctx.guild, "VotesMuteTime")
        ment_chan = self.settings.getServerStat(ctx.guild, "VoteKickChannel")
        vote_ment = self.settings.getServerStat(ctx.guild, "VoteKickMention")
        vote_rest = self.settings.getServerStat(ctx.guild, "VotesResetTime")
        vote_list = self.settings.getServerStat(ctx.guild, "VoteKickArray")
        vote_anon = self.settings.getServerStat(ctx.guild, "VoteKickAnon")

        msg = "__**Current Vote-Kick Settings For {}:**__\n```\n".format(
            Nullify.escape_all(ctx.guild.name))

        msg += "   Votes To Mute: {}\n".format(int(mute_votes))
        msg += "       Muted For: {}\n".format(
            ReadableTime.getReadableTimeBetween(0, mute_time))
        msg += "Votes to Mention: {}\n".format(int(ment_votes))
        if vote_ment:
            role_check = DisplayName.roleForName(vote_ment, ctx.guild)
            if not role_check:
                user_check = DisplayName.memberForName(vote_ment, ctx.guild)
                if not user_check:
                    msg += "         Mention: None\n"
                else:
                    msg += "         Mention: {}\n".format(user_check)
            else:
                msg += "         Mention: {} (role)\n".format(role_check)
        else:
            msg += "         Mention: None\n"

        m_channel = self.bot.get_channel(ment_chan)
        if m_channel:
            msg += "      Mention in: #{}\n".format(m_channel.name)
        else:
            msg += "      Mention in: None\n"
        if vote_rest == 0:
            msg += "      Vote reset: Permanent\n"
        elif vote_rest == 1:
            msg += "      Vote reset: After 1 second\n"
        else:
            msg += "      Vote reset: After {}\n".format(
                ReadableTime.getReadableTimeBetween(0, vote_rest))
        votes = 0
        for user in vote_list:
            votes += len(user["Kicks"])
        msg += " Anonymous votes: {}\n".format(vote_anon)
        msg += "    Active votes: {}\n```".format(votes)

        # Check if mention and mute are disabled
        if (ment_votes == 0 or ment_chan == None
                or ment_chan == None) and (mute_votes == 0 or mute_time == 0):
            msg += "\nSystem **not** configured fully."

        await ctx.send(msg)
	async def joke(self, ctx):
		"""Let's see if reddit can be funny..."""
		msg = await self.getText('https://www.reddit.com/r/jokes/top.json?sort=top&t=week&limit=100')
		if not msg: return await ctx.send("Whoops! I couldn't find a working link.")
		# Check for nsfw - and for now, only allow admins/botadmins to post those
		if msg['over_18']:
			# NSFW - check admin
			if not await Utils.is_bot_admin_reply(ctx,message="You do not have sufficient privileges to access nsfw subreddits."): return
		mess = '*{}*\n\n'.format(msg['title'])
		mess += msg['content']
		await Message.Message(message=Nullify.escape_all(mess,markdown=False)).send(ctx)
Beispiel #28
0
    async def teleblock(self, ctx, *, guild_name=None):
        """Blocks all tele-numbers associated with the passed guild (bot-admin only)."""
        isAdmin = ctx.author.permissions_in(ctx.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.guild, "AdminArray")
            for role in ctx.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.send(
                'You do not have sufficient privileges to access this command.'
            )
            return

        if guild_name == None:
            await ctx.send("Usage: `{}teleblock [guild_name]`".format(
                ctx.prefix))
            return

        # Verify our guild
        found = False
        target = None
        for guild in self.bot.guilds:
            teleNum = self.settings.getServerStat(guild, "TeleNumber")
            if not teleNum:
                continue
            if guild.name.lower() == guild_name.lower():
                if guild.id == ctx.guild.id:
                    # We're uh... blocking ourselves.
                    await ctx.send("You can't block your own number...")
                    return
                found = True
                target = guild
                break
        if not found:
            await ctx.send(
                "I couldn't find that guild to block.  Maybe they're not setup for :telephone: yet?"
            )
            return

        # Here, we should have a guild to block
        block_list = self.settings.getServerStat(ctx.guild, "TeleBlock")
        if block_list == None:
            block_list = []
        block_list.append(target.id)
        self.settings.setServerStat(ctx.guild, "TeleBlock", block_list)

        msg = "You are now blocking *{}!*".format(
            Nullify.escape_all(target.name))
        await ctx.send(msg)
    async def setvkmention(self, ctx, *, user_or_role=None):
        """Sets which user or role is mentioned when enough votes against a user are reached."""
        isAdmin = ctx.message.author.permissions_in(
            ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild,
                                                     "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send(
                'You do not have sufficient privileges to access this command.'
            )
            return

        if user_or_role == None:
            self.settings.setServerStat(ctx.guild, "VoteKickMention", None)
            await ctx.send("Removed the vote kick mention!")
            return

        check_role = DisplayName.roleForName(user_or_role, ctx.guild)
        if check_role:
            self.settings.setServerStat(ctx.guild, "VoteKickMention",
                                        check_role.id)
            await ctx.send("Vote kick will now mention the *{}* role.".format(
                Nullify.escape_all(check_role.name)))
            return
        check_user = DisplayName.memberForName(user_or_role, ctx.guild)
        if check_user:
            self.settings.setServerStat(ctx.guild, "VoteKickMention",
                                        check_user.id)
            await ctx.send("Vote kick will now mention *{}.*".format(
                DisplayName.name(check_user)))
            return
        await ctx.send("I couldn't find *{}*...".format(
            Nullify.escape_all(user_or_role)))
Beispiel #30
0
    async def offset(self, ctx, *, member=None):
        """See a member's UTC offset."""

        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        if member == None:
            member = ctx.message.author

        if type(member) == str:
            # Try to get a user first
            memberName = member
            member = DisplayName.memberForName(memberName, ctx.message.guild)
            if not member:
                msg = 'Couldn\'t find user *{}*.'.format(
                    Nullify.escape_all(memberName))
                await ctx.channel.send(msg)
                return

        # We got one
        offset = self.settings.getGlobalUserStat(member, "UTCOffset")
        if offset == None:
            msg = '*{}* hasn\'t set their offset yet - they can do so with the `{}setoffset [+-offset]` command.'.format(
                DisplayName.name(member), ctx.prefix)
            await ctx.channel.send(msg)
            return

        # Split time string by : and get hour/minute values
        try:
            hours, minutes = map(int, offset.split(':'))
        except Exception:
            try:
                hours = int(offset)
                minutes = 0
            except Exception:
                await ctx.channel.send('Offset has to be in +-H:M!')
                return

        msg = 'UTC'
        # Apply offset
        if hours > 0:
            # Apply positive offset
            msg += '+{}'.format(offset)
        elif hours < 0:
            # Apply negative offset
            msg += '{}'.format(offset)

        msg = '*{}\'s* offset is *{}*'.format(DisplayName.name(member), msg)
        await ctx.channel.send(msg)