Java Telegrambots отправка сообщений

Хочу настроить отправку сообщений пользователям, рассылку типо.

 import org.telegram.telegrambots.bots.TelegramLongPollingBot;
 import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
 import org.telegram.telegrambots.meta.api.objects.Update;
 import org.telegram.telegrambots.meta.exceptions.TelegramApiException;


 public class Bot extends TelegramLongPollingBot {
private String chat_id;
private String nameUser = "";
Login login = new Login();

  public void sendMsg(SendMessage message, String text, String chat){
      
      chat = "77777";
      text = "test";
      
        SendMessage sendMessage = new SendMessage();            
        sendMessage.enableMarkdown(true);                           
        sendMessage.setChatId(chat);     
      //sendMessage.setReplyToMessageId(message.getMessageId());    
        sendMessage.setText(text);                                 
        try {
           execute(new SendMessage(chat, text));
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
 

public void onUpdateReceived(Update update) {
    update.getUpdateId();
    
    
    SendMessage sendMessage = new SendMessage().setChatId(update.getMessage().getChatId());
    
    if(update.getMessage().getText().equals("Привет")) {
        sendMessage.setText("hello World.");
        try {
            execute(sendMessage);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
    
     
    
    chat_id = String.valueOf(update.getMessage().getChatId());
    nameUser = update.getMessage().getFrom().getUserName();
    String text = update.getMessage().getText();
    try {
        sendMessage.setText(getMsg(text));
        execute(sendMessage);
        System.out.println(update.getMessage().getFrom().getUserName() + ": " + update.getMessage().getText());
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}
public String getMsg(String msg) {
/*  if(msg.contains("/remove")){
        msg.replace("/remove", "");
        login.remove(msg);
        
    } */
if(msg.contains("/add")) {
    login.add(nameUser,  chat_id);

}



return "OK";

}

public String getBotUsername() {
    return "";
    
}
public String getBotToken() {
    return "";
    
}
 }

и класс для отправки в БД

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;


public class Login {

private Connection con;
private Statement st;
private ResultSet rs;

public Login() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection( "jdbc:", "", "");
    st = con.createStatement();
    
    } catch (Exception e) {
        System.out.println("Error: " +e);
    }
}
public String add(String name, String chat_id) {
    String sql = "INSERT INTO id(name, chat_id) VALUES(?,?)";
    try {
        PreparedStatement st = con.prepareStatement(sql);
        st.setString( 1, name);
        st.setString( 2, chat_id);
        st.executeUpdate ();
    } catch (SQLException e) {
        System.out.println("Error " +e);
        return "Ne ydaloc dobavit";
        
    }
return "Yspeshno";
}
public void change(String newName, String id_chat) {
    try {
        PreparedStatement st = con.prepareStatement( "UPDATE id SET name = ? WHERE chat_id = ?");
        st.setString( 1, newName);;
        st.setString(2, id_chat);
        st.executeUpdate();
        
    }catch(Exception ex) {
        System.out.println(ex);
        
    }
}

/* public ArrayList getChatID() {
    ArrayList<String> list = null;
try {
    list = new ArrayList<>();
    PreparedStatement st = null;
    String query = "select * FROM id";
    st = con.prepareStatement(query);
    rs = st.executeQuery();
    while (rs.next()) {
        list.add(rs.getString( "chat_id"));
    }
} catch (SQLException e) {
    e.printStackTrace();
}
return list;

    }



*/
}

Планирую, чтоб при запуске, сразу шла рассылка сообщений всем, кто записался в базу. пока вставил для тест чат ид сразу, но при запуске не идет отправка сообщения. консоль тоже ничего не говорит, ошибок связанных с этим - нет. подскажите, что не так делаю?


Ответы (1 шт):

Автор решения: Иван Луполов

На сколько мне известно бот не может отсылать сообщения пользователям, если они ни разу с ним не общались. Если подставляемое id принадлежит пользователю, который не активировал вашего ботаы не сможете ему ничего послать. Первым должен прислать сообщение пользователь, а оттуда уже вы сможете достать chat_id по которому можно уже слать сообщение пользователю в ответ, пока у него активен бот.

→ Ссылка