clear all messages in certain channel on_load - python

When I'm playing with my bot I do everything in a "bottesting" channel only I have access to, I'm trying to figure out how to get the bot on load to purge or delete all the messages currently in that certain channel
I've tried to make the bot.say(!clear) its own command to clear the channel but it won't recognize its output, I currently have to manually do the clear command I have set up for others to use
#bot.event
async def on_ready():
#bot announces to me when its online and posts in bottesting channel
await bot.send_message(discord.Object(id=bottesting), 'Im Back ' + myid)
print('<',datetime.datetime.now(),'>',NaMe," Launched")
This is what my current on_ready looks like and as of now it just posts that it is online and tags me in the post and the channel as well as outputs to cmd with print.

Here's one way you could turn clear into a seperate coroutine that can be called from both places:
#bot.command(pass_context=True)
#has_permissions(administrator=True, manage_messages=True, manage_roles=True)
async def clear(ctx, amount: int=1):
await _clear(ctx.message.channel, amount) # Technically you could apply the decorators directly
# to the _clear callback, but that's a little complicated
async def _clear(channel, amount=1):
messages = []
async for message in bot.logs_from(channel, limit=amount+1):
messages.append(message)
await bot.delete_messages(messages)
#bot.event
async def on_ready():
channel = bot.get_channel("123")
await _clear(channel, 100)

Related

How to delete number of chat in discord by python

I would like to create a bot which can delete number of recently chat and history chat
import discord
import random
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
channel = message.channel.name
restricted_channels = ["command-bot"]
prefix = "-" # Replace with your prefix
# If the message starts with the prefix
if message.content.startswith(prefix):
if channel in restricted_channels:
command = message.content[len(prefix):]
if command.startswith("clear"):
await message.delete()
I have try this
if command.startswith("clear"):
await message.delete()
But it only delete the chat which have command "clear"
First off, personally, I would change the structure/ layout of your code. This is so that it is easier to read, and easier to change and add commands/ different functions to. This is the way I have my bot setup and how I have seen many other bots setup as well:
import discord
client = commands.Bot(command_prefix='your prefix', intents=discord.Intents.all()) # creates client
#client.event # used commonly for different events such as on_ready, on_command_error, etc...
async def on_ready():
print('your bot is online') # basic on_ready event and print statement so you can see when your bot has gone online
Now that we've gone through that part, let's get onto the purge/ clear command you're trying to make. I have one in my bots which generally looks something like this:
#client.command() # from our client declaration earlier on at the start
#commands.has_permissions(moderate_members=True) # for if you want only certain server members to be able to clear messages. You can delete this if you'd like
async def purge(ctx, amount=2): # ctx is context. This is declared so that it will delete messages in the channel which it is used in. The default amount if none is specified in the command is set to 2 so that it will delete the command call message and the message before it
await ctx.channel.purge(limit=amount) # ctx.channel.purge is used to clear/ delete the amount of messages the user requests to be cleared/ deleted within a specific channel
Hope this helps! If you have any questions or issues just let me know and I'll help the best I can

Discord.py Translate message contents from Channel to Specific User ID's DMS

I am trying to create a bot that if it detects "$" before a message, to then take that entire messages content, and send it to a specific users dms. (user id removed for security)
async def on_message(message):
if message.content.startswith('$ '):
CONTENT = message.content
async def sendDm():
user = await client.fetch_user("530916313972080652")
await user.send(CONTENT)
However, upon doing this, the bot does not respond to any message period.
I have tried multiple send.message functions, all to no avail, most saying not defined.
I got assistance from the Discord.py Discord.
#client.event
async def on_message(message):
if message.content and message.content.startswith("$") and not message.author.bot:
user = await client.fetch_user(user_id)
await user.send(message.content)

Join + Leave with a Discord bot in Python

