首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >循环通过通道中的不和谐消息历史并删除

循环通过通道中的不和谐消息历史并删除
EN

Stack Overflow用户
提问于 2022-08-14 02:41:46
回答 1查看 130关注 0票数 0

我试图在发送新消息之前循环遍历特定不和谐通道的消息历史,并删除所有以前的消息。我似乎搞不懂这件事,到处寻找解决办法。我的代码如下:

代码语言:javascript
运行
复制
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()) 

当我去运行我的代码时,我会得到以下错误:

repl process died unexpectedly: signal: killed

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-14 12:01:48

您可以尝试使用channel.purge()方法代替。对我来说很好。唯一的问题是,如果信道中有太多的消息,就会有点滞后。

代码语言:javascript
运行
复制
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()) 

我希望这就是你想要的

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73348825

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档