我正在构建我的第一个电报机器人。它每 5 秒向用户发送一条消息。
虽然它将其发送给一位用户,但它无法从其他聊天中接收更新。
public void foo(msg, Update update){
msg.setChatId(update.getMessage().getChatId());
for (int i = 1; i < links.size(); i++){
msg.setText(links.get(i));
execute(msg);
}
Thread.sleep(wait * 1000);
}
如何使用线程?我尝试在这里创建多个线程
public static void bot(){
ApiContextInitializer.init();
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(new myBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
但他尝试创建多个机器人但失败了。如果这是可运行函数,则相同:
我该怎么做?我被困住了。我无法在不同线程中创建此函数
public void onUpdateReceived(Update update) {
leggi(new SendMessage(), update.getMessage().getText(), update);
//.setChatId(update.getMessage().getChatId())
public void leggi(SendMessage msg, String command, Update update){
if(command.equals("test") {
foo( msg, update);
}
这里是完整的代码... https://github.com/siamoInPochi/Ilsottomarinobot/tree/prova/src/main/java/Ilsottomarinobot
最佳答案
如果您为每个想要接收消息的机器人用户生成一个线程,那么在用户数量较多的情况下,您将很快耗尽计算机资源。所以我认为线程对于你的任务来说不是一个好主意。
在我看来,更自然的方法如下:
- 查找具有 HTTP 服务器的图书馆。
- 从
GetUpdates
切换到 Webhooks。 - 将
每 5 秒发送消息给用户
任务安排到服务器的事件循环。 - 每 5 秒异步发送一次消息。
关于java - 使用 TelegramLongPollingBot 和线程同时处理多个用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55690909/