discord bot deletes every message, not just ones that don't contain a specific word, which is "egg" - discord.py

import discord
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
#client.event
async def on_message(message):
content = message.content.lower().strip():
if "egg" not in content:
await message.delete()
I tried:
async def on_message(message):
if "egg" in message.content.lower():
return
await message.delete()`
what am I doing wrong?
first time making a discord bot. I did search a LOT, most questions are only about how TO delete messages containing specific words, not the other way around.
appreciate any help, thanks.

Related

Can't figure out how to use discord.py ctx

I have tried to convert my discord bot's commands to using ctx instead of interactions but the code I have tried below does not work.
#bot.command(description="Says test")
async def test(ctx):
await ctx.send("Test")
My issue is that the command never loads.
Updated code but still broken
import discord
from discord import ui
from discord.ext import commands
bot = commands.Bot(command_prefix="/", intents = discord.Intents.all())
# Run code
#bot.event
async def on_ready():
print('The bot has sucuessfully logged in: {0.user}'.format(bot))
await bot.change_presence(activity=discord.Activity(type = discord.ActivityType.listening, name = f"Chilling Music - {len(bot.guilds)}"))
# Commands
#bot.command(description="Says Hello")
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}!")
#bot.command(description="Plays music")
async def play(ctx, song_name : str):
await ctx.author.voice.channel.connect()
await ctx.send(f"Now playing: {song_name}")
#bot.command(description="The amount of servers the bot is in")
async def servercount(ctx):
await ctx.send(f"Chill Bot is in {len(bot.guilds)} discord servers!")
#bot.command(description="The bots ping")
async def ping(ctx):
await ctx.send(f"🏓Pong\nChill Bot's ping is\n{round(bot.latency * 1000)} ms")
#bot.command(description="Announcement command")
async def announce(ctx, message : str):
await ctx.send(message)
#bot.command(description="Support Invite")
async def support(ctx):
await ctx.send(f"{ctx.author.mention} Please join our server for support! [invite]", ephemeral=True)
#bot.command(description = "Syncs up commands")
async def sync(ctx):
await ctx.send("Synced commands!", ephemeral=True)
bot.run('')
Your commands don't work because you incorrectly created an on_message event handler.
By overwriting it and not calling Bot.process_commands(), the library no longer tries to parse incoming messages into commands.
The docs also show this in the Frequently Asked Questions (https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working)
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a bot.process_commands(message) line at the end of your on_message.
Also, don't auto-sync (you're doing it in on_ready). Make a message command and call it manually whenever you want to sync.

Message content intent is not enabled. Prefix commands may not work as expected unless you enable this

I don't know why I'm getting this error. I have all the intents enabled as seen in the image below.
This is my first project** in discord.py, and I don't really understand some things.
Here is the code I have (hoping this is relavant):
import nextcord
from nextcord import Interaction
from nextcord.ext import commands
intents = nextcord.Intents.default()
intents.members = True
command_prefix = '!'
client = commands.Bot(command_prefix, intents = intents)
#client.event
async def on_ready():
print('logged in as {0.user}'.format(client))
print(command_prefix)
testserver = 988598060538015815
#nextcord.slash_command(name = "hello", description = "Bot Says Hello", guild_ids = [testserver])
async def hellocommand(interaction: Interaction):
await interaction.response.send_message("yoooo")
client.run("my token")
change intents = nextcord.Intents.default() to intents = nextcord.Intents.all()

Get a message sent to only one guild when my bot is added to a server

I am new to coding so sorry if this is easy to do. But what I am wanting to have my bot do is send a message to my private guild when it is added or removed from another guild. Also if it could say the name of said guild that would help as well.
#client.event
async def on_guild_join(guild):
chn = client.get_channel(YOUR_PRIVATE_GUILD_CHANNEL_ID)
embed = discord.Embed(title=f"Bot Invited",description=f"""
**User Name:** {bot_entry[0].user.name}
**User ID:** {bot_entry[0].user.id}
**Server Name:** {guild.name}
**Server ID:** {guild.id}
**Members Count:** {len(guild.members)}
""", colour=0x2dc6f9)
embed.set_footer(icon_url=guild.icon_url, text=guild.name)
embed.set_author(name=f"{bot_entry[0].user.name}#{bot_entry[0].user.discriminator}", icon_url=bot_entry[0].user.avatar_url)
embed.timestamp = datetime.datetime.utcnow()
server_invite = await guild.text_channels[0].create_invite(max_age = 0, max_uses = 0)
await chn.send(f"{server_invite}", embed=embed)
Something like this?
#client.event
async def on_guild_join(guild):
await client.get_channel(idchannel).send(f"{client.name} has joined")

auto mute a member if they say a specific word discord py rewrite

import discord
import re
from itertools import cycle
class Status(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, ctx):
if ctx.author.id == self.client.user.id:
return
if re.search("\.\.\.", ctx.content):
await ctx.send("you're... gonna get... muted... if you.. talk... like.. this...")
user = ctx.message.author
# print(str(user))
# print(str(message.content))
muted_role = discord.utils.get(ctx.author.guild.roles, name="Muted")
await self.client.add_roles(ctx.author, muted_role)
What I want is to temporarily mute a user if they use ellipses in a message they send. ctx.send doesn't work, the bot does not send a message to the channel. It says that self.client.add_roles doesn't exist.
Muted is a role that I have created that does not have any send message permissions.
Any idea why? Some help would be hugely appreciated. I'm using
AttributeError: 'Message' object has no attribute 'send' this is the error I get
[EDIT]
#commands.Cog.listener()
# #commands.command()
async def on_message(self, message):
if message.author.id == self.client.user.id:
return
if re.search("\.\.\.", message.content):
await message.channel.send("you're... gonna get... muted... if you.. talk... like.. this...")
user = message.author
muted_role = discord.utils.get(message.guild.roles, name="Muted")
await user.add_roles(muted_role, reason="you know what you did", atomic=True)
I took a look at the documentation and did this, it works, thank you for the support :)
There were many mistakes, please have a look at the documentation.
I have correct them for you -
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == self.client.user.id:
return
else:
await message.channel.send("you're... gonna get... muted... if you.. talk... like.. this...")
user = message.author
print(str(user))
print(str(message.content))
muted_role = discord.utils.get(message.guild.roles, name="Muted")
await self.user.add_roles(muted_role)
Let me know if you do still get any errors.
Last edit-
I tried this command for myself outside a cog, and it works perfectly fine :)
#client.event
async def on_message(message):
if message.author.id == client.user.id:
return
elif "test" in message.content:
await message.channel.send("you're... gonna get... muted... if you.. talk... like.. this...")
user = message.author
print(str(user))
print(str(message.content))
muted_role = discord.utils.get(message.guild.roles, name="Muted")
await user.add_roles(muted_role)
else:
return
await client.process_commands(message)

Trying to make a list case insensitive in discord.py (python)

I am trying to make a bad word filter for a bot that I am making for my friend's server, but, the list is case sensitive. How do I fix this?
#client.event
async def on_message(message):
author = message.author
content = message.content
channel = message.channel
log = client.get_channel(log channel)
bad_words=["bad","word","yellow"]
if any(bad_word in content for bad_word in bad_words):
embed = discord.Embed(title="Bad word detected!", color=discord.Color.red())
embed.add_field(name=f"{author.display_name}, you have said a forbidden word!", value="You
have been sent to Jail!")
embed2 = discord.Embed(title=f"Bad word sent by {author} in #{channel}.",
color=discord.Color.red())
embed2.add_field(name="They said:", value=f"{author.display_name}: {content}")
await message.delete()
await author.add_roles(discord.utils.get(author.guild.roles, name="jail"))
await channel.send(embed=embed)
await log.send(embed=embed2)
await client.process_commands(message)
Make the content lowercase before you check with it
content = message.content.lower()

Resources