问题
I am making a discord bot and I want a NSFW command in, so I used a command that's puts a random image of a NSFW subreddit, but I need help with the detection of a NSFW channel, so this command can't be used in channels that are not nsfw, and also send a message that says "You need to use this command in a nsfw channel!" Here's my command, but there's a error in the part of "else:"
async def nsfw(ctx):
if ctx.channel.is_nsfw():
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
else:
await ctx.send("You need to use this command in a nsfw channel!"
回答1:
You can add a check to see if the channel the command is being used in is NSFW
@commands.command()
@commands.is_nsfw()
async def your_nfsw_command(self, ctx):
#your-command
As for throwing an error if the command is used in a non-nsfw channel, you can use a error handler such as
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.errors.NSFWChannelRequired):
msg.title = "NSFW Command"
msg.description = error.args[0]
return await ctx.send(embed=msg)
Alternatively you may also add an error-handler by doing
commandname.error
and using the same logic.
Possible corrections to code may involve:
if ctx.channel.is_nsfw():
#logic
async with aiohttp.ClientSession() as cs:
#this line seems to be not indented correctly
else:
#logic
Your error is likely thrown by an else
without an if
.
来源:https://stackoverflow.com/questions/63543252/how-to-make-a-nsfw-command-in-discord-py