discord机器人异常地重复

20jt8wwn  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(416)

因此,我尝试创建一个discord bot,它可以简单地访问数据库以打印出值,我的代码当前将把值打印到discord服务器,但它会重复它们5次。
机器人功能类:

private MySQLAccess sql = new MySQLAccess();

public static void main(String[] args) throws Exception {
    JDABuilder ark = new JDABuilder(AccountType.BOT);
    ark.setToken("insert_discord_token_here");
    ark.addEventListener(new MessageListener());
    ark.buildAsync();
}

@Override
public void onMessageReceived(MessageReceivedEvent e) {
    if (e.getAuthor().isBot()) return;
    Message msg = e.getMessage();
    String str = msg.getContentRaw();

    //Ping pong
    if (str.equalsIgnoreCase("!ping")) {
        e.getChannel().sendMessage("Pong!").queue();
    }

    //Bal check
    if (str.contains("!bal")) {
        String user = str.substring(5);
        System.out.println(user);
        try {
            sql.readDataBase(e.getChannel(), user);
        } catch (Exception e1) {
        }

    }
}

数据库访问类:

private Connection connect = null;
private Statement statement = null;
private ResultSet resultSet = null;
private final String user = "pass";
private final String pass = "user";

public void readDataBase(MessageChannel msg, String username) throws Exception {
    //Retrieve data and search for username
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");

        connect = DriverManager.getConnection("jdbc:mysql://localhost/serverusers?allowPublicKeyRetrieval=true&useSSL=false", user, pass);

        statement = connect.createStatement();
        resultSet = statement
                .executeQuery("select * from serverusers.userinfo where user=\"" + username + "\"");
        writeResultSet(resultSet, msg);

    } catch (Exception e) {
        throw e;
    } finally {
        close();
    }

}

private void writeResultSet(ResultSet resultSet, MessageChannel msg) throws SQLException {
    // Check resultSet and print its contents
    if (resultSet.next()) {
        String user = resultSet.getString(2);
        Double website = resultSet.getDouble(3);
        msg.sendMessage("User: " + user).queue();
        msg.sendMessage("Bank Amount: " + website).queue();
    }
}

private void close() {
    try {
        if (resultSet != null) {
            resultSet.close();
        }

        if (statement != null) {
            statement.close();
        }

        if (resultSet != null) {
            resultSet.close();
        }
        if (connect != null) {
            connect.close();
        }
    } catch (Exception e) {

    }
}

当程序运行时,它会找到正确的数据,我正在寻找和搜索功能是好的,但由于一些奇怪的原因,该程序会吐出相同的用户名和平衡5倍。discord机器人截图

vlju58qv

vlju58qv1#

这里常见的错误是,您多次运行程序,然后每个示例相应地用相同的东西响应。您可以通过打开任务管理器并查找java进程来检查是否存在这种情况。这通常发生在使用eclipseide的开发人员身上,因为控制台将其他进程隐藏在控制台的下拉菜单后面。

相关问题