use of com.pengrad.telegrambot.model.Chat in project cryptonomica by Cryptonomica.
the class TelegramWebhookServlet method doPost.
/*
* to receive information using Telegram webhook ( Update object)
* Telegram: "Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url,
* containing a JSON-serialized Update. // see: Update object description on https://core.telegram.org/bots/api#update
* In case of an unsuccessful request, we will give up after a reasonable amount of attempts"
* https://core.telegram.org/bots/api#setwebhook
*
* */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TelegramBot cryptonomicaBot = TelegramBotFactory.getCryptonomicaBot();
// see:
// https://github.com/pengrad/java-telegram-bot-api#webhook
java.io.Reader reader = request.getReader();
// or from java.io.Reader
Update update = BotUtils.parseUpdate(reader);
Message message = update.message();
String messageText = message.text();
Integer message_id = message.messageId();
Chat chat = message.chat();
Long chat_id = chat.id();
String textToSend = null;
Keyboard replyMarkup = null;
if (messageText.equalsIgnoreCase("/start")) {
textToSend = "Hi, I'm Cryptonomica Bot.\n" + "Nice to meet you, " + message.from().firstName() + " " + message.from().lastName() + ". " + "if you need more info, type: /moreInfo \n" + "if you want to start from the beginning, type: /start \n";
// replyMarkup = new ForceReply();
replyMarkup = new ReplyKeyboardRemove();
} else if (messageText.equalsIgnoreCase("/moreInfo")) {
textToSend = "please visit my web-app: [Cryptonomica.net](https://cryptonomica.net) ";
// <<< needed!
replyMarkup = new ReplyKeyboardRemove();
} else if (message.chat().id() != TelegramBotFactory.getCryptonomicaAdminsChatId()) {
textToSend = "really, " + message.text() + "?\n";
// <<< needed!
replyMarkup = new ReplyKeyboardRemove();
}
if (textToSend != null) {
LOG.warning("sending message: " + textToSend + " to chat: " + message.chat().id() + " in respond to message '" + messageText + "' from " + message.from().username());
// see message params on
// https://core.telegram.org/bots/api#message
SendMessage sendMessageRequest = new SendMessage(// chat id
message.chat().id(), textToSend).parseMode(ParseMode.Markdown).disableWebPagePreview(false).disableNotification(// ?
false).replyToMessageId(message.messageId()).replyMarkup(replyMarkup);
LOG.warning(CollectionsService.mapToString(sendMessageRequest.getParameters()));
SendResponse sendResponse = cryptonomicaBot.execute(sendMessageRequest);
LOG.warning(sendResponse.toString());
}
ServletUtils.sendJsonResponse(response, "{}");
/*
// this works faster:
//
// check url key:
final String CryptonomicaBotTelegramUrlKey = ServletUtils.getUrlKey(request);
final String TELEGRAM_URL_KEY = ApiKeysUtils.getApiKey("CryptonomicaBotTelegramUrlKey");
if (!TELEGRAM_URL_KEY.equalsIgnoreCase(CryptonomicaBotTelegramUrlKey)) {
throw new ServletException("CryptonomicaBotTelegramUrlKey is invalid");
}
// Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update
// ( https://core.telegram.org/bots/api#setwebhook )
// Update is an object that represents an incoming update
// ( https://core.telegram.org/bots/api#update )
JSONObject updateJsonObject = ServletUtils.getJsonObjectFromRequestWithIOUtils(request);
JSONObject message = updateJsonObject.getJSONObject("message");
// message_id represented by int:
int message_id = message.getInt("message_id");
// the actual UTF-8 text of the message, 0-4096 characters.
String text = message.getString("text");
JSONObject chat = message.getJSONObject("chat");
// chat_id represented by int:
int chat_id = chat.getInt("id");
JSONObject from = message.getJSONObject("from");
LOG.warning("message: " + message.toString());
LOG.warning("message_id: " + message_id);
LOG.warning("message text: " + text);
LOG.warning("chat: " + chat.toString());
LOG.warning("chat_id: " + chat_id);
LOG.warning("from: " + from.toString());
// see:
// https://core.telegram.org/bots/api#sendmessage
Map<String, String> parameterMap = new HashMap<>();
String sendMessageText = "really, " + text + "?";
parameterMap.put("text", sendMessageText);
parameterMap.put("chat_id", Integer.toString(chat_id));
parameterMap.put("reply_to_message_id", Integer.toString(message_id));
HTTPResponse httpResponse = CryptonomicaBot.sendMessageWithParameterMap(parameterMap);
LOG.warning("httpResponse: " + httpResponse);
ServletUtils.sendJsonResponse(response, "O.K.");
*/
}
use of com.pengrad.telegrambot.model.Chat in project anton-pavlovich-bot by wyvie.
the class AbstractRemindCommand method sendMessage.
SendResponse sendMessage(Object id, String messageText, @Nullable ParseMode parseMode) {
String chatId;
if (id instanceof User) {
chatId = ((User) id).id().toString();
} else if (id instanceof Chat) {
chatId = ((Chat) id).id().toString();
} else {
logger.error("!!! Unknown type of id.");
return null;
}
logger.debug(">>> Sending message: " + messageText + " message size: " + messageText.length() + " to chat id: " + chatId);
SendMessage sendMessage = new SendMessage(chatId, messageText);
if (parseMode != null) {
sendMessage = sendMessage.parseMode(parseMode).disableWebPagePreview(true);
}
return telegramBot.execute(sendMessage);
}
use of com.pengrad.telegrambot.model.Chat in project anton-pavlovich-bot by wyvie.
the class RemindCommand method handle.
@Override
public void handle(Message message, String args) {
logger.debug("chat: " + message.chat().toString() + " from user");
Chat chat = message.chat();
if (!userCanPinEdit(botUser, chat)) {
sendMessage(chat, MAKE_BOT_ADMIN, ParseMode.HTML);
return;
}
User user = message.from();
List<String> tokenizedArgs = parseCommandArgs(args);
logger.debug("*** Tokenized arguments are: " + tokenizedArgs);
if (tokenizedArgs.isEmpty()) {
this.sendMessage(chat, USAGE, null);
return;
}
// list all notifications for this user in this chat
if (tokenizedArgs.get(0).equalsIgnoreCase("list")) {
sendMessage(user, getRemindersList(user, chat), ParseMode.HTML);
return;
}
// cancel task by id or cancel all tasks
if (tokenizedArgs.get(0).equalsIgnoreCase("cancel")) {
String id = tokenizedArgs.size() > 1 ? tokenizedArgs.get(1) : null;
cancelReminder(user, chat, id);
sendMessage(user, getRemindersList(user, chat), ParseMode.HTML);
return;
}
// continue with setting up reminder
long when;
try {
when = parseDateTimeToEpoch(tokenizedArgs.get(0));
} catch (DateTimeParseException e) {
sendMessage(chat, DATE_FORMAT_ERROR, ParseMode.HTML);
return;
}
String reminderText = tokenizedArgs.size() < 2 ? DEFAULT_REMINDER_TEXT : tokenizedArgs.stream().skip(1).collect(Collectors.joining(" "));
ScheduledFuture scheduledReminder = scheduleReminder(() -> {
long messageChatId = chat.id();
SendResponse response = sendMessage(chat, reminderText, null);
logger.debug("<<< Send Response: " + response.toString());
int messageToPinId = response.message().messageId();
PinChatMessage pinChatMessage = new PinChatMessage(messageChatId, messageToPinId);
BaseResponse pin = telegramBot.execute(pinChatMessage);
logger.debug("<<< Pin Response: " + pin.toString());
}, when);
// keep scheduled task reference for list or cancel
Reminder reminder = new Reminder(user, chat, tokenizedArgs.get(0), reminderText, scheduledReminder);
String key = sha256(args + scheduledReminder.toString());
scheduledNotifications.put(key, reminder);
sendMessage(chat, "Reminder created.", null);
logger.debug("*** Reminders list size: " + scheduledNotifications.size() + ", last one id: " + key + " set by user: " + user);
}
Aggregations