Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #296: PM check for !ping #314

Open
wants to merge 40 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
1aeed01
Added @mention parameter to unban command fixes cbrxyz/pi-bot#168
Nydauron Oct 3, 2020
9be5ec1
Changed commands to use has_any_role() and isStaff uses Staff role fi…
Nydauron Dec 18, 2020
4863519
Added command help documentation fixes cbrxyz/pi-bot#303
Nydauron Dec 18, 2020
295c658
Created channel blacklist check function fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
02f3728
Restructuring check function to pass ctx and blacklist array
Nydauron Dec 18, 2020
9a366a4
Fixed variables fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
4d106d8
Fixed how blacklist function is invoked to commands fixes cbrxyz/pi-b…
Nydauron Dec 18, 2020
0bc0ba0
Added custom command exception for channel blacklist checks fixes cbr…
Nydauron Dec 18, 2020
43e86f6
Implementation raises BlacklistException fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
5eb1f77
Renamed to better represent as command errors
Nydauron Dec 18, 2020
3247db6
Changed exception to CommandNotAllowedInChannel fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
f0b2b00
Added whitelist check function
Nydauron Dec 18, 2020
52f921f
Slight renaming and more consise documentation fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
ec4c367
Added blacklist channel check to fun commands fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
e9022fb
Fixed minor syntax error fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
72df2de
Added message to CommandNotAllowedInChannel fixes cbrxyz/pi-bot#305
Nydauron Dec 18, 2020
54cf57a
Created new command error NoDMsAllowed
Nydauron Dec 19, 2020
578b590
Implemented checkDM function
Nydauron Dec 19, 2020
2981667
Added checkDM to ping command
Nydauron Dec 19, 2020
56f327c
Added handling for NoDMsAllowed command error
Nydauron Dec 19, 2020
65c97c4
Using const role values and added perms for !slow fixes cbrxyz/pi-bot…
Nydauron Dec 19, 2020
1c016f2
Removing useless line
cbrxyz Dec 26, 2020
cebd7f5
Delete 2020 New Jersey State TournamentDivC.svg
cbrxyz Dec 26, 2020
379c0ed
Delete 2019 California (South) State TournamentDivC.svg
cbrxyz Dec 26, 2020
a476844
Delete graphpage.svg
cbrxyz Dec 26, 2020
9757e2e
Delete graph1.svg
cbrxyz Dec 26, 2020
73977f9
Merge branch 'master' into 168_unban
cbrxyz Dec 26, 2020
b62bcf8
Merge pull request #198 from Nydauron/168_unban
cbrxyz Dec 26, 2020
8344ab2
Removing unnecessary commented lines
cbrxyz Dec 26, 2020
fefe90f
Merge branch 'master' into 303_rand_command_info
cbrxyz Dec 26, 2020
4f7dc80
Merge pull request #311 from Nydauron/303_rand_command_info
cbrxyz Dec 26, 2020
bcfb165
Restored command staff check to use isStaff function fixes cbrxyz/pi-…
Nydauron Dec 28, 2020
68d2962
Merge pull request #310 from Nydauron/306_staff_role_support
cbrxyz Dec 29, 2020
9103488
Removed commented print statement
cbrxyz Dec 29, 2020
9c596e7
Merge pull request #312 from Nydauron/305_command_channel_blacklist
cbrxyz Dec 29, 2020
96da460
Created new command error NoDMsAllowed
Nydauron Dec 19, 2020
86870c5
Implemented checkDM function
Nydauron Dec 19, 2020
8124a3a
Added checkDM to ping command
Nydauron Dec 19, 2020
39e195a
Added handling for NoDMsAllowed command error
Nydauron Dec 19, 2020
329e6a2
Merge conflict fix
Nydauron Dec 30, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 72 additions & 17 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
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
from commanderrors import NoDMsAllowed

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
Expand All @@ -51,6 +53,7 @@
ROLE_GM = "Global Moderator"
ROLE_AD = "Administrator"
ROLE_VIP = "VIP"
ROLE_STAFF = "Staff"
ROLE_BT = "Bots"
ROLE_LH = "Launch Helper"
ROLE_AT = "All Tournaments"
Expand Down Expand Up @@ -142,11 +145,9 @@ async def isBear(ctx):
async def isStaff(ctx):
"""Checks to see if the user is a staff member."""
member = ctx.message.author
wmRole = discord.utils.get(member.guild.roles, name=ROLE_WM)
gmRole = discord.utils.get(member.guild.roles, name=ROLE_GM)
aRole = discord.utils.get(member.guild.roles, name=ROLE_AD)
vipRole = discord.utils.get(member.guild.roles, name=ROLE_VIP)
if wmRole in member.roles or gmRole in member.roles or aRole in member.roles or vipRole in member.roles: return True
staffRole = discord.utils.get(member.guild.roles, name=ROLE_STAFF)
return vipRole in member.roles or staffRole in member.roles

async def isLauncher(ctx):
"""Checks to see if the user is a launch helper."""
Expand All @@ -173,6 +174,44 @@ 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)

def checkDM():
"""Checks if the user has DM permissions. If the send responds 403, then they have DMs disabled."""
async def predicate(ctx):
user = ctx.message.author
try:
await user.send("")
except discord.Forbidden:
raise NoDMsAllowed(user, f"{user} has DMs set to off.")
except discord.HTTPException:
pass
return True

return commands.check(predicate)

##############
# CONSTANTS
##############
Expand Down Expand Up @@ -737,6 +776,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 @@ -767,6 +807,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 @@ -800,6 +841,7 @@ async def coach(ctx):
await ctx.send("Successfully gave you the Coach role, and sent a verification message to staff.")

