1. Refactor

This commit is contained in:
Rubenlagu 2016-01-14 23:09:19 +01:00 committed by Rubenlagus
parent 9a7c9bbd4d
commit 25d11ecadc
62 changed files with 718 additions and 674 deletions

View File

@ -1,13 +0,0 @@
package org.telegram.api.objects;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents one result of an inline query.
* @date 01 of January of 2016
*/
public interface InlineQueryResult extends BotApiObject, IToJson {
}

View File

@ -1,13 +0,0 @@
package org.telegram.api.objects;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Reply keyboard abstract type
* @date 20 of June of 2015
*/
public interface ReplyKeyboard extends BotApiObject, IToJson {
}

View File

@ -1,348 +0,0 @@
package org.telegram.services;
import org.telegram.BuildVars;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Ruben Bermudez
* @version 2.0
* @brief Logger to file
* @date 21/01/15
*/
public class BotLogger {
private static final Object lockToWrite = new Object();
private static volatile PrintWriter logginFile;
private static volatile String currentFileName;
private static final Logger logger = Logger.getLogger("Tsupport Bot");
private static volatile LocalDateTime lastFileDate;
private static LoggerThread loggerThread = new LoggerThread();
private static final ConcurrentLinkedQueue<String> logsToFile = new ConcurrentLinkedQueue<>();
static {
logger.setLevel(Level.ALL);
logger.addHandler(new ConsoleHandler());
loggerThread.start();
lastFileDate = LocalDateTime.now();
if ((currentFileName == null) || (currentFileName.compareTo("") == 0)) {
currentFileName = dateFormatterForFileName(lastFileDate) + ".log";
try {
final File file = new File(currentFileName);
if (file.exists()) {
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} else {
final boolean created = file.createNewFile();
if (created) {
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} else {
throw new NullPointerException("File for logging error");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void log(@NotNull Level level, String tag, String msg) {
logger.log(level, String.format("[%s] %s", tag, msg));
logToFile(level, tag, msg);
}
public static void severe(String tag, String msg) {
logger.severe(String.format("[%s] %s", tag, msg));
logToFile(Level.SEVERE, tag, msg);
}
public static void warn(String tag, String msg) {
warning(tag, msg);
}
public static void debug(String tag, String msg) {
fine(tag, msg);
}
public static void error(String tag, String msg) {
severe(tag, msg);
}
public static void trace(String tag, String msg) {
finer(tag, msg);
}
public static void warning(String tag, String msg) {
logger.warning(String.format("[%s] %s", tag, msg));
logToFile(Level.WARNING, tag, msg);
}
public static void info(String tag, String msg) {
logger.info(String.format("[%s] %s", tag, msg));
logToFile(Level.INFO, tag, msg);
}
public static void config(String tag, String msg) {
logger.config(String.format("[%s] %s", tag, msg));
logToFile(Level.CONFIG, tag, msg);
}
public static void fine(String tag, String msg) {
logger.fine(String.format("[%s] %s", tag, msg));
logToFile(Level.FINE, tag, msg);
}
public static void finer(String tag, String msg) {
logger.finer(String.format("[%s] %s", tag, msg));
logToFile(Level.FINER, tag, msg);
}
public static void finest(String tag, String msg) {
logger.finest(String.format("[%s] %s", tag, msg));
logToFile(Level.FINEST, tag, msg);
}
public static void log(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable) {
logger.log(level, String.format("[%s] Exception", tag), throwable);
logToFile(level, tag, throwable);
}
public static void log(@NotNull Level level, @NotNull String tag, @NotNull String msg, @NotNull Throwable thrown) {
logger.log(level, msg, thrown);
logToFile(level, msg, thrown);
}
public static void severe(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.SEVERE, tag, throwable);
}
public static void warning(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.WARNING, tag, throwable);
}
public static void info(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.INFO, tag, throwable);
}
public static void config(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.CONFIG, tag, throwable);
}
public static void fine(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.FINE, tag, throwable);
}
public static void finer(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.FINER, tag, throwable);
}
public static void finest(@NotNull String tag, @NotNull Throwable throwable) {
logToFile(Level.FINEST, tag, throwable);
}
public static void warn(@NotNull String tag, Throwable throwable) {
warning(tag, throwable);
}
public static void debug(@NotNull String tag, Throwable throwable) {
fine(tag, throwable);
}
public static void error(@NotNull String tag, Throwable throwable) {
severe(tag, throwable);
}
public static void trace(@NotNull String tag, Throwable throwable) {
finer(tag, throwable);
}
public static void severe(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.SEVERE, tag, msg, throwable);
}
public static void warning(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.WARNING, tag, msg, throwable);
}
public static void info(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.INFO, tag, msg, throwable);
}
public static void config(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.CONFIG, tag, msg, throwable);
}
public static void fine(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINE, tag, msg, throwable);
}
public static void finer(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINER, tag, msg, throwable);
}
public static void finest(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINEST, msg, throwable);
}
public static void warn(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.WARNING, tag, msg, throwable);
}
public static void debug(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINE, tag, msg, throwable);
}
public static void error(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.SEVERE, tag, msg, throwable);
}
public static void trace(@NotNull String msg, @NotNull String tag, @NotNull Throwable throwable) {
log(Level.FINER, tag, msg, throwable);
}
private static boolean isCurrentDate(LocalDateTime dateTime) {
return dateTime.toLocalDate().isEqual(lastFileDate.toLocalDate());
}
private static String dateFormatterForFileName(@NotNull LocalDateTime dateTime) {
String dateString = "";
dateString += dateTime.getDayOfMonth();
dateString += dateTime.getMonthValue();
dateString += dateTime.getYear();
return dateString;
}
private static String dateFormatterForLogs(@NotNull LocalDateTime dateTime) {
String dateString = "[";
dateString += dateTime.getDayOfMonth() + "_";
dateString += dateTime.getMonthValue() + "_";
dateString += dateTime.getYear() + "_";
dateString += dateTime.getHour() + ":";
dateString += dateTime.getMinute() + ":";
dateString += dateTime.getSecond();
dateString += "] ";
return dateString;
}
private static void updateAndCreateFile(LocalDateTime dateTime) {
if (!isCurrentDate(dateTime)) {
lastFileDate = LocalDateTime.now();
currentFileName = BuildVars.pathToLogs + dateFormatterForFileName(lastFileDate) + ".log";
try {
logginFile.flush();
logginFile.close();
final File file = new File(currentFileName);
if (file.exists()) {
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} else {
final boolean created = file.createNewFile();
if (created) {
logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true)));
} else {
throw new NullPointerException("Error updating log file");
}
}
} catch (IOException ignored) {
}
}
}
private static void logToFile(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable) {
if (isLoggable(level)) {
synchronized (lockToWrite) {
final LocalDateTime currentDate = LocalDateTime.now();
final String dateForLog = dateFormatterForLogs(currentDate);
updateAndCreateFile(currentDate);
logThrowableToFile(level, tag, throwable, dateForLog);
}
}
}
private static void logToFile(@NotNull Level level, @NotNull String tag, @NotNull String msg) {
if (isLoggable(level)) {
synchronized (lockToWrite) {
final LocalDateTime currentDate = LocalDateTime.now();
updateAndCreateFile(currentDate);
final String dateForLog = dateFormatterForLogs(currentDate);
logMsgToFile(level, tag, msg, dateForLog);
}
}
}
private static void logToFile(Level level, @NotNull String tag, @NotNull String msg, @NotNull Throwable throwable) {
if (isLoggable(level)) {
synchronized (lockToWrite) {
final LocalDateTime currentDate = LocalDateTime.now();
updateAndCreateFile(currentDate);
final String dateForLog = dateFormatterForLogs(currentDate);
logMsgToFile(level, tag, msg, dateForLog);
logThrowableToFile(level, tag, throwable, dateForLog);
}
}
}
private static void logMsgToFile(@NotNull Level level, @NotNull String tag, @NotNull String msg, @NotNull String dateForLog) {
final String logMessage = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, msg);
logsToFile.add(logMessage);
synchronized (logsToFile) {
logsToFile.notifyAll();
}
}
private static void logThrowableToFile(@NotNull Level level, @NotNull String tag, @NotNull Throwable throwable, @NotNull String dateForLog) {
String throwableLog = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, throwable.toString());
for (StackTraceElement element : throwable.getStackTrace()) {
throwableLog += "\tat " + element + "\n";
}
logsToFile.add(throwableLog);
synchronized (logsToFile) {
logsToFile.notifyAll();
}
}
private static boolean isLoggable(Level level) {
return logger.isLoggable(level) && BuildVars.debug;
}
private static class LoggerThread extends Thread {
@Override
public void run() {
while(true) {
final ConcurrentLinkedQueue<String> stringsToLog = new ConcurrentLinkedQueue<>();
synchronized (logsToFile) {
if (logsToFile.isEmpty()) {
try {
logsToFile.wait();
} catch (InterruptedException e) {
return;
}
if (logsToFile.isEmpty()) {
continue;
}
}
stringsToLog.addAll(logsToFile);
logsToFile.clear();
}
stringsToLog.stream().forEach(logginFile::println);
logginFile.flush();
}
}
}
}

