How to make a NSFW command in discord.py?

℡╲_俬逩灬. 提交于 2021-01-07 02:27:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!