I am trying to loop through message history of a particular Discord channel and delete all previous messages before sending new messages to the channel. I can't seem to figure this out and have searched EVERYWHERE to find a solution. My code below:
import discord
from discord.ext import tasks, commands
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
async def my_background_task():
channel = client.get_channel(999999999999999)
history = await channel.history().flatten()
await channel.delete_messages(history)
# Loop and send messages to channel
while not client.is_closed():
await channel.send('Test')
schedule.every(5).seconds.do(my_background_task)
# Loop event
@client.event
async def on_ready():
print('Running...')
client.loop.create_task(my_background_task())
When I go to run my code, I get the following error:
repl process died unexpectedly: signal: killed
CodePudding user response:
You can try using the channel.purge() methode instead. It Works fine for me. The only Problem is that it will be a bit laggy if there are too many messages in the channel.
import discord
from discord.ext import tasks, commands
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#deletes all messages in one particular channel
async def deleteAllMessages(deleted, channel):
purge = len(await channel.purge(limit=100))
if purge < 100:
print(f"process finished\n{deleted purge} messages were deleted.")
return
else:
await deleteAllMessages(deleted 100, channel)
return
async def my_background_task():
channel = client.get_channel(999999999999999)
await deleteAllMessages(0, channel)
#Loop and send messages to channel
if not client.is_closed():
await channel.send('Test')
schedule.every(5).seconds.do(my_background_task)
# Loop event
@client.event
async def on_ready():
print('Running...')
client.loop.create_task(my_background_task())
I hope this is what you were looking for