package de.mrbesen.telegram; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import org.json.JSONObject; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Random; //for https server: https://stackoverflow.com/questions/2308479/simple-java-https-server //for jks store: https://stackoverflow.com/questions/2138940/import-pem-into-java-key-store public class WebhookTelegramAPI extends TelegramAPI implements HttpHandler { private int port = 8000; private String pw = "supersecret"; public void main() throws Exception { try { HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/" + pw , this); server.setExecutor(null); // creates a default executor server.start(); start = System.currentTimeMillis(); } catch (Exception exception) { System.out.println("Failed to create HTTPS server on port " + port + " of localhost"); exception.printStackTrace(); } } @Override public void handle(HttpExchange req) throws IOException { req.sendResponseHeaders(200,0); String data = readfromIS(req.getRequestBody()); TelegramAPIUpdate upd = new TelegramAPIUpdate(new JSONObject(data), this); ++fetchedUpdates; } public WebhookTelegramAPI(String apikey, String externaladdr, String allowedupd) throws IOException { super(apikey); byte[] array = new byte[16]; // length is bounded by 7 new Random().nextBytes(array); pw = new String(array, Charset.forName("UTF-8")); if(externaladdr.endsWith("/")) externaladdr = externaladdr.substring(0, externaladdr.length()-1); request("setWebhook", "url=" + externaladdr + "/" + pw + "&allowed_updates=" + allowedupd, 0); } public WebhookTelegramAPI(String apikey, String externaladdr) throws IOException { this(apikey, externaladdr, "[\"message\",\"edited_message\",\"channel_post\",\"edited_channel_post\",\"inline_query\",\"chosen_inline_result\",\"callback_query\",\"shipping_query\",\"pre_checkout_query\"]"); } }