要清空 Discord 服务器上的频道消息,您需要使用 Discord4J 版本 3.2.4 的 Bot。以下是一个示例代码,可以用来清空指定频道的所有消息:

import discord4j.common.util.Snowflake;
import discord4j.core.DiscordClient;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Channel;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.TextChannel;
import discord4j.core.object.util.Permission;
import discord4j.core.spec.MessageDeleteSpec;
import discord4j.rest.util.PermissionSet;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class ClearMessagesBot {
  
  public static void main(String[] args) {
    DiscordClient client = DiscordClient.create("YOUR_BOT_TOKEN");
    
    client.getEventDispatcher().on(MessageCreateEvent.class)
        .flatMap(event -> {
          Message message = event.getMessage();
          String content = message.getContent();
          if (content.startsWith("!clear")) {
            return clearMessages(message.getChannelId());
          }
          return Mono.empty();
        }).subscribe();
    
    client.login().block();
  }
  
  private static Mono<Void> clearMessages(Snowflake channelId) {
    return Mono.just(channelId)
        .flatMap(id -> {
          TextChannel channel = (TextChannel) channel(id);
          if (channel == null) {
            return Mono.error(new IllegalArgumentException("Invalid channel ID"));
          }
          if (!channel.getGuildId().isPresent()) {
            return Mono.error(new IllegalArgumentException("Cannot clear messages in DM"));
          }
          if (!channel.getGuild().getSelfMember().hasPermission(channelId, Permission.MANAGE_MESSAGES)) {
            return Mono.error(new IllegalStateException("Bot does not have permission to manage messages"));
          }
          return Flux.fromIterable(channel.getMessagesBefore(Snowflake.of(System.currentTimeMillis())))
              .flatMap(message -> message.delete(spec -> {}))
              .then();
        });
  }
  
  private static Channel channel(Snowflake id) {
    return DiscordClient.getDefaultResources().getRestClient().getChannelById(id).block();
  }
  
}

这个 Bot 在收到以 !clear 开头的消息时,会清空当前频道的所有消息。请注意,这个操作是不可逆的,一旦执行,所有消息都将被删除。因此,您应该在使用之前谨慎考虑清空消息的必要性。

discord4j version 324 bot 清空频道消息

原文地址: https://www.cveoy.top/t/topic/bYP2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录