Deleting messages that start with certain prefix [discord.py] - python

I want my bot to delete all messages that are not starting with the prefix .. I wrote this code so far in discord.py but it keeps deleting all messages.
#Client.event
async def on_message(message):
if message.author.has_role("Bot"):
return
elif message.content.startswith('.'):
return
else:
await message.delete()
Thanks in advance

Try doing it like this:
#client.event
async def on_message(ctx):
if ctx.content.startswith('.'):
await client.process_commands(ctx)
return
for role in ctx.author.roles:
if role.name == 'Bot':
return
await ctx.delete()

I would do it like this:
#Client.event
async def on_message(message):
if message.content.startswith(".") == False:
message.channel.purge(limit=1)
else:
pass

Related

Delete a message from a specific channel if it contains a specific word

#bot.event
async def opt1(msg):
await msg.channel.purge(limit=100, check= lambda x: ('++' in x.content.strip().lower()) and x.channel.id == 954573387387265024)
#bot.event
async def on_message(message):
if '++' in message.content and message.channel.id == 954573376209420328:
await opt1(message)
What I want to do is if a user types ++ in a channel 954573376209420328 then all the messages that contain ++ in a channel 954573387387265024 will be deleted by a bot.
You almost got it. You just have to delete #bot.event from opt1 function.
async def opt1(msg):
await msg.channel.purge(limit=100, check= lambda x: ('++' in x.content.strip().lower()) and x.channel.id == 954573387387265024)
#bot.event
async def on_message(message):
if '++' in message.content and message.channel.id == 954573376209420328:
await opt1(message)
async def on_message(message):
purgeChannel = bot.get_channel(954573387387265024)
if '++' in message.content and message.channel.id == 954573376209420328:
await purgeChannel.purge(limit=100, check = lambda x: ('++' in x.content.strip().lower() and x.author.id == message.author.id))
Okay I figured out it by myself, it was much simpler than I thought

How to code yes/no function for discord bot

I wanted to code a function in which the bot sends the message 'happiness reloaded' when the user answers Y, or else it sends the message good night if the user answers N. I have tried to run this code, which replies to 'hi' but after that, when I type in Y or N, the bot cannot reply. My code example:
#client.event
async def on_message(message):
if message.author == client.user:
return
# if message.content.startswith('$inspire'):
# quote = get_quote()
# await message.channel.send(quote)
if message.content.startswith('hi'): # Delete this after testing
await message.channel.send('Congratulations! Your Disgotchi is hatched! (Play around? : Y/N)')
if message.content.includes('y', 'Y'):
await message.channel.send('Happiness reloaded! ( ^Θ^)❤️')
elif message.content.includes('n', 'N'):
await message.channel.send('I will go to bed, good night!')
should do what you want
all you have to do is store the ids outside the callback, expecting another message in same callback is useles as message newer changes
import discord
from discord.ext.commands import Bot
bot = Bot(command_prefix='$')
y_users = set() # set is best for this
#bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
#bot.event
async def on_message(message):
if message.content == 'hi':
await message.channel.send('Congratulations! Your Disgotchi is hatched! (Play around? : Y/N)')
y_users.add(message.author.id) # saving the id
# checking if id is in set which means user sent hello previously
elif (message.content.startswith('y', 'Y') and message.author.id in y_users):
await message.channel.send('Happiness reloaded! ( ^Θ^)❤️')
y_users.remove(message.author.id)
elif (message.content.startswith('n', 'N') and message.author.id in y_users):
await message.channel.send('I will go to bed, good night!')
y_users.remove(message.author.id)
bot.run("token")
please mark it as correct solution if it does what you want

Getting message content with Discord.py

I would like to have a command like $status idle and it would do the follow
variblething = 'I am idle'
activity = discord.Game(name=variblething)
await client.change_presence(status=discord.Status.idle, activity=activity)
then they can do $message write what you want the status to be
then it would change what the activity message is. I hope this all makes sense. My current code is the following
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$helloThere'):
await message.channel.send('General Kenobi')
Firstly I would highly advise that you use prefixes and the command decorators/functions.
This means that your on_message() function won't be a mile long. To set your bot's command prefix, you can do:
from discord.ext import commands
bot = commands.Bot(command_prefix ='$')
This will allow you to make commands like so:
#bot.command()
async def changeStatus(ctx, *, status):
if status == 'online':
new_status = discord.Status.online
elif status == 'offline':
new_status = discord.Status.offline
elif status == 'idle':
new_status = discord.Status.idle
elif status == 'dnd':
new_status = discord.Status.dnd
else:
return
await bot.change_presence(status=new_status, activity=discord.Game(f'I am {status}'))

Discord bot not recognizing commands

I'm new to the discord API and I'm having trouble figuring out why my commands are not recognized. I've read through the documentation, but I'm not exactly sure where to look. Any help would be appreciated. Don't mind the hard-coded lists. I plan on changing that in the future. For now I just want to make sure that it works.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
Client = discord.Client()
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print("Bot online!")
#client.command(pass_context=True)
async def add_roles(member, *roles):
if message.content.startswith("!role"):
role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"]
entered_role = message.content[6:].upper()
role = discord.utils.get(message.server.roles, name=entered_role)
if role is None or role.name not in role_list:
# If the role wasn't found by discord.utils.get() or is a role that we don't want to add:
await client.send_message(message.channel, "Role doesn't exist.")
return
elif role in message.author.roles:
# If they already have the role
await client.send_message(message.channel, "You already have this role.")
else:
try:
await client.add_roles(message.author, role)
await client.send_message(message.channel, "Successfully added role {0}".format(role.name))
except discord.Forbidden:
await client.send_message(message.channel, "I don't have perms to add roles.")
#client.command(pass_context=True)
async def remove_roles(member, *roles):
if message.content.startswith("!unassign"):
role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"]
roles_cleared = True
for r in role_list:
# Check every role
role = discord.utils.get(message.server.roles, name=r)
if role in message.author.roles:
# If they have the role, get rid of it
try:
await client.remove_roles(message.author, role)
except discord.Forbbiden:
await client.send_message(message.channel, "I don't have perms to remove roles.")
roles_cleared = False
break
if roles_cleared:
await client.send_message(message.channel, "Roles successfully cleared.")
client.run("mytoken")
In function you need to have ctx variable
#client.comman(pass_context = True)
async def some_command(ctx, bla_bla, and_bla_bla):
pass
i think...
tell if it was helpful for u

How to give role to user for reaction

If user add reaction :HotS_Tank: in a special message, the bot will need to give this role to user, but I do not have any idea how to do it...
That's what I have tried:
async def role_background_task():
await client.wait_until_ready()
roleChannel = discord.Object(id='411270826374070293')
roleMSG1 = client.get_message(roleChannel, id='411657109860515840')
roleMSG2 = client.get_message(roleChannel, id='411657144488689674')
while not client.is_closed:
reac1 = await client.wait_for_reaction(emoji=':HotS_Tank:411445724287598592',message=roleMSG1)
if reac1.reaction.emoji == ':HotS_Tank:411445724287598592':
await client.add_roles(reac1.user, roleHOTS_Tank)
client.loop.create_task(role_background_task())
If you check the documentation, there's an event called on_reaction_add here. You can simply use that.
#client.event
async def on_reaction_add(reaction, user):
roleChannelId = '411270826374070293'
if reaction.message.channel.id != roleChannelId:
return #So it only happens in the specified channel
if str(reaction.emoji) == "<:HotS_Tank:411445724287598592>":
await client.add_roles(user, roleHOTS_Tank)

Categories

Resources