首页 > 解决方案 > 制作电报机器人 - ClassNotFoundException: org.apache.http.client.HttpClient

问题描述

我有一个大问题:

我想做一个非常简单的 Telegram Bot 。


我搜索了很多网站,找到了这段代码,但是在运行以下代码时出现了这个错误:

我在 Eclipse 中尝试过,但错误是一样的,它是关于ClassLoader


我不知道是什么问题,该怎么办?

C:\Users\HM\.jdks\openjdk-16.0.2\bin\java.exe "-javaagent:E:\IntelliJ IDEA 
Community Edition 2021.1.1\lib\idea_rt.jar=51246:E:\IntelliJ IDEA Community Edition 
2021.1.1\bin" -Dfile.encoding=UTF-8 -classpath 

C:\Users\HM\IdeaProjects\telegramNew\out\production\telegramNew
;C:\Users\HM\Desktop\telegram 
bots-5.3.0.jar;C:\Users\HM\Desktop\telegrambots-meta-5.3.0.jar com.company.Main
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient
at com.company.Main.main(Main.java:14)
Caused by: java.lang.ClassNotFoundException: org.apache.http.client.HttpClient
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
... 1 more

我的主要方法:

import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;

public class Main {

  public static void main(String[] args) {

    try {
      TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);

      botsApi.registerBot(new MyBot());
    } catch (TelegramApiException e) {
      e.printStackTrace();
    }

  }
}

我的机器人:

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 MyBot extends TelegramLongPollingBot {

  @Override
  public String getBotUsername() {
    return "hamidComputerBot";
  }

  @Override
  public String getBotToken() {
    return "1909766145:AAF7rk22xEbtM45zUm4RVCpK3MNpjuD52lI";
  }

  @Override
  public void onUpdateReceived(Update update) {

    if (update.hasMessage() && update.getMessage().hasText()) {
      SendMessage message = new SendMessage(); // Create a SendMessage object with 
      mandatory fields
      message.setChatId(update.getMessage().getChatId().toString());
      message.setText(update.getMessage().getText());

      try {
        execute(message); // Call method to send the message
      } catch (TelegramApiException e) {
        e.printStackTrace();
      }

    }
  }
}

标签: javatelegram-bot

解决方案


我有同样的麻烦。
您应该导入 maven lib transitive dependencies(看看它在 Intellij Idea 中的外观)。
它是必需的,因为电报 Api 的某些部分使用了这些不包含在telegram bots-5.3.0.jar

在此处输入图像描述


推荐阅读