View File

@ -0,0 +1,30 @@
package org.telegram.telegrambots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief TODO
* @date 14 of January of 2016
*/
public class TelegramApiException extends Exception {
private String apiResponse = null;
public TelegramApiException(String message) {
super(message);
}
public TelegramApiException(String message, String apiResponse) {
super(message);
this.apiResponse = apiResponse;
}
public TelegramApiException(String message, Throwable cause) {
super(message, cause);
}
public String getApiResponse() {
return apiResponse;
}
}

View File

@ -0,0 +1,161 @@
package org.telegram.telegrambots;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.api.Constants;
import org.telegram.telegrambots.api.methods.SetWebhook;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.bots.TelegramWebhookBot;
import org.telegram.telegrambots.updatesreceivers.UpdatesThread;
import org.telegram.telegrambots.updatesreceivers.Webhook;
import java.io.File;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief TODO
* @date 14 of January of 2016
*/
public class TelegramBotsApi {
private final boolean useWebhook; ///<
private final Webhook webhook; ///<
private final String extrenalUrl; ///<
private final String pathToCertificate; ///<
private final String publicCertificateName; ///<
/**
*
*/
public TelegramBotsApi() {
this.useWebhook = false;
webhook = null;
extrenalUrl = null;
this.pathToCertificate = null;
this.publicCertificateName = null;
}
/**
*
* @param keyStore
* @param keyStorePassword
* @param externalUrl
* @param internalUrl
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiException {
this.useWebhook = true;
this.extrenalUrl = fixExternalUrl(externalUrl);
this.pathToCertificate = null;
this.publicCertificateName = null;
webhook = new Webhook(keyStore, keyStorePassword, internalUrl);
webhook.startServer();
}
/**
*
* @param keyStore
* @param keyStorePassword
* @param externalUrl
* @param internalUrl
* @param pathToCertificate
* @param publicCertificateName
*/
public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate, String publicCertificateName) throws TelegramApiException {
this.useWebhook = true;
this.extrenalUrl = fixExternalUrl(externalUrl);
this.pathToCertificate = pathToCertificate;
this.publicCertificateName = publicCertificateName;
webhook = new Webhook(keyStore, keyStorePassword, internalUrl);
webhook.startServer();
}
/**
*
* @param bot
*/
public void registerBot(TelegramLongPollingBot bot) throws TelegramApiException {
setWebhook(bot.getBotToken());
new UpdatesThread(bot.getBotToken(), bot);
}
/**
*
* @param bot
*/
public void registerBot(TelegramWebhookBot bot) throws TelegramApiException {
if (useWebhook) {
webhook.registerWebhook(bot);
setWebhook(bot.getBotToken());
}
}
/**
*
* @param botToken
*/
private void setWebhook(String botToken) throws TelegramApiException {
if (botToken != null) {
throw new TelegramApiException("Parameter botToken can not be null");
}
setWebhook(extrenalUrl, botToken, pathToCertificate, publicCertificateName);
}
/**
*
* @param externalUrl
* @return
*/
private static String fixExternalUrl(String externalUrl) {
if (!externalUrl.endsWith("/")) {
externalUrl = externalUrl + "/";
}
return externalUrl;
}
/**
*
* @param webHookURL
* @param botToken
* @param publicCertificatePath
* @param publicCertificateName
* @throws TelegramApiException
*/
private static void setWebhook(String webHookURL, String botToken, String publicCertificatePath, String publicCertificateName) throws TelegramApiException {
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + SetWebhook.PATH;
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, webHookURL);
if (publicCertificatePath != null) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, new File(publicCertificatePath), ContentType.APPLICATION_OCTET_STREAM, publicCertificateName);
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new TelegramApiException(webHookURL == null ? "Error removing old webhook" : "Error setting webhook", responseContent);
}
} catch (JSONException e) {
throw new TelegramApiException("Error deserializing setWebhook method response", e);
} catch (IOException e) {
throw new TelegramApiException("Error executing setWebook method", e);
}
}
}