I've made these two commands, one for leaving the channel that the bot is currently connected to, and one for joining the command sender's channel.
The problem is that neither of them are working. How can I fix this?
#bot.command(pass_context=True)
async def leave(ctx):
server = ctx.message.guild.voice_client
await server.disconnect()
#bot.command(pass_context = True)
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await bot.join_voice_channel(channel)
It looks as though you're using old documentation or tutorials, along with some new documentation.
Some changes from 0.16.x to rewrite:
You should use VoiceChannel.join() instead of Client.join_voice_channel()
Shortcuts are available when using Context. In your case, ctx.guild instead of ctx.message.guild.
All voice changes
Context is automatically passed - there isn't any need for pass_context=True
Rewriting your code - with some conditions to check if the author is in a voice channel:
#bot.command()
async def leave(ctx):
if ctx.guild.voice_client.is_connected(): # Checking that they're in a vc
await ctx.guild.voice_client.disconnect()
else:
await ctx.send("Sorry, I'm not connected to a voice channel at the moment.")
#bot.command()
async def join(ctx):
if ctx.author.voice:
await ctx.author.voice.channel.connect() # This will error if the bot doesn't have sufficient permissions
else:
await ctx.send("You're not connected to a channel at the moment.")
References:
New documentation
VoiceClient.is_connected()
VoiceClient.disconnect()
Context.send()
Member.voice
VoiceState.channel
VoiceChannel.connect()

Discord Bot Delete Messages in Specific Channel

TIA for your help and apologies, I'm a newbie so this may be a foolish question. I've searched through and can't find anything specific on how to make a discord bot (in Python) delete messages only within a specific channel. I want all messages sent to a specific channel to be deleted, their contents sent via PM to the user and the user's role changed.
Is there a way to use on_message and specify in an specific channel?
#client.event
async def on_message(message):
user = message.author
if message.content.startswith("Cluebot:"):
await message.delete()
await user.send("Yes?")
await user.remove_roles(get(user.guild.roles, "Investigator"))
The problem I'm having is I'm also using commands which now no longer work because the bot only responds if the message begins with "Cluebot:" Can I have the bot only look for "Cluebot:" in a specific channel?
Is it possible to make this work through a command instead of an event?
Thanks for your help. :)
The problem I'm having is I'm also using commands which now no longer work because the bot only responds if the message begins with "Cluebot:" Can I have the bot only look for "Cluebot:" in a specific channel?
About this problem the clue is:
await bot.process_commands(message)
as docs says Without this coroutine, none of the commands will be triggered.
about the main question you could try using get_channel by ID and then purge it:
eg.
#client.event
async def on_message(message):
purgeChannel = client.get_channel([CHANNEL ID]])
await purgeChannel.purge(limit=1)
you can add check to purge() to check for deleting specific message:
eg.:
def check(message):
return message.author.id == [author's ID]
#client.event
async def on_message(message):
purgeChannel = client.get_channel([CHANNEL ID]])
await purgeChannel.purge(limit=1, check=check)

Blocking commands in a certain discord.py channel

So I recently added this code
#bot.event
async def on_message(message):
prefix = re.findall('([;]|[-]|[=]+)', message.content.lower())
if prefix and message.channel.id == "405815888177266689":
await bot.delete_message(message)
The bot does remove the message but the bot detects the command too fast so the other bot(s) reply. I am wanting to make it where the other bots can't reply. What I'm asking is - is it possible to basically add the purge to this command to make it purge the recent 2 messages (the command + the bots reply).
You could do something like this
#bot.event
async def on_message(message):
prefix = re.findall('([;]|[-]|[=]+)', message.content.lower())
if prefix and message.channel.id == "405815888177266689":
await bot.delete_message(message)
muted_bots = ['bot_1_id','bot_2_id']
async for msg in bot.logs_from(bot.get_channel("405815888177266689"), limit=4):
if msg.author.id in muted_bots:
await bot.delete_message(msg)
where after someone writes a message with that prefix and it gets deleted, it checks for the last number of messages (whatever you put the limit to depending on how many bots respond) and checks if whoever wrote that is in your muted_bots id list.

Categories

Resources