Skip to content

Commit

Permalink
Merge pull request cbrxyz#312 from Nydauron/305_command_channel_black…
Browse files Browse the repository at this point in the history
…list

Issue cbrxyz#305: Added channel whitelist/blacklist for commands.
  • Loading branch information
cbrxyz authored Dec 29, 2020
2 parents 68d2962 + 9103488 commit 9c596e7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
39 changes: 39 additions & 0 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from commands import getList, getQuickList, getHelp
from lists import getStateList
import xkcd as xkcd_module # not to interfere with xkcd method
from commanderrors import CommandNotAllowedInChannel

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
Expand Down Expand Up @@ -172,6 +173,30 @@ async def isAdmin(ctx):
aRole = discord.utils.get(member.guild.roles, name=ROLE_AD)
if aRole in member.roles or member.id == 715048392408956950: return True

def notBlacklistedChannel(blacklist):
"""Given a string array blacklist, check if command was not invoked in specified blacklist channels."""
async def predicate(ctx):
channel = ctx.message.channel
server = bot.get_guild(SERVER_ID)
for c in blacklist:
if channel == discord.utils.get(server.text_channels, name=c):
raise CommandNotAllowedInChannel(channel, "Command was invoked in a blacklisted channel.")
return True

return commands.check(predicate)

def isWhitelistedChannel(whitelist):
"""Given a string array whitelist, check if command was invoked in specified whitelisted channels."""
async def predicate(ctx):
channel = ctx.message.channel
server = bot.get_guild(SERVER_ID)
for c in whitelist:
if channel == discord.utils.get(server.text_channels, name=c):
return True
raise CommandNotAllowedInChannel(channel, "Command was invoked in a non-whitelisted channel.")

return commands.check(predicate)

##############
# CONSTANTS
##############
Expand Down Expand Up @@ -736,6 +761,7 @@ async def rand(ctx, a=1, b=10):
await ctx.send(f"Random number between `{a}` and `{b}`: `{r}`")

@bot.command()
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def magic8ball(ctx):
msg = await ctx.send("Swishing the magic 8 ball...")
await ctx.channel.trigger_typing()
Expand Down Expand Up @@ -766,6 +792,7 @@ async def magic8ball(ctx):
await ctx.send(f"**{response}**")

@bot.command()
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def xkcd(ctx, num = None):
max_num = await xkcd_module.get_max()
if num == None:
Expand Down Expand Up @@ -1363,6 +1390,7 @@ async def pingPM(userID, pinger, pingExp, channel, content, jumpUrl):
await userToSend.send(embed=embed)

@bot.command(aliases=["doggobomb"])
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def dogbomb(ctx, member:str=False):
"""Dog bombs someone!"""
if member == False:
Expand All @@ -1372,6 +1400,7 @@ async def dogbomb(ctx, member:str=False):
await ctx.send(f"{member}, <@{ctx.message.author.id}> dog bombed you!!")

@bot.command()
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def shibabomb(ctx, member:str=False):
"""Shiba bombs a user!"""
if member == False:
Expand Down Expand Up @@ -1630,6 +1659,7 @@ async def help(ctx, command:str=None):
await ctx.send(embed=hlp)

@bot.command(aliases=["feedbear"])
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def fish(ctx):
"""Gives a fish to bear."""
global fishNow
Expand All @@ -1651,11 +1681,13 @@ async def fish(ctx):
return await ctx.send(f":sob:\n:sob:\n:sob:\nAww, bear's fish was accidentally square root'ed. Bear now has {fishNow} fish. \n:sob:\n:sob:\n:sob:")

@bot.command()
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def nofish(ctx):
"""DEPRECATED - Removes all of bear's fish."""
await ctx.send("`!nofish` no longer exists! Please use `!stealfish` instead.")

@bot.command(aliases=["badbear"])
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def stealfish(ctx):
global fishNow
member = ctx.message.author
Expand Down Expand Up @@ -1684,6 +1716,7 @@ async def stealfish(ctx):
return await ctx.send("You are banned from using `!stealfish` until the next version of Pi-Bot is released.")

@bot.command(aliases=["slap", "trouts", "slaps", "troutslaps"])
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def trout(ctx, member:str=False):
if await sanitizeMention(member) == False:
return await ctx.send("Woah... looks like you're trying to be a little sneaky with what you're telling me to do. Not so fast!")
Expand All @@ -1694,6 +1727,7 @@ async def trout(ctx, member:str=False):
await ctx.send("http://gph.is/1URFXN9")

@bot.command(aliases=["givecookie"])
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def cookie(ctx, member:str=False):
if await sanitizeMention(member) == False:
return await ctx.send("Woah... looks like you're trying to be a little sneaky with what you're telling me to do. You can't ping roles or everyone.")
Expand All @@ -1704,11 +1738,13 @@ async def cookie(ctx, member:str=False):
await ctx.send("http://gph.is/1UOaITh")

@bot.command()
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def treat(ctx):
await ctx.send("You give bernard one treat!")
await ctx.send("http://gph.is/11nJAH5")

@bot.command(aliases=["givehershey", "hershey"])
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def hersheybar(ctx, member:str=False):
if await sanitizeMention(member) == False:
return await ctx.send("Woah... looks like you're trying to be a little sneaky with what you're telling me to do. You can't ping roles or everyone.")
Expand All @@ -1719,6 +1755,7 @@ async def hersheybar(ctx, member:str=False):
await ctx.send("http://gph.is/2rt64CX")

@bot.command(aliases=["giveicecream"])
@notBlacklistedChannel(blacklist=[CHANNEL_WELCOME])
async def icecream(ctx, member:str=False):
if await sanitizeMention(member) == False:
return await ctx.send("Woah... looks like you're trying to be a little sneaky with what you're telling me to do. You can't ping roles or everyone.")
Expand Down Expand Up @@ -2632,6 +2669,8 @@ async def on_command_error(ctx, error):
return await ctx.send("Uh... this channel can only be run in a NSFW channel... sorry to disappoint.")

# Command errors
if isinstance(error, CommandNotAllowedInChannel):
return await ctx.send(f"You are not allowed to use this command in {error.channel.mention}.")
if isinstance(error, discord.ext.commands.ConversionError):
return await ctx.send("Oops, there was a bot error here, sorry about that.")
if isinstance(error, discord.ext.commands.UserInputError):
Expand Down
5 changes: 5 additions & 0 deletions commanderrors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import discord.ext.commands as commands
class CommandNotAllowedInChannel(commands.CommandError):
def __init__(self, channel, *args, **kwargs):
self.channel = channel
super().__init__(*args, **kwargs)

0 comments on commit 9c596e7

Please sign in to comment.