View File

@ -1,4 +1,4 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api;
/**
* @author Ruben Bermudez
@ -7,5 +7,5 @@ package org.telegram.api.methods;
* @date 20 of June of 2015
*/
public class Constants {
public static final String BASEURL = "https://api.telegram.org/bot";
public static final String BASEURL = "https://api.telegram.org/bot/";
}

View File

@ -1,7 +1,8 @@
package org.telegram.api.interfaces;
package org.telegram.telegrambots.api.interfaces;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.Serializable;
/**
* @author Ruben Bermudez
@ -9,5 +10,5 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
* @brief An object of Telegram Bots Api
* @date 07 of September of 2015
*/
public interface BotApiObject extends JsonSerializable {
public interface IBotApiObject extends JsonSerializable, Serializable {
}

View File

@ -1,4 +1,4 @@
package org.telegram.api.interfaces;
package org.telegram.telegrambots.api.interfaces;
import org.json.JSONObject;

View File

@ -1,11 +1,11 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.api.objects.InlineQueryResult;
import org.telegram.telegrambots.api.objects.InlineQueryResult;
import java.io.IOException;
import java.util.List;

View File

@ -1,8 +1,10 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.databind.JsonSerializable;
import org.json.JSONObject;
import org.telegram.api.interfaces.IToJson;
import org.telegram.telegrambots.api.interfaces.IToJson;
import java.io.Serializable;
/**
* @author Ruben Bermudez
@ -10,7 +12,7 @@ import org.telegram.api.interfaces.IToJson;
* @brief A method of Telegram Bots Api that is fully supported in json format
* @date 07 of September of 2015
*/
public abstract class BotApiMethod<T> implements JsonSerializable, IToJson {
public abstract class BotApiMethod<T extends Serializable> implements JsonSerializable, IToJson {
protected static final String METHOD_FIELD = "method";
/**

View File

@ -1,10 +1,10 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.objects.Message;
import org.telegram.telegrambots.api.objects.Message;
import java.io.IOException;

View File

@ -1,10 +1,10 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.objects.File;
import org.telegram.telegrambots.api.objects.File;
import java.io.IOException;

View File

@ -1,10 +1,10 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.objects.User;
import org.telegram.telegrambots.api.objects.User;
import java.io.IOException;

View File

@ -1,7 +1,7 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import org.json.JSONObject;
import org.telegram.api.interfaces.IToJson;
import org.telegram.telegrambots.api.interfaces.IToJson;
/**
* @author Ruben Bermudez

View File

@ -1,10 +1,10 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.objects.UserProfilePhotos;
import org.telegram.telegrambots.api.objects.UserProfilePhotos;
import java.io.IOException;

View File

@ -1,6 +1,6 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez

View File

@ -1,4 +1,4 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;

View File

@ -1,6 +1,6 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez

View File

@ -1,11 +1,11 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.objects.Message;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
import java.io.IOException;

View File

@ -1,11 +1,11 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.objects.Message;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
import java.io.IOException;

View File

@ -1,6 +1,6 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez

View File

@ -1,6 +1,6 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez

View File

@ -1,6 +1,6 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez

View File

@ -1,6 +1,6 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
import org.telegram.api.objects.ReplyKeyboard;
import org.telegram.telegrambots.api.objects.ReplyKeyboard;
/**
* @author Ruben Bermudez

View File

@ -1,4 +1,4 @@
package org.telegram.api.methods;
package org.telegram.telegrambots.api.methods;
/**
* @author Ruben Bermudez

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents an audio file
* @date 16 of July of 2015
*/
public class Audio implements BotApiObject {
public class Audio implements IBotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a Telegram chat with an user or a group
* @date 24 of June of 2015
*/
public class Chat implements BotApiObject {
public class Chat implements IBotApiObject {
private static final String USERCHATTYPE = "private";
private static final String GROUPCHATTYPE = "group";
private static final String CHANNELCHATTYPE = "channel";

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a result of an inline query that was chosen by the user and sent to their chat partner.
* @date 01 of January of 2016
*/
public class ChosenInlineQuery implements BotApiObject {
public class ChosenInlineQuery implements IBotApiObject {
public static final String RESULTID_FIELD = "id";
@JsonProperty(RESULTID_FIELD)
private String resultId; ///< The unique identifier for the result that was chosen.

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a phone contact.
* @date 20 of June of 2015
*/
public class Contact implements BotApiObject {
public class Contact implements IBotApiObject {
public static final String PHONENUMBER_FIELD = "phone_number";
@JsonProperty(PHONENUMBER_FIELD)

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -16,7 +16,7 @@ import java.io.IOException;
* Telegram users can send files of any type of up to 1.5 GB in size.
* @date 20 of June of 2015
*/
public class Document implements BotApiObject {
public class Document implements IBotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a file ready to be downloaded
* @date 24 of June of 2015
*/
public class File implements BotApiObject {
public class File implements IBotApiObject {
public static final String FILE_ID = "file_id";
@JsonProperty(FILE_ID)
private String fileId; ///< Unique identifier for this file

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -16,7 +16,7 @@ import java.io.IOException;
* When the user sends an empty query, your bot could return some default or trending results.
* @date 01 of January of 2016
*/
public class InlineQuery implements BotApiObject {
public class InlineQuery implements IBotApiObject {
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier for this query

View File

@ -0,0 +1,13 @@
package org.telegram.telegrambots.api.objects;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents one result of an inline query.
* @date 01 of January of 2016
*/
public interface InlineQueryResult extends IBotApiObject, IToJson {
}

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a point on the map.
* @date 20 of June of 2015
*/
public class Location implements BotApiObject {
public class Location implements IBotApiObject {
public static final String LONGITUDE_FIELD = "longitude";
@JsonProperty(LONGITUDE_FIELD)

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
@ -6,7 +6,7 @@ import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import java.util.ArrayList;
@ -18,7 +18,7 @@ import java.util.List;
* @brief This object represents a message.
* @date 20 of June of 2015
*/
public class Message implements BotApiObject {
public class Message implements IBotApiObject {
public static final String MESSAGEID_FIELD = "message_id";
@JsonProperty(MESSAGEID_FIELD)
private Integer messageId; ///< Integer Unique message identifier

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents one size of a photo or a file / sticker thumbnail.
* @date 20 of June of 2015
*/
public class PhotoSize implements BotApiObject {
public class PhotoSize implements IBotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)

View File

@ -0,0 +1,13 @@
package org.telegram.telegrambots.api.objects;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import org.telegram.telegrambots.api.interfaces.IToJson;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Reply keyboard abstract type
* @date 20 of June of 2015
*/
public interface ReplyKeyboard extends IBotApiObject, IToJson {
}

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a sticker.
* @date 20 of June of 2015
*/
public class Sticker implements BotApiObject {
public class Sticker implements IBotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -16,7 +16,7 @@ import java.io.IOException;
* Only one of the optional parameters can be present in any given update.
* @date 20 of June of 2015
*/
public class Update implements BotApiObject {
public class Update implements IBotApiObject {
public static final String UPDATEID_FIELD = "update_id";
@JsonProperty(UPDATEID_FIELD)
private Integer updateId;

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a Telegram user or bot.
* @date 20 of June of 2015
*/
public class User implements BotApiObject {
public class User implements IBotApiObject {
public static final String ID_FIELD = "id";
@JsonProperty(ID_FIELD)

View File

@ -1,4 +1,4 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
@ -6,7 +6,7 @@ import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
import java.util.ArrayList;
@ -18,7 +18,7 @@ import java.util.List;
* @brief This object represent a user's profile pictures.
* @date 22 of June of 2015
*/
public class UserProfilePhotos implements BotApiObject {
public class UserProfilePhotos implements IBotApiObject {
public static final String TOTALCOUNT_FIELD = "total_count";
@JsonProperty(TOTALCOUNT_FIELD)

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a video file.
* @date 20 of June of 2015
*/
public class Video implements BotApiObject {
public class Video implements IBotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)

View File

@ -1,11 +1,11 @@
package org.telegram.api.objects;
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.api.interfaces.BotApiObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
@ -15,7 +15,7 @@ import java.io.IOException;
* @brief This object represents a voice note
* @date 16 of July of 2015
*/
public class Voice implements BotApiObject {
public class Voice implements IBotApiObject {
public static final String FILEID_FIELD = "file_id";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file

View File

@ -1,4 +1,4 @@
package org.telegram;
package org.telegram.telegrambots.bots;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
@ -16,13 +16,17 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.telegram.api.methods.*;
import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.SentCallback;
import org.telegram.telegrambots.TelegramApiException;
import org.telegram.telegrambots.api.Constants;
import org.telegram.telegrambots.api.methods.*;
import org.telegram.telegrambots.api.objects.File;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.api.objects.UserProfilePhotos;
import org.telegram.telegrambots.updateshandlers.SentCallback;
import java.io.File;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
@ -31,23 +35,161 @@ import java.util.concurrent.Executors;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Send Helper
* @date 20 of June of 2015
* @brief TODO
* @date 14 of January of 2016
*/
public class SenderHelper {
private static final String LOGTAG = "SENDERHELPER";
private static final ExecutorService exe = Executors.newSingleThreadExecutor();
public abstract class AbsSender {
private final ExecutorService exe = Executors.newSingleThreadExecutor();
public abstract String getBotToken();
public Message sendMessage(SendMessage sendMessage) throws TelegramApiException {
if (sendMessage == null) {
throw new TelegramApiException("Parameter sendMessage can not be null");
}
return (Message) sendApiMethod(sendMessage);
}
public Boolean sendAnswerInlineQuery(AnswerInlineQuery answerInlineQuery) throws TelegramApiException {
if (answerInlineQuery == null) {
throw new TelegramApiException("Parameter answerInlineQuery can not be null");
}
return (Boolean) sendApiMethod(answerInlineQuery);
}
public Boolean sendChatAction(SendChatAction sendChatAction) throws TelegramApiException {
if (sendChatAction == null) {
throw new TelegramApiException("Parameter sendChatAction can not be null");
}
return (Boolean) sendApiMethod(sendChatAction);
}
public Message forwardMessage(ForwardMessage forwardMessage) throws TelegramApiException {
if (forwardMessage == null) {
throw new TelegramApiException("Parameter forwardMessage can not be null");
}
return (Message) sendApiMethod(forwardMessage);
}
public File sendLocation(SendLocation sendLocation) throws TelegramApiException {
if (sendLocation == null) {
throw new TelegramApiException("Parameter sendLocation can not be null");
}
return (File) sendApiMethod(sendLocation);
}
public UserProfilePhotos getUserProfilePhotos(GetUserProfilePhotos getUserProfilePhotos) throws TelegramApiException {
if (getUserProfilePhotos == null) {
throw new TelegramApiException("Parameter getUserProfilePhotos can not be null");
}
return (UserProfilePhotos) sendApiMethod(getUserProfilePhotos);
}
public User getMe() throws TelegramApiException {
GetMe getMe = new GetMe();
return (User) sendApiMethod(getMe);
}
public void sendMessageAsync(SendMessage sendMessage, SentCallback<Message> sentCallback) throws TelegramApiException {
if (sendMessage == null) {
throw new TelegramApiException("Parameter sendMessage can not be null");
}
if (sentCallback == null) {
throw new TelegramApiException("Parameter sentCallback can not be null");
}
sendApiMethodAsync(sendMessage, sentCallback);
}
public void sendAnswerInlineQueryAsync(AnswerInlineQuery answerInlineQuery, SentCallback<Boolean> sentCallback) throws TelegramApiException {
if (answerInlineQuery == null) {
throw new TelegramApiException("Parameter answerInlineQuery can not be null");
}
if (sentCallback == null) {
throw new TelegramApiException("Parameter sentCallback can not be null");
}
sendApiMethodAsync(answerInlineQuery, sentCallback);
}
public void sendChatActionAsync(SendChatAction sendChatAction, SentCallback<Boolean> sentCallback) throws TelegramApiException {
if (sendChatAction == null) {
throw new TelegramApiException("Parameter sendChatAction can not be null");
}
if (sentCallback == null) {
throw new TelegramApiException("Parameter sentCallback can not be null");
}
sendApiMethodAsync(sendChatAction, sentCallback);
}
public void forwardMessageAsync(ForwardMessage forwardMessage, SentCallback<Message> sentCallback) throws TelegramApiException {
if (forwardMessage == null) {
throw new TelegramApiException("Parameter forwardMessage can not be null");
}
if (sentCallback == null) {
throw new TelegramApiException("Parameter sentCallback can not be null");
}
sendApiMethodAsync(forwardMessage, sentCallback);
}
public void sendLocationAsync(SendLocation sendLocation, SentCallback<File> sentCallback) throws TelegramApiException {
if (sendLocation == null) {
throw new TelegramApiException("Parameter sendLocation can not be null");
}
if (sentCallback == null) {
throw new TelegramApiException("Parameter sentCallback can not be null");
}
sendApiMethodAsync(sendLocation, sentCallback);
}
public void getUserProfilePhotosAsync(GetUserProfilePhotos getUserProfilePhotos, SentCallback<UserProfilePhotos> sentCallback) throws TelegramApiException {
if (getUserProfilePhotos == null) {
throw new TelegramApiException("Parameter getUserProfilePhotos can not be null");
}
if (sentCallback == null) {
throw new TelegramApiException("Parameter sentCallback can not be null");
}
sendApiMethodAsync(getUserProfilePhotos, sentCallback);
}
public void getMeAsync(SentCallback<User> sentCallback) throws TelegramApiException {
if (sentCallback == null) {
throw new TelegramApiException("Parameter sentCallback can not be null");
}
GetMe getMe = new GetMe();
sendApiMethodAsync(getMe, sentCallback);
}
public Message sendDocument(SendDocument sendDocument) throws TelegramApiException {
String responseContent;
public static void SendDocument(SendDocument sendDocument, String botToken) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendDocument.PATH;
String url = getBaseUrl() + SendDocument.PATH;
HttpPost httppost = new HttpPost(url);
if (sendDocument.isNewDocument()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendDocument.CHATID_FIELD, sendDocument.getChatId());
builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName());
builder.addBinaryBody(SendDocument.DOCUMENT_FIELD, new java.io.File(sendDocument.getDocument()), ContentType.APPLICATION_OCTET_STREAM, sendDocument.getDocumentName());
if (sendDocument.getReplayMarkup() != null) {
builder.addTextBody(SendDocument.REPLYMARKUP_FIELD, sendDocument.getReplayMarkup().toJson().toString());
}
@ -70,26 +212,32 @@ public class SenderHelper {
}
CloseableHttpResponse response = httpClient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
responseContent = EntityUtils.toString(buf, "UTF-8");
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
} finally {
if (sendDocument.isNewDocument()) {
File fileToDelete = new File(sendDocument.getDocument());
fileToDelete.delete();
}
throw new TelegramApiException("Unable to send document", e);
}
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new TelegramApiException("Error at sendDocument", jsonObject.getString("description"));
}
return new Message(jsonObject);
}
public static void SendPhoto(SendPhoto sendPhoto, String botToken) {
public Message sendPhoto(SendPhoto sendPhoto) throws TelegramApiException {
String responseContent;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendPhoto.PATH;
String url = getBaseUrl() + SendPhoto.PATH;
HttpPost httppost = new HttpPost(url);
if (sendPhoto.isNewPhoto()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId());
builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName());
builder.addBinaryBody(SendPhoto.PHOTO_FIELD, new java.io.File(sendPhoto.getPhoto()), ContentType.APPLICATION_OCTET_STREAM, sendPhoto.getPhotoName());
if (sendPhoto.getReplayMarkup() != null) {
builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, sendPhoto.getReplayMarkup().toJson().toString());
}
@ -118,21 +266,32 @@ public class SenderHelper {
}
CloseableHttpResponse response = httpClient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
responseContent = EntityUtils.toString(buf, "UTF-8");
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
throw new TelegramApiException("Unable to send photo", e);
}
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new TelegramApiException("Error at sendPhoto", jsonObject.getString("description"));
}
return new Message(jsonObject);
}
public static void SendVideo(SendVideo sendVideo, String botToken) {
public Message sendVideo(SendVideo sendVideo) throws TelegramApiException {
String responseContent;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendVideo.PATH;
String url = getBaseUrl() + SendVideo.PATH;
HttpPost httppost = new HttpPost(url);
if (sendVideo.isNewVideo()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendVideo.CHATID_FIELD, sendVideo.getChatId());
builder.addBinaryBody(SendVideo.VIDEO_FIELD, new File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName());
builder.addBinaryBody(SendVideo.VIDEO_FIELD, new java.io.File(sendVideo.getVideo()), ContentType.APPLICATION_OCTET_STREAM, sendVideo.getVideoName());
if (sendVideo.getReplayMarkup() != null) {
builder.addTextBody(SendVideo.REPLYMARKUP_FIELD, sendVideo.getReplayMarkup().toJson().toString());
}
@ -167,21 +326,33 @@ public class SenderHelper {
}
CloseableHttpResponse response = httpClient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
responseContent = EntityUtils.toString(buf, "UTF-8");
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
throw new TelegramApiException("Unable to send video", e);
}
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new TelegramApiException("Error at sendVideo", jsonObject.getString("description"));
}
return new Message(jsonObject);
}
public static void sendSticker(SendSticker sendSticker, String botToken) {
public Message sendSticker(SendSticker sendSticker) throws TelegramApiException {
String responseContent;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = Constants.BASEURL + botToken + "/" + SendSticker.PATH;
String url = getBaseUrl() + SendSticker.PATH;
HttpPost httppost = new HttpPost(url);
if (sendSticker.isNewSticker()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId());
builder.addBinaryBody(SendSticker.STICKER_FIELD, new File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName());
builder.addBinaryBody(SendSticker.STICKER_FIELD, new java.io.File(sendSticker.getSticker()), ContentType.APPLICATION_OCTET_STREAM, sendSticker.getStickerName());
if (sendSticker.getReplayMarkup() != null) {
builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, sendSticker.getReplayMarkup().toJson().toString());
}
@ -204,68 +375,26 @@ public class SenderHelper {
}
CloseableHttpResponse response = httpClient.execute(httppost);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
} finally {
if (sendSticker.isNewSticker()) {
File fileToDelete = new File(sendSticker.getSticker());
fileToDelete.delete();
}
}
}
public static void SendWebhook(String webHookURL, String botToken, String publicCertificatePath, String publicCertificateName) {
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + "/" + SetWebhook.PATH;
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, webHookURL);
if (publicCertificatePath != null) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, new File(publicCertificatePath), ContentType.APPLICATION_OCTET_STREAM, publicCertificateName);
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
BotLogger.debug(LOGTAG, responseContent);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
}
public static void SendApiMethod(BotApiMethod method, String botToken) throws InvalidObjectException {
String responseContent = "{}";
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + "/" + method.getPath();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("charset", "UTF-8");
httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
responseContent = EntityUtils.toString(buf, "UTF-8");
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
throw new TelegramApiException("Unable to send sticker", e);
}
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new InvalidObjectException(jsonObject.getString("description"));
throw new TelegramApiException("Error at sendSticker", jsonObject.getString("description"));
}
return new Message(jsonObject);
}
public static void SendApiMethodAsync(BotApiMethod method, String botToken, SentCallback callback) {
private void sendApiMethodAsync(BotApiMethod method, SentCallback callback) {
exe.submit(() -> {
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + botToken + "/" + method.getPath();
String url = getBaseUrl() + method.getPath();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("charset", "UTF-8");
httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON));
@ -280,8 +409,36 @@ public class SenderHelper {
}
callback.onResult(method, jsonObject);
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
callback.onException(method, e);
}
});
}
private Serializable sendApiMethod(BotApiMethod method) throws TelegramApiException {
String responseContent;
try {
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = getBaseUrl() + method.getPath();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("charset", "UTF-8");
httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
responseContent = EntityUtils.toString(buf, "UTF-8");
} catch (IOException e) {
throw new TelegramApiException("Unable to execute " + method.getPath() + " method", e);
}
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new TelegramApiException("Error at " + method.getPath(), jsonObject.getString("description"));
}
return method.deserializeResponse(jsonObject);
}
private String getBaseUrl() {
return Constants.BASEURL + getBotToken() + "/";
}
}

View File

@ -0,0 +1,27 @@
package org.telegram.telegrambots.bots;
import org.telegram.telegrambots.api.objects.Update;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Callback to handle updates.
* @date 20 of June of 2015
*/
public interface ITelegramLongPollingBot {
/**
* This method is called when receiving updates via GetUpdates method
* @param update Update received
*/
void onUpdateReceived(Update update);
/**
* Return bot username of this bot
*/
String getBotUsername();
/**
* Return bot token to access Telegram API
*/
String getBotToken();
}

View File

@ -0,0 +1,34 @@
package org.telegram.telegrambots.bots;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.objects.Update;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Callback to handle updates.
* @date 20 of June of 2015
*/
public interface ITelegramWebhookBot {
/**
* This method is called when receiving updates via webhook
* @param update Update received
*/
BotApiMethod onWebhookUpdateReceived(Update update);
/**
* Return bot username of this bot
*/
String getBotUsername();
/**
* Return bot token to access Telegram API
*/
String getBotToken();
/**
* TODO
* @return
*/
String getBotPath();
}

View File

@ -0,0 +1,11 @@
package org.telegram.telegrambots.bots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief TODO
* @date 14 of January of 2016
*/
public abstract class TelegramLongPollingBot extends AbsSender implements ITelegramLongPollingBot {
}

View File

@ -0,0 +1,10 @@
package org.telegram.telegrambots.bots;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief TODO
* @date 14 of January of 2016
*/
public abstract class TelegramWebhookBot extends AbsSender implements ITelegramWebhookBot {
}

View File

@ -1,7 +1,9 @@
package org.telegram.updateshandlers;
package org.telegram.telegrambots.updateshandlers;
import org.json.JSONObject;
import org.telegram.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import java.io.Serializable;
/**
* @author Ruben Bermudez
@ -9,7 +11,7 @@ import org.telegram.api.methods.BotApiMethod;
* @brief Callback to execute api method asynchronously
* @date 10 of September of 2015
*/
public interface SentCallback<T> {
public interface SentCallback<T extends Serializable> {
/**
* Called when the request is successful
* @param method Method executed
@ -23,4 +25,11 @@ public interface SentCallback<T> {
* @param jsonObject Answer from Telegram server (contains error information)
*/
void onError(BotApiMethod<T> method, JSONObject jsonObject);
/**
* Called when the http request throw an exception
* @param method Method executed
* @param exception Excepction thrown
*/
void onException(BotApiMethod<T> method, Exception exception);
}

View File

@ -0,0 +1,52 @@
package org.telegram.telegrambots.updatesreceivers;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.ITelegramWebhookBot;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Rest api to for webhook callback function
* @date 20 of June of 2015
*/
@Path("callback")
class RestApi {
private final ConcurrentHashMap<String, ITelegramWebhookBot> callbacks = new ConcurrentHashMap<>();
public RestApi() {
}
public void registerCallback(ITelegramWebhookBot callback) {
if (!callbacks.containsKey(callback.getBotPath())) {
callbacks.put(callback.getBotPath(), callback);
}
}
@POST
@Path("/{botPath}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateReceived(@PathParam("botPath") String botPath, Update update) {
if (callbacks.containsKey(botPath)) {
return Response.ok(this.callbacks.get(botPath).onWebhookUpdateReceived(update)).build();
}
return Response.ok().build();
}
@GET
@Path("/{botPath}")
@Produces(MediaType.APPLICATION_JSON)
public String testReceived(@PathParam("botPath") String botPath) {
if (callbacks.containsKey(botPath)) {
return "Hi there " + botPath + "!";
} else {
return "Callback not found for " + botPath;
}
}
}

View File

@ -1,4 +1,4 @@
package org.telegram.updatesreceivers;
package org.telegram.telegrambots.updatesreceivers;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
@ -13,11 +13,10 @@ import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.api.objects.Update;
import org.telegram.api.methods.Constants;
import org.telegram.api.methods.GetUpdates;
import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.UpdatesCallback;
import org.telegram.telegrambots.api.Constants;
import org.telegram.telegrambots.api.methods.GetUpdates;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.ITelegramLongPollingBot;
import java.io.IOException;
import java.io.InvalidObjectException;
@ -31,16 +30,14 @@ import java.util.concurrent.TimeUnit;
* @date 20 of June of 2015
*/
public class UpdatesThread {
private static final String LOGTAG = "UPDATESTHREAD";
private final UpdatesCallback callback;
private final ITelegramLongPollingBot callback;
private final ReaderThread readerThread;
private final HandlerThread handlerThread;
private int lastReceivedUpdate = 0;
private String token;
private final ConcurrentLinkedDeque<Update> receivedUpdates = new ConcurrentLinkedDeque<>();
public UpdatesThread(String token, UpdatesCallback callback) {
public UpdatesThread(String token, ITelegramLongPollingBot callback) {
this.token = token;
this.callback = callback;
this.readerThread = new ReaderThread();
@ -65,7 +62,6 @@ public class UpdatesThread {
httpPost.addHeader("charset", "UTF-8");
httpPost.setEntity(new StringEntity(request.toJson().toString(), ContentType.APPLICATION_JSON));
HttpResponse response;
BotLogger.debug(LOGTAG, httpPost.toString());
response = httpclient.execute(httpPost);
HttpEntity ht = response.getEntity();
@ -78,7 +74,6 @@ public class UpdatesThread {
throw new InvalidObjectException(jsonObject.toString());
}
JSONArray jsonArray = jsonObject.getJSONArray("result");
BotLogger.debug(LOGTAG, jsonArray.toString());
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
Update update = new Update(jsonArray.getJSONObject(i));
@ -95,16 +90,12 @@ public class UpdatesThread {
synchronized (this) {
this.wait(500);
}
} catch (InterruptedException e) {
BotLogger.error(LOGTAG, e);
continue;
} catch (InterruptedException ignored) {
}
}
} catch (JSONException e) {
BotLogger.warn(LOGTAG, e);
} catch (JSONException ignored) {
}
} catch (IOException e) {
BotLogger.warn(LOGTAG, e);
} catch (IOException ignored) {
}
}
}
@ -122,7 +113,6 @@ public class UpdatesThread {
try {
receivedUpdates.wait();
} catch (InterruptedException e) {
BotLogger.error(LOGTAG, e);
continue;
}
update = receivedUpdates.pollLast();
@ -132,8 +122,7 @@ public class UpdatesThread {
}
}
callback.onUpdateReceived(update);
} catch (Exception e) {
BotLogger.error(LOGTAG, e);
} catch (Exception ignored) {
}
}
}

View File

@ -1,4 +1,4 @@
package org.telegram.updatesreceivers;
package org.telegram.telegrambots.updatesreceivers;
import com.sun.jersey.api.json.JSONConfiguration;
import org.glassfish.grizzly.http.server.HttpServer;
@ -7,8 +7,8 @@ import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.telegram.services.BotLogger;
import org.telegram.updateshandlers.UpdatesCallback;
import org.telegram.telegrambots.TelegramApiException;
import org.telegram.telegrambots.bots.ITelegramWebhookBot;
import java.io.IOException;
import java.net.URI;
@ -26,22 +26,20 @@ public class Webhook {
private final String KEYSTORE_SERVER_PWD;
private final RestApi restApi;
private final String externalUrl;
private final String internalUrl;
public Webhook(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) {
public Webhook(String keyStore, String keyStorePassword, String internalUrl) {
this.KEYSTORE_SERVER_FILE = keyStore;
this.KEYSTORE_SERVER_PWD = keyStorePassword;
this.externalUrl = externalUrl;
this.internalUrl = internalUrl;
this.restApi = new RestApi();
}
public void registerWebhook(UpdatesCallback callback, String botName) {
restApi.registerCallback(callback, botName);
public void registerWebhook(ITelegramWebhookBot callback) {
restApi.registerCallback(callback);
}
public void startServer() {
public void startServer() throws TelegramApiException {
SSLContextConfigurator sslContext = new SSLContextConfigurator();
// set up security context
@ -52,7 +50,6 @@ public class Webhook {
rc.register(restApi);
rc.register(JacksonFeature.class);
rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true);
BotLogger.info(LOGTAG, "Internal webhook: " + getBaseURI().toString());
final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(
getBaseURI(),
rc,
@ -61,22 +58,10 @@ public class Webhook {
try {
grizzlyServer.start();
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
throw new TelegramApiException("Error starting webhook server", e);
}
}
public void startDebugServer() {
ResourceConfig rc = new ResourceConfig();
rc.register(restApi);
rc.register(JacksonFeature.class);
rc.property(JSONConfiguration.FEATURE_POJO_MAPPING, true);
GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
}
public String getExternalURL(String botName) {
return String.format("%s/callback/%s", externalUrl, botName);
}
private URI getBaseURI() {
return URI.create(internalUrl);
}

View File

@ -1,24 +0,0 @@
package org.telegram.updateshandlers;
import org.telegram.api.objects.Update;
import org.telegram.api.methods.BotApiMethod;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Callback to handle updates. Must support both, single update and List of updates
* @date 20 of June of 2015
*/
public interface UpdatesCallback {
/**
* This method is called when receiving updates via org.telegram.api.methods.GetUpdates method
* @param update Update received
*/
void onUpdateReceived(Update update);
/**
* This method is called when receiving updates via webhook
* @param update Update received
*/
BotApiMethod onWebhookUpdateReceived(Update update);
}

View File

@ -1,52 +0,0 @@
package org.telegram.updatesreceivers;
import org.telegram.api.objects.Update;
import org.telegram.updateshandlers.UpdatesCallback;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Rest api to for webhook callback function
* @date 20 of June of 2015
*/
@Path("callback")
public class RestApi {
private final ConcurrentHashMap<String, UpdatesCallback> callbacks = new ConcurrentHashMap<>();
public RestApi() {
}
public void registerCallback(UpdatesCallback callback, String botName) {
if (!callbacks.containsKey(botName)) {
callbacks.put(botName, callback);
}
}
@POST
@Path("/{botname}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateReceived(@PathParam("botname") String botname, Update update) {
if (callbacks.containsKey(botname)) {
return Response.ok(this.callbacks.get(botname).onWebhookUpdateReceived(update)).build();
}
return Response.ok().build();
}
@GET
@Path("/{botname}")
@Produces(MediaType.APPLICATION_JSON)
public String testReceived(@PathParam("botname") String botname) {
if (callbacks.containsKey(botname)) {
return "Hi there " + botname + "!";
} else {
return "Callback not found for " + botname;
}
}
}