@bot.command(aliases=["slow", "sm"])
@commands.check(isStaff)
async def slowmode(ctx, arg:int=None):
if arg == None:
if ctx.channel.slowmode_delay == 0:
Expand Down Expand Up @@ -1043,16 +1085,16 @@ async def info(ctx):
emoji_percentage = round(emoji_count/emoji_limit * 100, 3)
channel_percentage = round(channel_count/500 * 100, 3)
role_percenatege = round(role_count/250 * 100, 3)

staff_member = await isStaff(ctx)
fields = [
{
"name": "Basic Information",
"value": (
f"**Creation Date:** {creation_date}\n" +
f"**Creation Date:** {creation_date}\n" +
f"**ID:** {iden}\n" +
f"**Animated Icon:** {animated_icon}\n" +
f"**Banner URL:** {banner}\n" +
f"**Banner URL:** {banner}\n" +
f"**Splash URL:** {splash}\n" +
f"**Discovery Splash URL:** {discovery_splash_url}"
),
Expand All @@ -1074,19 +1116,19 @@ async def info(ctx):
"value": (
f"**Owner:** {owner}\n" +
f"**MFA Level:** {mfa_level}\n" +
f"**Verification Level:** {verification_level}\n" +
f"**Verification Level:** {verification_level}\n" +
f"**Content Filter:** {content_filter}\n" +
f"**Default Notifications:** {default_notifs}\n" +
f"**Features:** {features}\n" +
f"**Bitrate Limit:** {bitrate_limit}\n" +
f"**Features:** {features}\n" +
f"**Bitrate Limit:** {bitrate_limit}\n" +
f"**Filesize Limit:** {filesize_limit} MB"
),
"inline": False
},
{
"name": "Channels",
"value": (
f"**Public Updates Channel:** {public_updates_channel}\n" +
f"**Public Updates Channel:** {public_updates_channel}\n" +
f"**System Channel:** {system_channel}\n" +
f"**Rules Channel:** {rules_channel}\n" +
f"**Text Channel Count:** {text_channel_count}\n" +
Expand Down Expand Up @@ -1226,6 +1268,7 @@ async def resultstemplate(ctx, url):
await ctx.send(file=file)

@bot.command()
@checkDM()
async def ping(ctx, command=None, *args):
"""Controls Pi-Bot's ping interface."""
if command is None:
Expand Down Expand Up @@ -1363,6 +1406,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 +1416,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 +1675,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 +1697,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 +1732,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 +1743,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 +1754,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 +1771,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 @@ -2010,13 +2063,11 @@ async def ban(ctx, member:discord.User=None, reason=None, *args):

@bot.command()
@commands.check(isStaff)
async def unban(ctx, id:int=0):
async def unban(ctx, member:discord.User=None):
"""Unbans a user."""
if id == 0:
await ctx.channel.send("Please give a user ID.")
if member == None:
await ctx.channel.send("Please give either a user ID or mention a user.")
return
invite = await ctx.channel.create_invite(max_age = 86400)
member = await bot.fetch_user(id)
await ctx.guild.unban(member)
await ctx.channel.send(f"Inverse ban hammer applied, user unbanned. Please remember that I cannot force them to re-join the server, they must join themselves.")

Expand Down Expand Up @@ -2317,7 +2368,7 @@ async def on_message(message):
await autoReport("User was auto-muted (caps)", "red", f"A user ({str(message.author)}) was auto muted in {message.channel.mention} because of repeated caps.")
elif sum(1 for m in RECENT_MESSAGES if m['author'] == message.author.id and m['caps']) > 3 and caps:
await message.channel.send(f"{message.author.mention}, please watch the caps, or else I will lay down the mute hammer!")

# Do not treat messages with only exclamations as command
if message.content.count(BOT_PREFIX) != len(message.content):
await bot.process_commands(message)
Expand Down Expand Up @@ -2616,6 +2667,8 @@ async def on_command_error(ctx, error):
return await ctx.send("Sorry, I'm having trouble reading one of the arguments you just used. Try again!")

# Check failure errors
if isinstance(error, NoDMsAllowed):
return await ctx.send("Pings require direct messages to be sent to you. You need to turn on \"Allow direct messages from server members.\"")
if isinstance(error, discord.ext.commands.CheckAnyFailure):
return await ctx.send("It looks like you aren't able to run this command, sorry.")
if isinstance(error, discord.ext.commands.PrivateMessageOnly):
Expand All @@ -2634,6 +2687,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
10 changes: 10 additions & 0 deletions commanderrors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import discord.ext.commands as commands
class CommandNotAllowedInChannel(commands.CommandError):
def __init__(self, channel, *args, **kwargs):
self.channel = channel
super().__init__(*args, **kwargs)

class NoDMsAllowed(commands.CommandError):
def __init__(self, user, *args, **kwargs):
self.channel = channel
super().__init__(*args, **kwargs)
29 changes: 29 additions & 0 deletions commandinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -1379,5 +1379,34 @@
"Member"
],
"inQuickList": False
},
{
"name": "rand",
"description": "Generates a random number",
"aliases": ["random"],
"parameters": [
{
"name": "min",
"description": "the lower bound (inclusive)"
},
{
"name": "max",
"description": "the upper bound (inclusive)"
}
],
"usage": [
{
"cmd": "!rand",
"result": "Generates a random number in the interval [1, 10]"
},
{
"cmd": "!rand 50 100",
"result": "Generates a random number in the interval [50, 100]"
}
],
"access":[
"Member"
],
"inQuickList": False
}
]
Empty file added resultstemplate.txt
Empty file.