【问题标题】:Discord JDA - Sometimes working, sometimes notDiscord JDA - 有时有效,有时无效
【发布时间】:2022-01-05 19:08:47
【问题描述】:

我想做的是:

当一个人离开一个特定的语音频道,而这个频道现在是空的,机器人:

  • 删除特定文本频道中除 1 条以外的所有消息
  • 删除他刚刚离开的语音频道

问题:

  • 语音通道已成功删除,但文本通道中的消息未被机器人删除

代码:

@Override
public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
     
    
      VoiceChannel channelLeft = event.getChannelLeft();
                
        if (channelLeft.getName().startsWith("???? Coaching de")) { 
            
            if (channelLeft.getMembers().isEmpty()) { 
  
                channelLeft.delete().queue(); //The bot delete de channel successfully
                
                List<Message> messagesCoaching = event.getChannelLeft().getGuild().getTextChannelById("489420943991635988").getHistory().retrievePast(20).complete(); // Using a list to store the retrieved messages
        
                messagesCoaching.removeIf(m -> m.getId().equals("490567304971812885")); // Removing from the list the message i want to keep 
        
                event.getChannelLeft().getGuild().getTextChannelById("489420943991635988").deleteMessages(messagesCoaching).complete(); // Deleting all the messages (not working)
            
            } 
            
            
        }

【问题讨论】:

    标签: discord bots discord-jda


    【解决方案1】:

    我不能 100% 确定您的错误是什么,但我可以向您保证,您正在尝试删除在文本频道中发送的所有消息。

    目前,您的代码从您通过 ID 获得的文本通道获取最后 20 条消息。如果您有超过 20 条消息,机器人不会删除这些消息。如果消息超过 2 周,它也不会删除它们。此外,不要使用 complete(),因为这会停止机器人的主线程。我建议使用这样的代码:

        @Override
        public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
            VoiceChannel channelLeft = event.getChannelLeft();
    
            if (channelLeft.getName().startsWith("? Coaching de")) {
    
                if (channelLeft.getMembers().isEmpty()) {
                    channelLeft.delete().queue(); // Telling the bot to delete the channel.
                    MessageHistory history = event.getGuild().getTextChannelById("489420943991635988").getHistory(); // Pulling up the history from a text channel
    
                    history.retrievePast(100).queue(messages -> { // Putting the past 100 messages in a queue, and using a lamba to do something with the returned messages
                        messages.removeIf(m -> m.getId().equals("490567304971812885")); // If a message contains the same ID as told here, it removes it.
                        event.getGuild().getTextChannelById("489420943991635988").deleteMessages(messages).queue(); // And now, delete all messages.
                    });
                }
            }
        }
    

    【讨论】:

    • 更好一点,因为它使用队列机制来防止停止整个机器人,直到它设法完成上述任务
    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2012-08-02
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多