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!"
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.
probably you are missing paranthesis in else statement
Code
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!")
This is my solution, I used to get the same thing before, but researching I found the solution, I hope it helps you.
#bot.command()
#commands.is_nsfw()
async def nsfw(ctx):
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)
#nsfw.error(ctx, error):
if isinstance(error, NSFWChannelRequired):
await ctx.send(f"Hey! {ctx.author.mention}, sorry but i can't submit nsfw content without nsfw category.")
Related
The command is executed, although the terminal says the command doesn't exist.
Not sure what's up as this is my first discord bot, I know a little bit of python, so I am sorry for taking up your guys's time, really.
Thank you for the help though!
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix= ':')
game = discord.Game("with the API")
#list of banned words
filtered_words = ['bad words']
#bot.event
async def on_ready():
print("Hello I am online and ready!")
bot.run('token')
#Group message clearing
#bot.command(aliases=['c'])
#commands.has_permissions(manage_messages = True)
async def clear(ctx, amount=1):
await ctx.channel.purge(Limit = amount)
await ctx.reply(f'Deleted {clear} messages')
#auto mod
#bot.event
async def on_message(msg):
for word in filtered_words:
if word in msg.context:
await msg.delete()
await bot.process_commands(msg)
#bot.event
async def on_disconnect():
print("I seem to be getting disconnected, one minute!")
#bot.event
async def on_member_join(memeber):
print(f'Weclome {memeber} to the server, please enjoy your stay!')
#bot.event
async def on_message_delete(msg):
msg.send(" <:raysQ:835686467844964395> ")
The bot.run part should be at the end of the file. It's.the entry point to the loop.
Also please regenerate your token before someone else can use it.
i need to use my discord command in specific channel , I'm using #client.command()
I mean if i used my command in another channel will be not working
#client.command()
async def w(ctx):
channel = client.get_channel(775491463940669480)
await ctx.send("hello) ```
You can check if ctx.channel is equal to your specific channel.
#client.command()
async def w(ctx):
if ctx.channel.id == 775491463940669480:
await ctx.send("hello)
There is even an easier way to do it without getting the channel. And without having to indent the whole code.
#client.command()
async def w(ctx):
# exit command if not the desired channel.
if ctx.channel.id is not 775491463940669480:
return
#code here
await ctx.send("hello")
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print("bot is Online")
-
#client.event
async def on_message(message):
cmdChannel = client.get_channel(776179059355942943)
if message.content.lower().startswith('!w'):
if message.channel.id == cmdChannel.id:
#command invoked in command channel - execute it
await client.process_commands(message)
else:
#command attempted in non command channel - redirect user
await message.channel.send('Write this command in {}'.format(cmdChannel.mention))
#client.command()
async def w(ctx, amount):
await ctx.send(f"done {amount}")
async def is_channel(ctx):
return ctx.channel.id = 775491463940669480
#client.command()
#client.check(is_channel)
async def w(ctx):
await ctx.send("hello)
Making the check call the function is_channel makes the code simpler and you can resuse it multiple times.
I have seen this command
#bot.command()
async def disappear(ctx):
msg = await ctx.send("Hey!")
await msg.delete(delay=1)
However, I'm trying to delete the "msg" in some other function. To be precise, this is my code
#bot.command()
async def disappear(ctx):
msg = await ctx.send("Hey!")
await msg.delete(delay=1)
#bot.command()
async def somethingelse(ctx):
await msg.delete(delay=1)
which gives me an error
NameError: name 'msg' is not defined
So i wanted to know if there is any method where it is possible to delete the bot's previous message by the bot itself.
You could try this:
prev_msg = None
#bot.command()
async def deleteprevmsg(ctx):
global prev_msg
try:
await prev_msg.delete(delay = 1)
except:
prev_msg = await ctx.send("No previous message found")
And put prev_msg = before every await ctx.send(). Remember to global prev_msg in every function that uses it.
If you don't want to use globals, you can get last message sent by your bot in that channel then delete it.
#client.command()
async def somethingelse(ctx):
channel = client.get_channel(123456789123456) # ID of channel
msg = await channel.history().get(author__id=123456789123456) # ID of bot
await msg.delete(delay=1)
print(f"Deleted message: {msg.id}")
channel.history()
I would like to have my bot edit a message if it detects a keyword, i'm not sure how to edit the message though.
I've looked through the documentation but can't seem to figure it out. I'm using discord.py with python 3.6.
This is the code:
#bot.event
async def on_message(message):
if 'test' in message.content:
await edit(message, "testtest")
This is the error:
File "testthing.py", line 67, in on_message
await edit(message, "test")
NameError: name 'edit' is not defined
I would like the bot to edit a message to "testtest" if the message contains the word test, but i just get an error.
You can use the Message.edit coroutine. The arguments must be passed as keyword arguments content, embed, or delete_after. You may only edit messages that you have sent.
await message.edit(content="newcontent")
Here's a solution that worked for me.
#client.command()
async def test(ctx):
message = await ctx.send("hello")
await asyncio.sleep(1)
await message.edit(content="newcontent")
Did you do this:
from discord import edit
or this:
from discord import *
before using message.edit function?
If you did it, maybe the problem is with your discord.py version.
Try this:
print(discord.__version__)
If you are wanting to update responses in discord.py you have to use:
#tree.command(name = 'foobar', description = 'Send the word foo and update it to say bar')
async def self(interaction: discord.Interaction):
await interaction.response.send_message(f'foo', ephemeral = True)
time.sleep(1)
await interaction.edit_original_response(content=f'bar')
Assign the original message to a variable. Reference the variable with .edit(content='content').
(You need "content=" in there).
#bot.command()
async def test(ctx):
msg = await ctx.send('test')
await msg.edit(content='this message has been edited')
#bot.event
async def on_message(message):
if message.content == 'test':
messages=await message.channel.send("CONTENT")
await asyncio.sleep(INT)
await messages.edit(content="NEW CONTENT")
Please try to add def to your code like this:
#bot.event
async def on_message(message):
if 'test' in message.content:
await edit(message, "edited !")
This is what I did:
#bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Hello World!')
await message.edit(content='testtest')
I don't know if this will work for you, but try and see.
Here is the sendMessage function:
async def sendMessage(color, title, value, should_delete=True, channel=""):
embed = discord.Embed(color=color)
embed.add_field(name=title, value=value, inline=False)
if channel == "":
msg = await client.send_message(message_obj.channel, embed=embed)
else:
msg = await client.send_message(client.get_channel(channel), embed=embed)
if should_delete:
await delete_msg(msg)
The bot can mention anyone but everyone and here. Despite having mention everyone permission.
sendMessage(OK_COLOR_HASH, "title", "Hello #everyone")
Edit: When I converted the message type to the normal one instead of embed one, it worked.
You can try to sending a mention to everyone through the default_role attribute
#bot.command(pass_context=True)
async def evy(msg):
await bot.say(msg.message.server.default_role)
You can try this block code. roles return a list all guild's roles, but first role always a default guild role (default_role) and that's why you must use slicing function.
#bot.command()
async def test(ctx):
await ctx.send(ctx.message.guild.roles[0])
Or you can do something like this.
#bot.command()
async def test(ctx):
await ctx.send(ctx.message.guild.default_role)