feat: add change language in welcome message (#2)
continuous-integration/drone/push Build is passing Details

Co-authored-by: Davide Polonio <poloniodavide@gmail.com>
Reviewed-on: #2
devel
Davide Polonio 2023-04-03 10:57:14 +02:00
parent cea9f3222a
commit 00bac97e59
35 changed files with 1466 additions and 253 deletions

View File

@ -1,2 +1,3 @@
MD013: MD013:
line_length: 120 line_length: 120
code_blocks: false

View File

@ -26,7 +26,9 @@ valid Telegram Bot token.
To configure Webhook configuration for your bot, open up a terminal and type: To configure Webhook configuration for your bot, open up a terminal and type:
```shell ```shell
curl -F "url=https://example.com/api/tg" https://api.telegram.org/bot<YOUR BOT TOKEN>/setWebhook curl -F "url=https://example.com/api/tg" \
-F "allowed_updates=[\"message\", \"edited_message\", \"channel_post\", \"edited_channel_post\", \"inline_query\", \"choosen_inline_result\", \"callback_query\", \"poll\", \"poll_answer\", \"my_chat_member\", \"chat_member\", \"chat_join_request\"]" \
https://api.telegram.org/bot<YOUR BOT TOKEN>/setWebhook
``` ```
## Building ## Building

View File

@ -40,6 +40,7 @@
<org.testcontainers.junit-jupiter.version>1.16.3</org.testcontainers.junit-jupiter.version> <org.testcontainers.junit-jupiter.version>1.16.3</org.testcontainers.junit-jupiter.version>
<jsonschema2pojo.version>1.1.1</jsonschema2pojo.version> <jsonschema2pojo.version>1.1.1</jsonschema2pojo.version>
<jackson-databind.version>2.13.3</jackson-databind.version> <jackson-databind.version>2.13.3</jackson-databind.version>
<junit-jupiter-params.version>5.9.1</junit-jupiter-params.version>
</properties> </properties>
<dependencies> <dependencies>
@ -68,6 +69,13 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit-jupiter-params.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>io.jooby</groupId> <groupId>io.jooby</groupId>
<artifactId>jooby-test</artifactId> <artifactId>jooby-test</artifactId>

View File

@ -0,0 +1,25 @@
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"$id": "http://example.com/example.json",
"type": "object",
"default": {},
"required": [
"event",
"telegramChatId"
],
"additionalProperties": true,
"properties": {
"event": {
"type": "string",
"default": ""
},
"messageId": {
"type": "number",
"default": 0
},
"telegramChatId": {
"type": "number",
"default": 0
}
}
}

View File

@ -3,6 +3,7 @@ package com.github.polpetta.mezzotre;
import com.github.polpetta.mezzotre.orm.di.Db; import com.github.polpetta.mezzotre.orm.di.Db;
import com.github.polpetta.mezzotre.route.Telegram; import com.github.polpetta.mezzotre.route.Telegram;
import com.github.polpetta.mezzotre.route.di.Route; import com.github.polpetta.mezzotre.route.di.Route;
import com.github.polpetta.mezzotre.telegram.callbackquery.di.CallbackQuery;
import com.github.polpetta.mezzotre.telegram.command.di.Command; import com.github.polpetta.mezzotre.telegram.command.di.Command;
import com.github.polpetta.mezzotre.util.di.ThreadPool; import com.github.polpetta.mezzotre.util.di.ThreadPool;
import com.google.inject.*; import com.google.inject.*;
@ -26,6 +27,7 @@ public class App extends Jooby {
modules.add(new ThreadPool()); modules.add(new ThreadPool());
modules.add(new Route()); modules.add(new Route());
modules.add(new Command()); modules.add(new Command());
modules.add(new CallbackQuery());
return modules; return modules;
}; };

View File

@ -1,6 +1,7 @@
package com.github.polpetta.mezzotre.i18n; package com.github.polpetta.mezzotre.i18n;
import java.util.Locale; import java.util.Locale;
import java.util.ResourceBundle;
import javax.inject.Inject; import javax.inject.Inject;
import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.JarResourceLoader; import org.apache.velocity.runtime.resource.loader.JarResourceLoader;
@ -11,8 +12,17 @@ import org.apache.velocity.tools.config.FactoryConfiguration;
import org.apache.velocity.tools.config.ToolConfiguration; import org.apache.velocity.tools.config.ToolConfiguration;
import org.apache.velocity.tools.config.ToolboxConfiguration; import org.apache.velocity.tools.config.ToolboxConfiguration;
/**
* This class provides utility to create {@link ToolManager} for {@link VelocityEngine} or to
* retrieve simple localized strings from the system.
*
* @author Davide Polonio
* @since 1.0
*/
public class LocalizedMessageFactory { public class LocalizedMessageFactory {
private static final String MESSAGE_PATH = "i18n/message";
private final VelocityEngine velocityEngine; private final VelocityEngine velocityEngine;
@Inject @Inject
@ -20,9 +30,15 @@ public class LocalizedMessageFactory {
this.velocityEngine = velocityEngine; this.velocityEngine = velocityEngine;
} }
public ToolManager create(Locale locale) { /**
* Provide a {@link ToolManager} completely setup. Localization will be taken from jar resources,
// properties.setProperty("file.resource.loader.class", FileResourceLoader.class.getName());. * and {@link LocalizedTool} can be used in Velocity templates to automatically access them.
*
* @param locale the language needed
* @return a {@link ToolManager} ready with the desired locale, if it exists. Fallback to english
* otherwise
*/
public ToolManager createVelocityToolManager(Locale locale) {
final ToolManager toolManager = new ToolManager(); final ToolManager toolManager = new ToolManager();
toolManager.setVelocityEngine(velocityEngine); toolManager.setVelocityEngine(velocityEngine);
@ -33,10 +49,20 @@ public class LocalizedMessageFactory {
toolConfiguration.setClassname(LocalizedTool.class.getName()); toolConfiguration.setClassname(LocalizedTool.class.getName());
toolConfiguration.setProperty("file.resource.loader.class", JarResourceLoader.class.getName()); toolConfiguration.setProperty("file.resource.loader.class", JarResourceLoader.class.getName());
toolConfiguration.setProperty(ToolContext.LOCALE_KEY, locale); toolConfiguration.setProperty(ToolContext.LOCALE_KEY, locale);
toolConfiguration.setProperty(LocalizedTool.BUNDLES_KEY, "i18n/message"); toolConfiguration.setProperty(LocalizedTool.BUNDLES_KEY, MESSAGE_PATH);
toolboxConfiguration.addTool(toolConfiguration); toolboxConfiguration.addTool(toolConfiguration);
factoryConfiguration.addToolbox(toolboxConfiguration); factoryConfiguration.addToolbox(toolboxConfiguration);
toolManager.configure(factoryConfiguration); toolManager.configure(factoryConfiguration);
return toolManager; return toolManager;
} }
/**
* Creates a {@link ResourceBundle} object that can be used to access single localized strings
*
* @param locale the language desired to retrieve the translated strings
* @return a {@link ResourceBundle} with the provided locale
*/
public ResourceBundle createResourceBundle(Locale locale) {
return ResourceBundle.getBundle(MESSAGE_PATH, locale);
}
} }

View File

@ -0,0 +1,75 @@
package com.github.polpetta.mezzotre.orm.model;
import com.github.polpetta.types.json.CallbackQueryMetadata;
import io.ebean.annotation.DbJson;
import io.ebean.annotation.Length;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
// Could be better to adopt redis? Seems too much overhead for now...
/**
* This entity allows for the push and retrieval of {@link CallbackQueryMetadata} related to a
* particular <i>InlineKeyboardButton</i>. {@link CallbackQueryMetadata} is a loosely-structured
* object, and this is by design: the fields stored in it depends on the metadata of the callback
* and on the type of event
*
* @author Davide Polonio
* @since 1.0
*/
@Entity
@Table(name = "callback_query_context")
public class CallbackQueryContext extends Base {
@Id
@Length(36)
private final String id;
/**
* Each callback can belong to a particular group. In that case, this variable will be the same
* for all the related {@link CallbackQueryMetadata}
*/
@NotNull
@Length(36)
private final String entryGroup;
@DbJson
@Column(columnDefinition = "json not null default '{}'::json")
@NotNull
private final CallbackQueryMetadata fields;
public CallbackQueryContext(String id, String entryGroup, CallbackQueryMetadata fields) {
this.id = id;
this.entryGroup = entryGroup;
this.fields = fields;
}
public String getId() {
return id;
}
public String getEntryGroup() {
return entryGroup;
}
public CallbackQueryMetadata getFields() {
return fields;
}
@Override
public String toString() {
return "CallbackQueryContext{"
+ "id='"
+ id
+ '\''
+ ", entryGroup='"
+ entryGroup
+ '\''
+ ", fields="
+ fields
+ '}';
}
}

View File

@ -3,7 +3,6 @@ package com.github.polpetta.mezzotre.orm.model;
import com.github.polpetta.types.json.ChatContext; import com.github.polpetta.types.json.ChatContext;
import io.ebean.annotation.DbJsonB; import io.ebean.annotation.DbJsonB;
import io.ebean.annotation.Length; import io.ebean.annotation.Length;
import javax.annotation.Nullable;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
@ -41,18 +40,13 @@ public class TgChat extends Base {
/** The locale to use when chatting. Defaults to {@code en-US} */ /** The locale to use when chatting. Defaults to {@code en-US} */
@NotNull @NotNull
@Length(5) @Length(10)
@Column(columnDefinition = "varchar(5) not null default 'en-US'") @Column(columnDefinition = "varchar(5) not null default 'en-US'")
private String locale; private String locale;
/** @NotNull
* See {@link #TgChat( Long, ChatContext, String)}. The default locale set here is {@code en-US} @Column(columnDefinition = "boolean default false")
*/ private Boolean hasHelpBeenShown;
public TgChat(Long id, ChatContext chatContext) {
this.id = id;
this.chatContext = chatContext;
this.locale = "en";
}
/** /**
* Build a new Telegram Chat * Build a new Telegram Chat
@ -61,11 +55,21 @@ public class TgChat extends Base {
* @param chatContext the context of the chat, where possible metadata can be stored. See {@link * @param chatContext the context of the chat, where possible metadata can be stored. See {@link
* ChatContext} * ChatContext}
* @param locale a specific locale for this chat * @param locale a specific locale for this chat
* @param hasHelpBeenShown boolean indicating if the user has seen the /help command at least once
*/ */
public TgChat(Long id, @Nullable ChatContext chatContext, String locale) { public TgChat(Long id, ChatContext chatContext, String locale, boolean hasHelpBeenShown) {
this.id = id; this.id = id;
this.chatContext = chatContext; this.chatContext = chatContext;
this.locale = locale; this.locale = locale;
this.hasHelpBeenShown = hasHelpBeenShown;
}
/**
* See {@link #TgChat( Long, ChatContext, String,boolean)}. The default locale set here is {@code
* en-US}, and {@link #hasHelpBeenShown} is set to {@code false}
*/
public TgChat(Long id, ChatContext chatContext) {
this(id, chatContext, "en-US", false);
} }
public Long getId() { public Long getId() {
@ -89,6 +93,14 @@ public class TgChat extends Base {
this.locale = locale; this.locale = locale;
} }
public Boolean getHasHelpBeenShown() {
return hasHelpBeenShown;
}
public void setHasHelpBeenShown(Boolean hasHelpBeenShown) {
this.hasHelpBeenShown = hasHelpBeenShown;
}
@Override @Override
public String toString() { public String toString() {
return "TgChat{" return "TgChat{"
@ -99,6 +111,8 @@ public class TgChat extends Base {
+ ", locale='" + ", locale='"
+ locale + locale
+ '\'' + '\''
+ ", isTutorialComplete="
+ hasHelpBeenShown
+ '}'; + '}';
} }
} }

View File

@ -1,10 +1,13 @@
package com.github.polpetta.mezzotre.route; package com.github.polpetta.mezzotre.route;
import com.github.polpetta.mezzotre.orm.model.TgChat; import com.github.polpetta.mezzotre.orm.model.TgChat;
import com.github.polpetta.mezzotre.orm.model.query.QCallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.query.QTgChat; import com.github.polpetta.mezzotre.orm.model.query.QTgChat;
import com.github.polpetta.mezzotre.telegram.callbackquery.Dispatcher;
import com.github.polpetta.mezzotre.telegram.command.Router; import com.github.polpetta.mezzotre.telegram.command.Router;
import com.github.polpetta.types.json.ChatContext; import com.github.polpetta.types.json.ChatContext;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.pengrad.telegrambot.model.CallbackQuery;
import com.pengrad.telegrambot.model.Message; import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.BaseRequest; import com.pengrad.telegrambot.request.BaseRequest;
@ -15,6 +18,7 @@ import io.jooby.annotations.Path;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.parameters.RequestBody; import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import javax.inject.Inject; import javax.inject.Inject;
@ -30,17 +34,20 @@ public class Telegram {
private final Gson gson; private final Gson gson;
private final Executor completableFutureThreadPool; private final Executor completableFutureThreadPool;
private final Router router; private final Router router;
private final Dispatcher dispatcher;
@Inject @Inject
public Telegram( public Telegram(
Logger log, Logger log,
Gson gson, Gson gson,
@Named("eventThreadPool") Executor completableFutureThreadPool, @Named("eventThreadPool") Executor completableFutureThreadPool,
Router router) { Router router,
Dispatcher dispatcher) {
this.log = log; this.log = log;
this.gson = gson; this.gson = gson;
this.completableFutureThreadPool = completableFutureThreadPool; this.completableFutureThreadPool = completableFutureThreadPool;
this.router = router; this.router = router;
this.dispatcher = dispatcher;
} }
@Operation( @Operation(
@ -51,33 +58,30 @@ public class Telegram {
requestBody = @RequestBody(required = true)) requestBody = @RequestBody(required = true))
@POST @POST
public CompletableFuture<String> incomingUpdate(Context context, Update update) { public CompletableFuture<String> incomingUpdate(Context context, Update update) {
return CompletableFuture.supplyAsync( /*
() -> { Steps:
1 - Retrieve the chat. If new chat, createVelocityToolManager and entry in the db
2 - Check if the incoming payload is an inline event (keyboard, query, ecc). Possibly check if there is any context previously saved in the database to retrieve. In that case, process the payload accordingly
3 - If it is not an inline event, then process it as an incoming message
*/
return CompletableFuture.completedFuture(update)
.thenComposeAsync(
ignored -> {
context.setResponseType(MediaType.JSON); context.setResponseType(MediaType.JSON);
log.trace(gson.toJson(update)); log.trace(gson.toJson(update));
final Message message = update.message(); if (update.message() != null) {
return new QTgChat() return processMessage(update);
.id }
.eq(message.chat().id())
.findOneOrEmpty() if (update.callbackQuery() != null) {
.map( return processCallBackQuery(update);
u -> { }
log.debug(
"Telegram chat " + u.getId() + " already registered in the database"); return CompletableFuture.failedFuture(
return u; new IllegalArgumentException("The given update is not formatted correctly"));
})
.orElseGet(
() -> {
final TgChat newTgChat = new TgChat(message.chat().id(), new ChatContext());
newTgChat.save();
log.trace(
"New Telegram chat " + newTgChat.getId() + " added into the database");
return newTgChat;
});
}, },
completableFutureThreadPool) completableFutureThreadPool)
.thenComposeAsync(tgChat -> router.process(tgChat, update), completableFutureThreadPool)
// See https://core.telegram.org/bots/faq#how-can-i-make-requests-in-response-to-updates // See https://core.telegram.org/bots/faq#how-can-i-make-requests-in-response-to-updates
.thenApply( .thenApply(
tgResponse -> { tgResponse -> {
@ -86,4 +90,45 @@ public class Telegram {
return response; return response;
}); });
} }
private CompletableFuture<Optional<BaseRequest<?, ?>>> processMessage(Update update) {
final Message message = update.message();
final TgChat tgChat =
new QTgChat()
.id
.eq(message.chat().id())
.findOneOrEmpty()
.map(
u -> {
log.debug("Telegram chat " + u.getId() + " already registered in the database");
return u;
})
.orElseGet(
() -> {
final TgChat newTgChat = new TgChat(message.chat().id(), new ChatContext());
newTgChat.save();
log.trace("New Telegram chat " + newTgChat.getId() + " added into the database");
return newTgChat;
});
return router.process(tgChat, update);
}
private CompletableFuture<Optional<BaseRequest<?, ?>>> processCallBackQuery(Update update) {
final CallbackQuery callbackQuery = update.callbackQuery();
return new QCallbackQueryContext()
.id
.eq(callbackQuery.data())
.findOneOrEmpty()
.map(
c -> {
log.debug("CallbackQuery " + c.getId() + " find in the database");
return dispatcher.dispatch(c, update);
})
.orElse(
CompletableFuture.failedFuture(
new IllegalStateException(
"No such callback query in our database " + callbackQuery.data())));
}
} }

View File

@ -0,0 +1,64 @@
package com.github.polpetta.mezzotre.telegram.callbackquery;
import com.github.polpetta.mezzotre.orm.model.CallbackQueryContext;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.BaseRequest;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
/**
* This class dispatches incoming {@link Update} containing a {@link
* com.pengrad.telegrambot.model.CallbackQuery} entry to the right {@link Processor} that will take
* care of processing them.
*
* @author Davide Polonio
* @since 1.0
*/
@Singleton
public class Dispatcher {
private final Set<Processor> tgEventProcessors;
private final Executor threadPool;
@Inject
public Dispatcher(
@Named("eventProcessors") Set<Processor> tgEventProcessors,
@Named("eventThreadPool") Executor threadPool) {
this.tgEventProcessors = tgEventProcessors;
this.threadPool = threadPool;
}
/**
* This method searches for the right {@link Processor} installed in the system. A {@link
* CallbackQueryContext} has to be previously saved in the database in order for this method to
* find the right event to process. Once the corresponding {@link Processor} is found, the
* computation is delegated to it
*
* @param callbackQueryContext the context coming from the database storage - cannot be null
* @param update the incoming {@link Update} coming from Telegram
* @return a {@link CompletableFuture} containing an {@link Optional} that may or not have a
* {@link BaseRequest} response to send back to Telegram.
*/
public CompletableFuture<Optional<BaseRequest<?, ?>>> dispatch(
CallbackQueryContext callbackQueryContext, Update update) {
return CompletableFuture.completedFuture(update)
.thenComposeAsync(
ignored ->
Optional.of(callbackQueryContext.getFields().getEvent())
.flatMap(
eventName ->
tgEventProcessors.stream()
// FIXME this is fucking stupid, why iterate over, just use a map!
// Make mapping at startup then we're gucci for the rest of the run
.filter(processor -> processor.getEventName().equals(eventName))
.findAny())
.map(processor -> processor.process(callbackQueryContext, update))
.orElse(CompletableFuture.failedFuture(new EventProcessorNotFoundException())),
threadPool);
}
}

View File

@ -0,0 +1,28 @@
package com.github.polpetta.mezzotre.telegram.callbackquery;
/**
* Wrapper exception when a valid {@link Processor} is not found in the system
*
* @author Davide Polonio
* @since 1.0
*/
public class EventProcessorNotFoundException extends RuntimeException {
public EventProcessorNotFoundException() {}
public EventProcessorNotFoundException(String message) {
super(message);
}
public EventProcessorNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public EventProcessorNotFoundException(Throwable cause) {
super(cause);
}
public EventProcessorNotFoundException(
String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -0,0 +1,38 @@
package com.github.polpetta.mezzotre.telegram.callbackquery;
import com.github.polpetta.mezzotre.orm.model.CallbackQueryContext;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.BaseRequest;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* A processor is an object which is able to process an incoming Telegram {@link Update} containing
* a {@link com.pengrad.telegrambot.model.CallbackQuery}. Any event of this type is related to a
* previous message.
*
* @author Davide Polonio
* @since 1.0
*/
public interface Processor {
/**
* The even name this processor is able to process
*
* @return a {@link String} containig the name of the event supported
*/
String getEventName();
/**
* Process the current event
*
* @param callbackQueryContext the corresponding even {@link CallbackQueryContext} previously
* stored in the database
* @param update the Telegram {@link Update} containing a {@link
* com.pengrad.telegrambot.model.CallbackQuery} incoming Telegram
* @return a {@link CompletableFuture} containing an {@link Optional} that may or maybe not have a
* {@link BaseRequest}, that is the response that will be sent back to Telegram
*/
CompletableFuture<Optional<BaseRequest<?, ?>>> process(
CallbackQueryContext callbackQueryContext, Update update);
}

View File

@ -0,0 +1,239 @@
package com.github.polpetta.mezzotre.telegram.callbackquery;
import com.github.polpetta.mezzotre.i18n.LocalizedMessageFactory;
import com.github.polpetta.mezzotre.orm.model.CallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.query.QCallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.query.QTgChat;
import com.github.polpetta.mezzotre.util.UUIDGenerator;
import com.github.polpetta.types.json.CallbackQueryMetadata;
import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.EditMessageText;
import com.pengrad.telegrambot.request.SendMessage;
import io.vavr.control.Try;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.util.StringBuilderWriter;
import org.slf4j.Logger;
/**
* SelectLanguageTutorial event is related to support locale change for a particular chat when the
* interaction with a new user starts
*
* @author Davide Polonio
* @since 1.0
*/
@Singleton
public class SelectLanguageTutorial implements Processor {
public static final String EVENT_NAME = "selectLanguageTutorial";
private final Executor threadPool;
private final LocalizedMessageFactory localizedMessageFactory;
private final Logger log;
private final UUIDGenerator uuidGenerator;
/**
* Additional fields that are related to {@code changeLanguage} event
*
* @author Davide Polonio
* @since 1.0
*/
public enum Field {
NewLanguage("newLanguage");
private final String name;
Field(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
/**
* Possible values for the additional {@link Field} of {@code changeLanguage} event
*
* @author Davide Polonio
* @since 1.0
*/
public enum Language {
English("en-US"),
Italian("it-IT");
private final String locale;
Language(String locale) {
this.locale = locale;
}
public String getLocale() {
return locale;
}
}
@Inject
public SelectLanguageTutorial(
@Named("eventThreadPool") Executor threadPool,
LocalizedMessageFactory localizedMessageFactory,
Logger log,
UUIDGenerator uuidGenerator) {
this.threadPool = threadPool;
this.localizedMessageFactory = localizedMessageFactory;
this.log = log;
this.uuidGenerator = uuidGenerator;
}
@Override
public String getEventName() {
return EVENT_NAME;
}
@Override
public CompletableFuture<Optional<BaseRequest<?, ?>>> process(
CallbackQueryContext callbackQueryContext, Update update) {
return CompletableFuture.supplyAsync(
() ->
Optional.of(callbackQueryContext.getFields().getTelegramChatId())
.map(Double::longValue)
// If we're desperate, search in the message for the chat id
.or(
() ->
Optional.ofNullable(update.callbackQuery().message())
.map(Message::messageId)
.map(Long::valueOf))
.filter(chatId -> chatId != 0L && chatId != Long.MIN_VALUE)
.flatMap(chatId -> new QTgChat().id.eq(chatId).findOneOrEmpty())
.map(
tgChat -> {
tgChat.setLocale(
(String)
callbackQueryContext
.getFields()
.getAdditionalProperties()
.getOrDefault(
Field.NewLanguage.getName(), tgChat.getLocale()));
tgChat.save();
log.trace(
"Locale for chat "
+ tgChat.getId()
+ " is now set in "
+ tgChat.getLocale());
return tgChat;
})
.orElseThrow(
() ->
new NoSuchElementException(
"Unable to find telegram chat "
+ Double.valueOf(
callbackQueryContext.getFields().getTelegramChatId())
.longValue()
+ " in the database")),
threadPool)
.thenApplyAsync(
// If we are here then we're sure there is at least a chat associated with this callback
tgChat -> {
final String message =
Try.of(
() -> {
final Locale locale = Locale.forLanguageTag(tgChat.getLocale());
final ToolManager toolManager =
localizedMessageFactory.createVelocityToolManager(locale);
final VelocityContext velocityContext =
new VelocityContext(toolManager.createContext());
velocityContext.put("hasHelpBeenShown", tgChat.getHasHelpBeenShown());
final StringBuilder content = new StringBuilder();
final StringBuilderWriter stringBuilderWriter =
new StringBuilderWriter(content);
toolManager
.getVelocityEngine()
.mergeTemplate(
"/template/callbackQuery/selectLanguageTutorial.vm",
StandardCharsets.UTF_8.name(),
velocityContext,
stringBuilderWriter);
stringBuilderWriter.close();
return content.toString();
})
.get();
log.trace("SelectLanguageTutorial event - message to send back: " + message);
final String callBackGroupToDelete = callbackQueryContext.getEntryGroup();
final int delete =
new QCallbackQueryContext().entryGroup.eq(callBackGroupToDelete).delete();
log.trace(
"Deleted "
+ delete
+ " entries regarding callback group "
+ callBackGroupToDelete);
final Optional<Integer> messageId =
Optional.ofNullable(update.callbackQuery().message()).map(Message::messageId);
BaseRequest<?, ?> baseRequest;
Optional<InlineKeyboardMarkup> helpButton = Optional.empty();
if (!tgChat.getHasHelpBeenShown()) {
// Add a button to show all the possible commands
final String showMeTutorialString =
localizedMessageFactory
.createResourceBundle(Locale.forLanguageTag(tgChat.getLocale()))
.getString("button.showMeTutorial");
final CallbackQueryMetadata callbackQueryMetadata =
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withEvent(ShowHelp.EVENT_NAME)
.withTelegramChatId(tgChat.getId())
.build();
final CallbackQueryContext callbackData =
new CallbackQueryContext(
uuidGenerator.generateAsString(),
uuidGenerator.generateAsString(),
callbackQueryMetadata);
callbackData.save();
helpButton =
Optional.of(
new InlineKeyboardMarkup(
new InlineKeyboardButton(showMeTutorialString)
.callbackData(callbackData.getId())));
}
if (messageId.isPresent()) {
log.trace("message id is present - editing old message");
final EditMessageText editMessageText =
new EditMessageText(tgChat.getId(), messageId.get(), message)
.parseMode(ParseMode.Markdown);
helpButton.ifPresent(editMessageText::replyMarkup);
baseRequest = editMessageText;
} else {
log.trace("no message id - sending a new message");
final SendMessage sendMessage =
new SendMessage(tgChat.getId(), message).parseMode(ParseMode.Markdown);
helpButton.ifPresent(sendMessage::replyMarkup);
baseRequest = sendMessage;
}
return Optional.of(baseRequest);
},
threadPool);
}
}

View File

@ -0,0 +1,26 @@
package com.github.polpetta.mezzotre.telegram.callbackquery;
import com.github.polpetta.mezzotre.orm.model.CallbackQueryContext;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.SendMessage;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class ShowHelp implements Processor {
public static String EVENT_NAME = "showHelp";
@Override
public String getEventName() {
return EVENT_NAME;
}
@Override
public CompletableFuture<Optional<BaseRequest<?, ?>>> process(
CallbackQueryContext callbackQueryContext, Update update) {
// TODO implement this method and put `hasHelpBeenShown` in tgChat to false
return CompletableFuture.completedFuture(
Optional.of(new SendMessage(callbackQueryContext.getFields().getTelegramChatId(), "TODO")));
}
}

View File

@ -0,0 +1,20 @@
package com.github.polpetta.mezzotre.telegram.callbackquery.di;
import com.github.polpetta.mezzotre.telegram.callbackquery.Processor;
import com.github.polpetta.mezzotre.telegram.callbackquery.SelectLanguageTutorial;
import com.github.polpetta.mezzotre.telegram.callbackquery.ShowHelp;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import java.util.Set;
import javax.inject.Named;
import javax.inject.Singleton;
public class CallbackQuery extends AbstractModule {
@Provides
@Singleton
@Named("eventProcessors")
public Set<Processor> getEventProcessor(
SelectLanguageTutorial selectLanguageTutorial, ShowHelp showHelp) {
return Set.of(selectLanguageTutorial, showHelp);
}
}

View File

@ -13,23 +13,22 @@ import java.util.concurrent.CompletableFuture;
* @author Davide Polonio * @author Davide Polonio
* @since 1.0 * @since 1.0
*/ */
public interface Executor { public interface Processor {
/** /**
* Provides the keyword to trigger this executor. Note that it must start with "/" at the * Provides the keyword to trigger this executor. Note that it must start with "/" at the
* beginning, e.g. {@code /start}. * beginning, e.g. {@code /start}.
* *
* @return a {@link String} providing the keyword to trigger the current {@link Executor} * @return a {@link String} providing the keyword to trigger the current {@link Processor}
*/ */
String getTriggerKeyword(); String getTriggerKeyword();
/** /**
* Process the current update * Process the current update
* *
* @param chat the chat the {@link Executor} is currently replying to * @param chat the chat the {@link Processor} is currently replying to
* @param update the update to process * @param update the update to process
* @return a {@link CompletableFuture} with the result of the computation * @return a {@link CompletableFuture} with the result of the computation
*/ */
// FIXME cannot be void - we don't want pesky side effects!
CompletableFuture<Optional<BaseRequest<?, ?>>> process(TgChat chat, Update update); CompletableFuture<Optional<BaseRequest<?, ?>>> process(TgChat chat, Update update);
} }

View File

@ -8,11 +8,12 @@ import com.pengrad.telegrambot.request.BaseRequest;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import javax.inject.Named; import javax.inject.Named;
/** /**
* This class has the goal of dispatching incoming {@link Update} events to the right {@link * This class has the goal of dispatching incoming {@link Update} events to the right {@link
* Executor}, that will provide an adequate response. * Processor}, that will provide an adequate response.
* *
* @author Davide Polonio * @author Davide Polonio
* @since 1.0 * @since 1.0
@ -20,31 +21,30 @@ import javax.inject.Named;
@Singleton @Singleton
public class Router { public class Router {
private final Set<Executor> tgExecutors; private final Set<Processor> tgCommandProcessors;
private final java.util.concurrent.Executor threadPool; private final Executor threadPool;
@Inject @Inject
public Router( public Router(
@Named("commands") Set<Executor> tgExecutors, @Named("commandProcessor") Set<Processor> tgCommandProcessors,
@Named("eventThreadPool") java.util.concurrent.Executor threadPool) { @Named("eventThreadPool") Executor threadPool) {
this.tgExecutors = tgExecutors; this.tgCommandProcessors = tgCommandProcessors;
this.threadPool = threadPool; this.threadPool = threadPool;
} }
/** /**
* Process the incoming {@link Update}. If no suitable {@link Executor} is able to process the * Process the incoming {@link Update}. If no suitable {@link Processor} is able to process the
* command, then {@link CommandNotFoundException} is used to signal this event. * command, then {@link CommandNotFoundException} is used to signal this event.
* *
* @param update the update coming from Telegram Servers * @param update the update coming from Telegram Servers
* @return a {@link CompletableFuture} that is marked as failure and containing a {@link * @return a {@link CompletableFuture} that is marked as failure and containing a {@link
* CommandNotFoundException} exception if no suitable {@link Executor} is found * CommandNotFoundException} exception if no suitable {@link Processor} is found
*/ */
public CompletableFuture<Optional<BaseRequest<?, ?>>> process(TgChat chat, Update update) { public CompletableFuture<Optional<BaseRequest<?, ?>>> process(TgChat chat, Update update) {
// This way exceptions are always under control // This way exceptions are always under control
return CompletableFuture.completedStage(update) return CompletableFuture.completedFuture(update)
.toCompletableFuture()
.thenComposeAsync( .thenComposeAsync(
up -> ignored ->
/* /*
Brief explanation of this chain: Brief explanation of this chain:
1 - Check if the message has a command in it (e.g. "/start hey!") 1 - Check if the message has a command in it (e.g. "/start hey!")
@ -53,17 +53,19 @@ public class Router {
could be in (maybe we're continuing a chat from previous messages?) could be in (maybe we're continuing a chat from previous messages?)
2.a - If there's a context with a valid stage, then continue with it 2.a - If there's a context with a valid stage, then continue with it
*/ */
Optional.of(up.message().text().split(" ")) Optional.of(update.message().text().split(" "))
.filter(list -> list.length > 0) .filter(list -> list.length > 0)
.map(list -> list[0]) .map(list -> list[0])
.filter(wannabeCommand -> wannabeCommand.startsWith("/")) .filter(wannabeCommand -> wannabeCommand.startsWith("/"))
.or(() -> Optional.ofNullable(chat.getChatContext().getStage())) .or(() -> Optional.ofNullable(chat.getChatContext().getStage()))
.flatMap( .flatMap(
command -> command ->
tgExecutors.stream() tgCommandProcessors.stream()
// FIXME this is fucking stupid, why iterate over, just use a map!
// Make mapping at startup then we're gucci for the rest of the run
.filter(ex -> ex.getTriggerKeyword().equals(command)) .filter(ex -> ex.getTriggerKeyword().equals(command))
.findAny()) .findAny())
.map(executor -> executor.process(chat, up)) .map(executor -> executor.process(chat, update))
.orElse(CompletableFuture.failedFuture(new CommandNotFoundException())), .orElse(CompletableFuture.failedFuture(new CommandNotFoundException())),
threadPool); threadPool);
} }

View File

@ -1,10 +1,17 @@
package com.github.polpetta.mezzotre.telegram.command; package com.github.polpetta.mezzotre.telegram.command;
import com.github.polpetta.mezzotre.i18n.LocalizedMessageFactory; import com.github.polpetta.mezzotre.i18n.LocalizedMessageFactory;
import com.github.polpetta.mezzotre.orm.model.CallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.TgChat; import com.github.polpetta.mezzotre.orm.model.TgChat;
import com.github.polpetta.mezzotre.telegram.callbackquery.SelectLanguageTutorial;
import com.github.polpetta.mezzotre.util.Clock;
import com.github.polpetta.mezzotre.util.UUIDGenerator;
import com.github.polpetta.types.json.CallbackQueryMetadata;
import com.github.polpetta.types.json.ChatContext; import com.github.polpetta.types.json.ChatContext;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.model.request.ParseMode; import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.request.BaseRequest; import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.SendMessage; import com.pengrad.telegrambot.request.SendMessage;
@ -13,6 +20,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Locale; import java.util.Locale;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
@ -21,26 +29,32 @@ import org.apache.velocity.util.StringBuilderWriter;
import org.slf4j.Logger; import org.slf4j.Logger;
/** /**
* This {@link Executor} has the goal to greet a user that typed {@code /start} to the bot. * This {@link Processor} has the goal to greet a user that typed {@code /start} to the bot.
* *
* @author Davide Polonio * @author Davide Polonio
* @since 1.0 * @since 1.0
*/ */
@Singleton @Singleton
public class Start implements Executor { public class Start implements Processor {
private final java.util.concurrent.Executor threadPool; private final Executor threadPool;
private final Logger log; private final Logger log;
private final UUIDGenerator uuidGenerator;
private final Clock clock;
private final LocalizedMessageFactory localizedMessageFactory; private final LocalizedMessageFactory localizedMessageFactory;
@Inject @Inject
public Start( public Start(
LocalizedMessageFactory localizedMessageFactory, LocalizedMessageFactory localizedMessageFactory,
@Named("eventThreadPool") java.util.concurrent.Executor threadPool, @Named("eventThreadPool") Executor threadPool,
Logger log) { Logger log,
UUIDGenerator uuidGenerator,
Clock clock) {
this.localizedMessageFactory = localizedMessageFactory; this.localizedMessageFactory = localizedMessageFactory;
this.threadPool = threadPool; this.threadPool = threadPool;
this.log = log; this.log = log;
this.uuidGenerator = uuidGenerator;
this.clock = clock;
} }
@Override @Override
@ -62,20 +76,21 @@ public class Start implements Executor {
Try.of( Try.of(
() -> { () -> {
final Locale locale = Locale.forLanguageTag(chat.getLocale()); final Locale locale = Locale.forLanguageTag(chat.getLocale());
final ToolManager toolContext = localizedMessageFactory.create(locale); final ToolManager toolManager =
localizedMessageFactory.createVelocityToolManager(locale);
final VelocityContext context = final VelocityContext context =
new VelocityContext(toolContext.createContext()); new VelocityContext(toolManager.createContext());
context.put("firstName", update.message().chat().firstName()); context.put("firstName", update.message().chat().firstName());
context.put("programName", "Mezzotre"); context.put("programName", "_Mezzotre_");
final StringBuilder content = new StringBuilder(); final StringBuilder content = new StringBuilder();
final StringBuilderWriter stringBuilderWriter = final StringBuilderWriter stringBuilderWriter =
new StringBuilderWriter(content); new StringBuilderWriter(content);
toolContext toolManager
.getVelocityEngine() .getVelocityEngine()
.mergeTemplate( .mergeTemplate(
"template/command/start.vm", "template/command/start.0.vm",
StandardCharsets.UTF_8.name(), StandardCharsets.UTF_8.name(),
context, context,
stringBuilderWriter); stringBuilderWriter);
@ -87,14 +102,61 @@ public class Start implements Executor {
log.trace("Start command - message to send back: " + message); log.trace("Start command - message to send back: " + message);
final ChatContext chatContext = chat.getChatContext(); final ChatContext chatContext = chat.getChatContext();
chatContext.setLastMessageSentId(update.message().messageId());
chatContext.setStage(getTriggerKeyword()); chatContext.setStage(getTriggerKeyword());
chatContext.setStep(0); chatContext.setStep(0);
chatContext.setPreviousMessageUnixTimestampInSeconds(update.message().date()); chatContext.setPreviousMessageUnixTimestampInSeconds(clock.now());
chat.setChatContext(chatContext); chat.setChatContext(chatContext);
chat.save(); chat.save();
return Optional.of(new SendMessage(chat.getId(), message).parseMode(ParseMode.Markdown)); // To get the messageId we should send the message first, then save it in the database!
final String groupId = uuidGenerator.generateAsString();
final CallbackQueryContext switchToEnglish =
new CallbackQueryContext(
uuidGenerator.generateAsString(),
groupId,
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withEvent(SelectLanguageTutorial.EVENT_NAME)
.withTelegramChatId(update.message().chat().id())
.withAdditionalProperty(
SelectLanguageTutorial.Field.NewLanguage.getName(),
SelectLanguageTutorial.Language.English.getLocale())
.build());
final CallbackQueryContext switchToItalian =
new CallbackQueryContext(
uuidGenerator.generateAsString(),
groupId,
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withEvent(SelectLanguageTutorial.EVENT_NAME)
.withTelegramChatId(update.message().chat().id())
.withAdditionalProperty(
SelectLanguageTutorial.Field.NewLanguage.getName(),
SelectLanguageTutorial.Language.Italian.getLocale())
.build());
final String englishButton =
localizedMessageFactory
.createResourceBundle(Locale.US)
.getString("changeLanguage.english");
final String italianButton =
localizedMessageFactory
.createResourceBundle(Locale.ITALY)
.getString("changeLanguage.italian");
final SendMessage messageToSend =
new SendMessage(chat.getId(), message)
.parseMode(ParseMode.Markdown)
.replyMarkup(
new InlineKeyboardMarkup(
new InlineKeyboardButton(englishButton)
.callbackData(switchToEnglish.getId()),
new InlineKeyboardButton(italianButton)
.callbackData(switchToItalian.getId())));
switchToEnglish.save();
switchToItalian.save();
return Optional.of(messageToSend);
}, },
threadPool); threadPool);
} }

View File

@ -1,6 +1,6 @@
package com.github.polpetta.mezzotre.telegram.command.di; package com.github.polpetta.mezzotre.telegram.command.di;
import com.github.polpetta.mezzotre.telegram.command.Executor; import com.github.polpetta.mezzotre.telegram.command.Processor;
import com.github.polpetta.mezzotre.telegram.command.Start; import com.github.polpetta.mezzotre.telegram.command.Start;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -14,8 +14,8 @@ import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
public class Command extends AbstractModule { public class Command extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
@Named("commands") @Named("commandProcessor")
public Set<Executor> getCommandExecutors(Start start) { public Set<Processor> getCommandProcessor(Start start) {
return Set.of(start); return Set.of(start);
} }

View File

@ -1,8 +1,18 @@
-- apply changes -- apply changes
create table callback_query_context (
id varchar(36) not null,
entry_group varchar(36) not null,
fields json not null default '{}'::json not null,
entry_created timestamptz not null,
entry_modified timestamptz not null,
constraint pk_callback_query_context primary key (id)
);
create table telegram_chat ( create table telegram_chat (
id bigint generated by default as identity not null, id bigint generated by default as identity not null,
chat_context jsonb not null default '{}'::jsonb not null, chat_context jsonb not null default '{}'::jsonb not null,
locale varchar(5) not null default 'en-US' not null, locale varchar(5) not null default 'en-US' not null,
has_help_been_shown boolean default false not null,
entry_created timestamptz not null, entry_created timestamptz not null,
entry_modified timestamptz not null, entry_modified timestamptz not null,
constraint pk_telegram_chat primary key (id) constraint pk_telegram_chat primary key (id)

View File

@ -1,3 +1,11 @@
start.hello=Hello start.helloFirstName=Hello {0}! \ud83d\udc4b
start.thisIs=This is start.description=This is {0}, a simple bot focused on DnD content management! Please start by choosing a language down below \ud83d\udc47
start.description=a simple bot focused on DnD content management! Please start by choosing a language down below. selectLanguageTutorial.drinkAction=*Proceeds to drink a potion with a strange, multicolor liquid*
selectLanguageTutorial.setLanguage=Thanks! Now that I drank this modified potion of {0} that I''ve found at the "Crystal Fermentary" magic potion shop yesterday I can speak with you in the language that you prefer!
selectLanguageTutorial.instructions=You can always change your language settings by typing /selectLanguageTutorial in the chat.
changeLanguage.english=English
changeLanguage.italian=Italian
spell.speakWithAnimals=Speak with animals
button.showMeTutorial=Show me what you can do!
help.notShownYet=It seems you haven''t checked out what I can do yet! To have a complete list of my abilities, type /help in chat at any time!
help.buttonBelow=Alternatively, you can click the button down below.

View File

@ -1,3 +1,11 @@
start.hello=Hello start.helloFirstName=Hello {0}! \ud83d\udc4b
start.thisIs=This is start.description=This is {0}, a simple bot focused on DnD content management! Please start by choosing a language down below \ud83d\udc47
start.description=a simple bot focused on DnD content management! Please start by choosing a language down below. selectLanguageTutorial.drinkAction=*Proceeds to drink a potion with a strange, multicolor liquid*
selectLanguageTutorial.setLanguage=Thanks! Now that I drank this modified potion of {0} that I''ve found at the "Crystal Fermentary" magic potion shop yesterday I can speak with you in the language that you prefer!
selectLanguageTutorial.instructions=You can always change your language settings by typing /selectLanguageTutorial in the chat.
selectLanguageTutorial.english=English
selectLanguageTutorial.italian=Italian
spell.speakWithAnimals=Speak with animals
button.showMeTutorial=Show me what you can do!
help.notShownYet=It seems you haven''t checked out what I can do yet! To have a complete list of my abilities, type /help in chat at any time!
help.buttonBelow=Alternatively, you can click the button down below.

View File

@ -1,3 +1,11 @@
start.hello=Ciao start.helloFirstName=Ciao {0}! \ud83d\udc4b
start.thisIs=Questo è start.description=Questo è {0}, un semplice bot che ci concenta sulla gestione di contenuto per DnD! Per favore comincia selezionando la lingua qui sotto \ud83d\udc47
start.description=un semplice bot che ci concenta sulla gestione di contenuto per DnD! Per favore comincia selezionando la lingua qui sotto selectLanguageTutorial.drinkAction=*Procede a bere una pozione al cui suo interno si trova uno strano liquido multicolore*
selectLanguageTutorial.setLanguage=Grazie! Ora che ho bevuto questa posizione modificata di {0} che ho trovato ieri al negozio di pozioni magiche la "Cristalleria Fermentatrice" posso parlare con te nel linguaggio che preferisci!
selectLanguageTutorial.instructions=Puoi sempre cambiare le preferenze della tua lingua scrivendo /selectLanguageTutorial nella chat.
selectLanguageTutorial.english=Inglese
selectLanguageTutorial.italian=Italiano
spell.speakWithAnimals=Parlare con animali
button.showMeTutorial=Mostrami cosa puoi fare!
help.notShownYet=Sembra tu non abbia ancora visto cosa posso fare! Per avere una lista completa delle mie abilità, scrivi /help nella chat in qualsiasi momento!
help.buttonBelow=Alternativamente, puoi premere il bottone qui sotto.

View File

@ -1,3 +1,11 @@
start.hello=Ciao start.helloFirstName=Ciao {0}! \ud83d\udc4b
start.thisIs=Questo è start.description=Questo è {0}, un semplice bot che ci concenta sulla gestione di contenuto per DnD! Per favore comincia selezionando la lingua qui sotto \ud83d\udc47
start.description=un semplice bot che ci concenta sulla gestione di contenuto per DnD! Per favore comincia selezionando la lingua qui sotto selectLanguageTutorial.drinkAction=*Procede a bere una pozione al cui suo interno si trova uno strano liquido multicolore*
selectLanguageTutorial.setLanguage=Grazie! Ora che ho bevuto questa posizione modificata di {0} che ho trovato ieri al negozio di pozioni magiche la "Cristalleria Fermentatrice" posso parlare con te nel linguaggio che preferisci!
selectLanguageTutorial.instructions=Puoi sempre cambiare le preferenze della tua lingua scrivendo /selectLanguageTutorial nella chat.
selectLanguageTutorial.english=Inglese
selectLanguageTutorial.italian=Italiano
spell.speakWithAnimals=Parlare con animali
button.showMeTutorial=Mostrami cosa puoi fare!
help.notShownYet=Sembra tu non abbia ancora visto cosa posso fare! Per avere una lista completa delle mie abilità, scrivi /help nella chat in qualsiasi momento!
help.buttonBelow=Alternativamente, puoi premere il bottone qui sotto.

View File

@ -0,0 +1,9 @@
_${i18n.selectLanguageTutorial.drinkAction}_
${i18n.selectLanguageTutorial.setLanguage.insert(${i18n.spell.speakWithAnimals})}
${i18n.selectLanguageTutorial.instructions}
#if(${hasHelpBeenShown} == false)
${i18n.help.notShownYet} ${i18n.help.buttonBelow}
#end

View File

@ -0,0 +1,3 @@
**${i18n.start.helloFirstName.insert(${firstName})}**
${i18n.start.description.insert(${programName})}

View File

@ -1,4 +0,0 @@
## https://velocity.apache.org/tools/2.0/apidocs/org/apache/velocity/tools/generic/ResourceTool.html
**$i18n.start.hello $firstName! 👋**
$i18n.start.thisIs _${programName}_, $i18n.start.description 👇

View File

@ -11,6 +11,9 @@ import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.util.Properties; import java.util.Properties;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.PostgreSQLContainer;
public class Loader { public class Loader {
@ -49,4 +52,13 @@ public class Loader {
public static Database connectToDatabase(Pair<Properties, Properties> connectionProperties) { public static Database connectToDatabase(Pair<Properties, Properties> connectionProperties) {
return connectToDatabase(connectionProperties.getLeft(), connectionProperties.getRight()); return connectToDatabase(connectionProperties.getLeft(), connectionProperties.getRight());
} }
public static VelocityEngine defaultVelocityEngine() {
final VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "classpath");
velocityEngine.setProperty(
"resource.loader.classpath.class", ClasspathResourceLoader.class.getName());
velocityEngine.init();
return velocityEngine;
}
} }

View File

@ -0,0 +1,108 @@
package com.github.polpetta.mezzotre.orm.model;
import static org.junit.jupiter.api.Assertions.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.polpetta.mezzotre.helper.Loader;
import com.github.polpetta.mezzotre.helper.TestConfig;
import com.github.polpetta.mezzotre.orm.model.query.QCallbackQueryContext;
import com.github.polpetta.mezzotre.util.Clock;
import com.github.polpetta.mezzotre.util.UUIDGenerator;
import com.github.polpetta.types.json.CallbackQueryMetadata;
import io.ebean.Database;
import io.ebean.SqlRow;
import java.sql.Timestamp;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@Tag("slow")
@Tag("database")
@Testcontainers
class CallbackQueryContextIntegrationTest {
private static ObjectMapper objectMapper;
private static UUIDGenerator uuidGenerator;
@Container
private final PostgreSQLContainer<?> postgresServer =
new PostgreSQLContainer<>(TestConfig.POSTGRES_DOCKER_IMAGE);
private Database database;
@BeforeAll
static void beforeAll() {
objectMapper = new ObjectMapper();
uuidGenerator = new UUIDGenerator();
}
@BeforeEach
void setUp() throws Exception {
database =
Loader.connectToDatabase(Loader.loadDefaultEbeanConfigWithPostgresSettings(postgresServer));
}
@Test
void shouldInsertEntryIntoDatabase() throws Exception {
final String uuidContext = uuidGenerator.generateAsString();
final String uuidGroup = uuidGenerator.generateAsString();
final CallbackQueryMetadata callbackQueryMetadata =
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withEvent("eventExample")
.withTelegramChatId(1234L)
.withMessageId(4242L)
.build();
final CallbackQueryContext callbackQueryContext =
new CallbackQueryContext(uuidContext, uuidGroup, callbackQueryMetadata);
callbackQueryContext.save();
final String query = "select * from callback_query_context where id = ?";
final SqlRow savedCallbackQueryContext =
database.sqlQuery(query).setParameter(uuidContext).findOne();
assertNotNull(savedCallbackQueryContext);
assertEquals(uuidGroup, savedCallbackQueryContext.getString("entry_group"));
assertEquals(uuidContext, savedCallbackQueryContext.getString("id"));
assertEquals(
objectMapper.writeValueAsString(callbackQueryMetadata),
savedCallbackQueryContext.getString("fields"));
}
@Test
void shouldRetrieveEntryInDatabase() throws Exception {
final Timestamp timestampFromUnixEpoch = Clock.getTimestampFromUnixEpoch(1L);
final String uuidId = uuidGenerator.generateAsString();
final String uuidEntryGroup = uuidGenerator.generateAsString();
final CallbackQueryMetadata callbackQueryMetadata =
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withEvent("eventExample")
.withTelegramChatId(12324L)
.withMessageId(42342L)
.build();
final String insertQuery = "insert into callback_query_context values (?, ?, ?::json, ?, ?)";
final int affectedRows =
database
.sqlUpdate(insertQuery)
.setParameter(uuidId)
.setParameter(uuidEntryGroup)
.setParameter(objectMapper.writeValueAsString(callbackQueryMetadata))
.setParameter(timestampFromUnixEpoch)
.setParameter(timestampFromUnixEpoch)
.execute();
assertEquals(1, affectedRows);
final CallbackQueryContext got = new QCallbackQueryContext().id.eq(uuidId).findOne();
assertNotNull(got);
final CallbackQueryMetadata gotFields = got.getFields();
assertNotNull(gotFields);
assertEquals("eventExample", gotFields.getEvent());
assertEquals(12324L, Double.valueOf(gotFields.getTelegramChatId()).longValue());
assertEquals(42342L, Double.valueOf(gotFields.getMessageId()).longValue());
}
}

View File

@ -54,7 +54,7 @@ class TgChatIntegrationTest {
.withPreviousMessageUnixTimestampInSeconds(42) .withPreviousMessageUnixTimestampInSeconds(42)
.build(); .build();
final TgChat user = new TgChat(1234L, chatContext, "en"); final TgChat user = new TgChat(1234L, chatContext, "en", false);
user.save(); user.save();
final String query = "select * from telegram_chat where id = ?"; final String query = "select * from telegram_chat where id = ?";
@ -63,6 +63,7 @@ class TgChatIntegrationTest {
assertNotNull(savedChat); assertNotNull(savedChat);
assertEquals(1234L, savedChat.getLong("id")); assertEquals(1234L, savedChat.getLong("id"));
assertEquals("en", savedChat.getString("locale")); assertEquals("en", savedChat.getString("locale"));
assertFalse(savedChat.getBoolean("has_help_been_shown"));
assertNotNull(savedChat.get("chat_context")); assertNotNull(savedChat.get("chat_context"));
assertEquals("jsonb", ((PGobject) savedChat.get("chat_context")).getType()); assertEquals("jsonb", ((PGobject) savedChat.get("chat_context")).getType());
assertEquals( assertEquals(
@ -82,13 +83,14 @@ class TgChatIntegrationTest {
.withPreviousMessageUnixTimestampInSeconds(42) .withPreviousMessageUnixTimestampInSeconds(42)
.build(); .build();
final String insertQuery = "insert into telegram_chat values (?, ?::jsonb, ?, ?, ?)"; final String insertQuery = "insert into telegram_chat values (?, ?::jsonb, ?, ?, ?, ?)";
final int affectedRows = final int affectedRows =
database database
.sqlUpdate(insertQuery) .sqlUpdate(insertQuery)
.setParameter(1234L) .setParameter(1234L)
.setParameter(objectMapper.writeValueAsString(chatContext)) .setParameter(objectMapper.writeValueAsString(chatContext))
.setParameter("en-US") .setParameter("en-US")
.setParameter(false)
.setParameter(timestampFromUnixEpoch) .setParameter(timestampFromUnixEpoch)
.setParameter(timestampFromUnixEpoch) .setParameter(timestampFromUnixEpoch)
.execute(); .execute();
@ -97,6 +99,7 @@ class TgChatIntegrationTest {
final TgChat got = new QTgChat().id.eq(1234L).findOne(); final TgChat got = new QTgChat().id.eq(1234L).findOne();
assertNotNull(got); assertNotNull(got);
assertFalse(got.getHasHelpBeenShown());
final ChatContext gotChatContext = got.getChatContext(); final ChatContext gotChatContext = got.getChatContext();
assertNotNull(gotChatContext); assertNotNull(gotChatContext);
assertEquals("/start", gotChatContext.getStage()); assertEquals("/start", gotChatContext.getStage());

View File

@ -6,14 +6,16 @@ import static org.mockito.Mockito.*;
import com.github.polpetta.mezzotre.helper.Loader; import com.github.polpetta.mezzotre.helper.Loader;
import com.github.polpetta.mezzotre.helper.TestConfig; import com.github.polpetta.mezzotre.helper.TestConfig;
import com.github.polpetta.mezzotre.orm.model.CallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.TgChat; import com.github.polpetta.mezzotre.orm.model.TgChat;
import com.github.polpetta.mezzotre.telegram.callbackquery.Dispatcher;
import com.github.polpetta.mezzotre.telegram.command.Router; import com.github.polpetta.mezzotre.telegram.command.Router;
import com.github.polpetta.types.json.CallbackQueryMetadata;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.SendMessage; import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import io.ebean.Database; import io.ebean.Database;
import io.jooby.Context; import io.jooby.Context;
import io.jooby.MediaType; import io.jooby.MediaType;
@ -42,6 +44,7 @@ class TelegramIntegrationTest {
private Telegram telegram; private Telegram telegram;
private TelegramBot fakeTelegramBot; private TelegramBot fakeTelegramBot;
private Router fakeRouter; private Router fakeRouter;
private Dispatcher fakeDispatcher;
@BeforeAll @BeforeAll
static void beforeAll() { static void beforeAll() {
@ -55,13 +58,15 @@ class TelegramIntegrationTest {
fakeTelegramBot = mock(TelegramBot.class); fakeTelegramBot = mock(TelegramBot.class);
fakeRouter = mock(Router.class); fakeRouter = mock(Router.class);
fakeDispatcher = mock(Dispatcher.class);
telegram = telegram =
new Telegram( new Telegram(
LoggerFactory.getLogger(getClass()), LoggerFactory.getLogger(getClass()),
new GsonBuilder().setPrettyPrinting().create(), new GsonBuilder().setPrettyPrinting().create(),
Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(),
fakeRouter); fakeRouter,
fakeDispatcher);
} }
@Test @Test
@ -72,9 +77,6 @@ class TelegramIntegrationTest {
when(fakeRouter.process(any(TgChat.class), any(Update.class))) when(fakeRouter.process(any(TgChat.class), any(Update.class)))
.thenReturn(CompletableFuture.completedFuture(Optional.of(expectedBaseRequest))); .thenReturn(CompletableFuture.completedFuture(Optional.of(expectedBaseRequest)));
final SendResponse fakeResponse = mock(SendResponse.class);
when(fakeResponse.isOk()).thenReturn(true);
when(fakeTelegramBot.execute(any(SendMessage.class))).thenReturn(fakeResponse);
final Context fakeContext = mock(Context.class); final Context fakeContext = mock(Context.class);
final Update update = final Update update =
gson.fromJson( gson.fromJson(
@ -100,11 +102,57 @@ class TelegramIntegrationTest {
+ "}\n" + "}\n"
+ "}\n", + "}\n",
Update.class); Update.class);
final CompletableFuture<String> integerCompletableFuture = final CompletableFuture<String> gotResponseFuture =
telegram.incomingUpdate(fakeContext, update); telegram.incomingUpdate(fakeContext, update);
final String gotReply = gotResponseFuture.get();
verify(fakeContext, times(1)).setResponseType(MediaType.JSON); verify(fakeContext, times(1)).setResponseType(MediaType.JSON);
final String gotReply = integerCompletableFuture.get(); verify(fakeRouter, times(1)).process(any(), any());
assertDoesNotThrow(() -> gotReply); verify(fakeDispatcher, times(0)).dispatch(any(), any());
assertEquals(expectedBaseRequest.toWebhookResponse(), gotReply);
}
@Test
@Timeout(value = 1, unit = TimeUnit.MINUTES)
void shouldProcessAnIncomingCallbackQueryThatExistsInTheDb() throws Exception {
final SendMessage expectedBaseRequest = new SendMessage(1111111, "Hello world");
when(fakeDispatcher.dispatch(any(CallbackQueryContext.class), any(Update.class)))
.thenReturn(CompletableFuture.completedFuture(Optional.of(expectedBaseRequest)));
final CallbackQueryContext callbackQueryContext =
new CallbackQueryContext(
"41427473-0d81-40a8-af60-9517163615a4",
"2ee7f5c6-93f0-4859-b902-af9476cf74ad",
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withTelegramChatId(666L)
.withMessageId(42L)
.withEvent("testEvent")
.build());
callbackQueryContext.save();
final Context fakeContext = mock(Context.class);
final Update update =
gson.fromJson(
"{\n"
+ "\"update_id\":10000,\n"
+ "\"callback_query\":{\n"
+ " \"id\": \"4382bfdwdsb323b2d9\",\n"
+ " \"from\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"type\": \"private\",\n"
+ " \"id\":1111111,\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"data\": \"41427473-0d81-40a8-af60-9517163615a4\",\n"
+ " \"inline_message_id\": \"1234csdbsk4839\"\n"
+ "}\n"
+ "}",
Update.class);
final CompletableFuture<String> gotResponseFuture =
telegram.incomingUpdate(fakeContext, update);
final String gotReply = gotResponseFuture.get();
verify(fakeContext, times(1)).setResponseType(MediaType.JSON);
verify(fakeRouter, times(0)).process(any(), any());
verify(fakeDispatcher, times(1)).dispatch(eq(callbackQueryContext), any());
assertEquals(expectedBaseRequest.toWebhookResponse(), gotReply); assertEquals(expectedBaseRequest.toWebhookResponse(), gotReply);
} }
} }

View File

@ -0,0 +1,338 @@
package com.github.polpetta.mezzotre.telegram.callbackquery;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.github.polpetta.mezzotre.helper.Loader;
import com.github.polpetta.mezzotre.helper.TestConfig;
import com.github.polpetta.mezzotre.i18n.LocalizedMessageFactory;
import com.github.polpetta.mezzotre.orm.model.CallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.TgChat;
import com.github.polpetta.mezzotre.orm.model.query.QCallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.query.QTgChat;
import com.github.polpetta.mezzotre.util.UUIDGenerator;
import com.github.polpetta.types.json.CallbackQueryMetadata;
import com.github.polpetta.types.json.ChatContext;
import com.google.gson.Gson;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.EditMessageText;
import com.pengrad.telegrambot.request.SendMessage;
import io.ebean.Database;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@Tag("slow")
@Tag("database")
@Tag("velocity")
@Testcontainers
class SelectLanguageTutorialIntegrationTest {
private static Gson gson;
@Container
private final PostgreSQLContainer<?> postgresServer =
new PostgreSQLContainer<>(TestConfig.POSTGRES_DOCKER_IMAGE);
private Database database;
private SelectLanguageTutorial selectLanguageTutorial;
private UUIDGenerator fakeUUIDGenerator;
@BeforeAll
static void beforeAll() {
gson = new Gson();
}
@BeforeEach
void setUp() throws Exception {
database =
Loader.connectToDatabase(Loader.loadDefaultEbeanConfigWithPostgresSettings(postgresServer));
fakeUUIDGenerator = mock(UUIDGenerator.class);
selectLanguageTutorial =
new SelectLanguageTutorial(
Executors.newSingleThreadExecutor(),
new LocalizedMessageFactory(Loader.defaultVelocityEngine()),
LoggerFactory.getLogger(SelectLanguageTutorial.class),
fakeUUIDGenerator);
}
private static Stream<Arguments> getTestLocales() {
return Stream.of(
Arguments.of(
SelectLanguageTutorial.Language.Italian,
"_*Procede a bere una pozione al cui suo interno si trova uno strano liquido"
+ " multicolore*_\n"
+ "\n"
+ "Grazie! Ora che ho bevuto questa posizione modificata di Parlare con animali che"
+ " ho trovato ieri al negozio di pozioni magiche la \"Cristalleria Fermentatrice\""
+ " posso parlare con te nel linguaggio che preferisci!\n"
+ "\n"
+ "Puoi sempre cambiare le preferenze della tua lingua scrivendo"
+ " /selectLanguageTutorial nella chat.\n"
+ "\n"
+ "Sembra tu non abbia ancora visto cosa posso fare! Per avere una lista completa"
+ " delle mie abilità, scrivi /help nella chat in qualsiasi momento!"
+ " Alternativamente, puoi premere il bottone qui sotto.\n",
"en-US",
"Mostrami cosa puoi fare!",
false),
Arguments.of(
SelectLanguageTutorial.Language.English,
"_*Proceeds to drink a potion with a strange, multicolor liquid*_\n"
+ "\n"
+ "Thanks! Now that I drank this modified potion of Speak with animals that I've"
+ " found at the \"Crystal Fermentary\" magic potion shop yesterday I can speak"
+ " with you in the language that you prefer!\n"
+ "\n"
+ "You can always change your language settings by typing /selectLanguageTutorial"
+ " in the chat.\n"
+ "\n"
+ "It seems you haven't checked out what I can do yet! To have a complete list of"
+ " my abilities, type /help in chat at any time! Alternatively, you can click the"
+ " button down below.\n",
"it-IT",
"Show me what you can do!",
false),
Arguments.of(
SelectLanguageTutorial.Language.Italian,
"_*Procede a bere una pozione al cui suo interno si trova uno strano liquido"
+ " multicolore*_\n"
+ "\n"
+ "Grazie! Ora che ho bevuto questa posizione modificata di Parlare con animali che"
+ " ho trovato ieri al negozio di pozioni magiche la \"Cristalleria Fermentatrice\""
+ " posso parlare con te nel linguaggio che preferisci!\n"
+ "\n"
+ "Puoi sempre cambiare le preferenze della tua lingua scrivendo"
+ " /selectLanguageTutorial nella chat.\n\n",
"en-US",
"Mostrami cosa puoi fare!",
true),
Arguments.of(
SelectLanguageTutorial.Language.English,
"_*Proceeds to drink a potion with a strange, multicolor liquid*_\n"
+ "\n"
+ "Thanks! Now that I drank this modified potion of Speak with animals that I've"
+ " found at the \"Crystal Fermentary\" magic potion shop yesterday I can speak"
+ " with you in the language that you prefer!\n"
+ "\n"
+ "You can always change your language settings by typing /selectLanguageTutorial"
+ " in the chat.\n\n",
"it-IT",
"Show me what you can do!",
true));
}
@ParameterizedTest
@Timeout(value = 1, unit = TimeUnit.MINUTES)
@MethodSource("getTestLocales")
void shouldProcessChangeLanguageToDesiredOneSendMessage(
SelectLanguageTutorial.Language language,
String expectedResult,
String startingLocale,
String buttonLocale,
boolean hasHelpBeenShown)
throws Exception {
when(fakeUUIDGenerator.generateAsString())
.thenReturn("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5")
.thenReturn("16507fbd-9f28-48a8-9de1-3ea1c943af67");
final Update update =
gson.fromJson(
"{\n"
+ "\"update_id\":10000,\n"
+ "\"callback_query\":{\n"
+ " \"id\": \"4382bfdwdsb323b2d9\",\n"
+ " \"from\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"type\": \"private\",\n"
+ " \"id\":1111111,\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"data\": \"Data from button callback\",\n"
+ " \"inline_message_id\": \"1234csdbsk4839\"\n"
+ "}\n"
+ "}",
Update.class);
final long tgChatId = 1111111L;
final ChatContext chatContext = new ChatContext();
final TgChat tgChat = new TgChat(tgChatId, chatContext, startingLocale, hasHelpBeenShown);
tgChat.save();
final CallbackQueryMetadata callbackQueryMetadata =
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withEvent("selectLanguageTutorial")
.withTelegramChatId(tgChatId)
.withAdditionalProperty(
SelectLanguageTutorial.Field.NewLanguage.getName(), language.getLocale())
.build();
final String entryGroupId = "2e67774a-e4e4-4369-a414-a7f8bfe74b80";
final CallbackQueryContext changeLanguageCallbackQueryContext =
new CallbackQueryContext(
"c018108f-6612-4848-8fca-cf301460d4eb", entryGroupId, callbackQueryMetadata);
changeLanguageCallbackQueryContext.save();
final CompletableFuture<Optional<BaseRequest<?, ?>>> processFuture =
selectLanguageTutorial.process(changeLanguageCallbackQueryContext, update);
final Optional<BaseRequest<?, ?>> gotResponseOpt = processFuture.get();
final SendMessage gotMessage = (SendMessage) gotResponseOpt.get();
assertEquals(expectedResult, gotMessage.getParameters().get("text"));
final InlineKeyboardButton[][] replyMarkups =
((InlineKeyboardMarkup)
gotMessage.getParameters().getOrDefault("reply_markup", new InlineKeyboardMarkup()))
.inlineKeyboard();
final List<InlineKeyboardButton> keyboardButtons =
Stream.of(replyMarkups).flatMap(Stream::of).toList();
if (!hasHelpBeenShown) {
assertEquals(1, keyboardButtons.size());
assertEquals(buttonLocale, keyboardButtons.get(0).text());
verify(fakeUUIDGenerator, times(2)).generateAsString();
assertEquals(
1, new QCallbackQueryContext().id.eq("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5").findCount());
} else {
assertEquals(0, keyboardButtons.size());
assertEquals(0, new QCallbackQueryContext().findCount());
}
final TgChat retrievedTgChat = new QTgChat().id.eq(tgChatId).findOne();
assertNotNull(retrievedTgChat);
assertEquals(language.getLocale(), retrievedTgChat.getLocale());
assertEquals(0, new QCallbackQueryContext().entryGroup.eq(entryGroupId).findCount());
}
@ParameterizedTest
@Timeout(value = 1, unit = TimeUnit.MINUTES)
@MethodSource("getTestLocales")
void shouldProcessChangeLanguageToDesiredOneEditMessage(
SelectLanguageTutorial.Language language,
String expectedResult,
String startingLocale,
String buttonLocale,
boolean hasHelpBeenShown)
throws Exception {
when(fakeUUIDGenerator.generateAsString())
.thenReturn("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5")
.thenReturn("16507fbd-9f28-48a8-9de1-3ea1c943af67");
final Update update =
gson.fromJson(
"{\n"
+ " \"update_id\": 10000,\n"
+ " \"callback_query\": {\n"
+ " \"id\": \"4382bfdwdsb323b2d9\",\n"
+ " \"from\": {\n"
+ " \"last_name\": \"Test Lastname\",\n"
+ " \"type\": \"private\",\n"
+ " \"id\": 1111111,\n"
+ " \"first_name\": \"Test Firstname\",\n"
+ " \"username\": \"Testusername\"\n"
+ " },\n"
+ " \"message\": {\n"
+ " \"message_id\": 2631,\n"
+ " \"from\": {\n"
+ " \"id\": 244745330,\n"
+ " \"is_bot\": true,\n"
+ " \"first_name\": \"test\",\n"
+ " \"username\": \"test\"\n"
+ " },\n"
+ " \"date\": 1680276288,\n"
+ " \"chat\": {\n"
+ " \"id\": 4772108,\n"
+ " \"type\": \"private\",\n"
+ " \"username\": \"userTest\",\n"
+ " \"first_name\": \"First Name\",\n"
+ " \"last_name\": \"Last Name\"\n"
+ " },\n"
+ " \"text\": \"Previous message content\",\n"
+ " \"reply_markup\": {\n"
+ " \"inline_keyboard\": [\n"
+ " [\n"
+ " {\n"
+ " \"text\": \"English\",\n"
+ " \"callback_data\": \"b345ea60-391a-40a4-96ac-8c36c4366498\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Italian\",\n"
+ " \"callback_data\": \"ab6487fa-b010-4eb6-a316-5b60f3b6bc1e\"\n"
+ " }\n"
+ " ]\n"
+ " ]\n"
+ " }\n"
+ " },\n"
+ " \"data\": \"Data from button callback\",\n"
+ " \"inline_message_id\": \"1234csdbsk4839\"\n"
+ " }\n"
+ "}",
Update.class);
final long tgChatId = 1111111L;
final ChatContext chatContext = new ChatContext();
final TgChat tgChat = new TgChat(tgChatId, chatContext, startingLocale, hasHelpBeenShown);
tgChat.save();
final CallbackQueryMetadata callbackQueryMetadata =
new CallbackQueryMetadata.CallbackQueryMetadataBuilder()
.withEvent("selectLanguageTutorial")
.withTelegramChatId(tgChatId)
.withAdditionalProperty(
SelectLanguageTutorial.Field.NewLanguage.getName(), language.getLocale())
.build();
final String entryGroupId = "2e67774a-e4e4-4369-a414-a7f8bfe74b80";
final CallbackQueryContext changeLanguageCallbackQueryContext =
new CallbackQueryContext(
"c018108f-6612-4848-8fca-cf301460d4eb", entryGroupId, callbackQueryMetadata);
changeLanguageCallbackQueryContext.save();
final CompletableFuture<Optional<BaseRequest<?, ?>>> processFuture =
selectLanguageTutorial.process(changeLanguageCallbackQueryContext, update);
final Optional<BaseRequest<?, ?>> gotResponseOpt = processFuture.get();
final EditMessageText gotMessage = (EditMessageText) gotResponseOpt.get();
assertEquals(expectedResult, gotMessage.getParameters().get("text"));
final InlineKeyboardButton[][] replyMarkups =
((InlineKeyboardMarkup)
gotMessage.getParameters().getOrDefault("reply_markup", new InlineKeyboardMarkup()))
.inlineKeyboard();
final List<InlineKeyboardButton> keyboardButtons =
Stream.of(replyMarkups).flatMap(Stream::of).toList();
if (!hasHelpBeenShown) {
assertEquals(1, keyboardButtons.size());
assertEquals(buttonLocale, keyboardButtons.get(0).text());
verify(fakeUUIDGenerator, times(2)).generateAsString();
assertEquals(
1, new QCallbackQueryContext().id.eq("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5").findCount());
} else {
assertEquals(0, keyboardButtons.size());
assertEquals(0, new QCallbackQueryContext().findCount());
}
final TgChat retrievedTgChat = new QTgChat().id.eq(tgChatId).findOne();
assertNotNull(retrievedTgChat);
assertEquals(language.getLocale(), retrievedTgChat.getLocale());
assertEquals(0, new QCallbackQueryContext().entryGroup.eq(entryGroupId).findCount());
}
}

View File

@ -23,22 +23,22 @@ import org.junit.jupiter.api.parallel.ExecutionMode;
@Execution(ExecutionMode.CONCURRENT) @Execution(ExecutionMode.CONCURRENT)
class RouterTest { class RouterTest {
private static Executor dummyEmptyExampleExecutor; private static Processor dummyEmptyExampleProcessor;
private static Executor anotherKeyWithResultExecutor; private static Processor anotherKeyWithResultProcessor;
private static Gson gson; private static Gson gson;
@BeforeAll @BeforeAll
static void beforeAll() { static void beforeAll() {
gson = new Gson(); gson = new Gson();
dummyEmptyExampleExecutor = mock(Executor.class); dummyEmptyExampleProcessor = mock(Processor.class);
when(dummyEmptyExampleExecutor.getTriggerKeyword()).thenReturn("/example"); when(dummyEmptyExampleProcessor.getTriggerKeyword()).thenReturn("/example");
when(dummyEmptyExampleExecutor.process(any(), any())) when(dummyEmptyExampleProcessor.process(any(), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty())); .thenReturn(CompletableFuture.completedFuture(Optional.empty()));
anotherKeyWithResultExecutor = mock(Executor.class); anotherKeyWithResultProcessor = mock(Processor.class);
when(anotherKeyWithResultExecutor.getTriggerKeyword()).thenReturn("/anotherExample"); when(anotherKeyWithResultProcessor.getTriggerKeyword()).thenReturn("/anotherExample");
when(anotherKeyWithResultExecutor.process(any(), any())) when(anotherKeyWithResultProcessor.process(any(), any()))
.thenReturn( .thenReturn(
CompletableFuture.completedFuture(Optional.of(new SendMessage(1234L, "hello world")))); CompletableFuture.completedFuture(Optional.of(new SendMessage(1234L, "hello world"))));
} }
@ -46,7 +46,7 @@ class RouterTest {
@Test @Test
void shouldMessageExampleMessageAndGetEmptyOptional() throws Exception { void shouldMessageExampleMessageAndGetEmptyOptional() throws Exception {
final Router router = final Router router =
new Router(Set.of(dummyEmptyExampleExecutor), Executors.newSingleThreadExecutor()); new Router(Set.of(dummyEmptyExampleProcessor), Executors.newSingleThreadExecutor());
final TgChat fakeChat = mock(TgChat.class); final TgChat fakeChat = mock(TgChat.class);
when(fakeChat.getChatContext()).thenReturn(new ChatContext()); when(fakeChat.getChatContext()).thenReturn(new ChatContext());
final Update update = final Update update =
@ -85,7 +85,7 @@ class RouterTest {
void shouldSelectRightExecutorAndReturnResult() throws Exception { void shouldSelectRightExecutorAndReturnResult() throws Exception {
final Router router = final Router router =
new Router( new Router(
Set.of(dummyEmptyExampleExecutor, anotherKeyWithResultExecutor), Set.of(dummyEmptyExampleProcessor, anotherKeyWithResultProcessor),
Executors.newSingleThreadExecutor()); Executors.newSingleThreadExecutor());
final TgChat fakeChat = mock(TgChat.class); final TgChat fakeChat = mock(TgChat.class);
when(fakeChat.getChatContext()).thenReturn(new ChatContext()); when(fakeChat.getChatContext()).thenReturn(new ChatContext());

View File

@ -1,12 +1,16 @@
package com.github.polpetta.mezzotre.telegram.command; package com.github.polpetta.mezzotre.telegram.command;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.github.polpetta.mezzotre.helper.Loader; import com.github.polpetta.mezzotre.helper.Loader;
import com.github.polpetta.mezzotre.helper.TestConfig; import com.github.polpetta.mezzotre.helper.TestConfig;
import com.github.polpetta.mezzotre.i18n.LocalizedMessageFactory; import com.github.polpetta.mezzotre.i18n.LocalizedMessageFactory;
import com.github.polpetta.mezzotre.orm.model.TgChat; import com.github.polpetta.mezzotre.orm.model.TgChat;
import com.github.polpetta.mezzotre.orm.model.query.QCallbackQueryContext;
import com.github.polpetta.mezzotre.orm.model.query.QTgChat; import com.github.polpetta.mezzotre.orm.model.query.QTgChat;
import com.github.polpetta.mezzotre.util.Clock;
import com.github.polpetta.mezzotre.util.UUIDGenerator;
import com.github.polpetta.types.json.ChatContext; import com.github.polpetta.types.json.ChatContext;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.Update;
@ -15,6 +19,7 @@ import com.pengrad.telegrambot.request.SendMessage;
import io.ebean.Database; import io.ebean.Database;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeConstants;
@ -45,6 +50,8 @@ class StartIntegrationTest {
private LocalizedMessageFactory localizedMessageFactory; private LocalizedMessageFactory localizedMessageFactory;
private Start start; private Start start;
private Database database; private Database database;
private Clock fakeClock;
private UUIDGenerator fakeUUIDGenerator;
@BeforeAll @BeforeAll
static void beforeAll() { static void beforeAll() {
@ -64,11 +71,25 @@ class StartIntegrationTest {
final Logger log = LoggerFactory.getLogger(Start.class); final Logger log = LoggerFactory.getLogger(Start.class);
start = new Start(localizedMessageFactory, Executors.newSingleThreadExecutor(), log); fakeClock = mock(Clock.class);
fakeUUIDGenerator = mock(UUIDGenerator.class);
start =
new Start(
localizedMessageFactory,
Executors.newSingleThreadExecutor(),
log,
fakeUUIDGenerator,
fakeClock);
} }
@Test @Test
void shouldUpdateContextInTheDatabase() throws Exception { void shouldUpdateContextInTheDatabase() throws Exception {
when(fakeClock.now()).thenReturn(42L);
when(fakeUUIDGenerator.generateAsString())
.thenReturn("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5")
.thenReturn("16507fbd-9f28-48a8-9de1-3ea1c943af67")
.thenReturn("0b0ac18e-f621-484e-aa8d-9b176be5b930");
final TgChat tgChat = new TgChat(1111111L, new ChatContext()); final TgChat tgChat = new TgChat(1111111L, new ChatContext());
tgChat.setLocale("en-US"); tgChat.setLocale("en-US");
tgChat.save(); tgChat.save();
@ -108,16 +129,113 @@ class StartIntegrationTest {
assertEquals( assertEquals(
"**Hello Test Firstname! \uD83D\uDC4B**\n\n" "**Hello Test Firstname! \uD83D\uDC4B**\n\n"
+ "This is _Mezzotre_, a simple bot focused on DnD content management! Please start by" + "This is _Mezzotre_, a simple bot focused on DnD content management! Please start by"
+ " choosing a language down below. \uD83D\uDC47", + " choosing a language down below \uD83D\uDC47",
message); message);
assertEquals(1111111L, (Long) gotMessage.getParameters().get("chat_id")); assertEquals(1111111L, (Long) gotMessage.getParameters().get("chat_id"));
final TgChat retrievedTgChat = new QTgChat().id.eq(1111111L).findOne(); final TgChat retrievedTgChat = new QTgChat().id.eq(1111111L).findOne();
assertNotNull(retrievedTgChat); assertNotNull(retrievedTgChat);
final ChatContext gotChatContext = retrievedTgChat.getChatContext(); final ChatContext gotChatContext = retrievedTgChat.getChatContext();
assertEquals(1441645532, gotChatContext.getPreviousMessageUnixTimestampInSeconds()); assertEquals(42, gotChatContext.getPreviousMessageUnixTimestampInSeconds());
assertEquals(1365, gotChatContext.getLastMessageSentId()); assertEquals(0, gotChatContext.getLastMessageSentId());
assertEquals("/start", gotChatContext.getStage()); assertEquals("/start", gotChatContext.getStage());
assertEquals(0, gotChatContext.getStep()); assertEquals(0, gotChatContext.getStep());
} }
@Test
void shouldReceiveHelloIntroduction() throws Exception {
when(fakeClock.now()).thenReturn(42L);
when(fakeUUIDGenerator.generateAsString())
.thenReturn("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5")
.thenReturn("16507fbd-9f28-48a8-9de1-3ea1c943af67")
.thenReturn("0b0ac18e-f621-484e-aa8d-9b176be5b930");
final TgChat tgChat = new TgChat(1111111L, new ChatContext(), "en-US", false);
final Update update =
gson.fromJson(
"{\n"
+ "\"update_id\":10000,\n"
+ "\"message\":{\n"
+ " \"date\":1441645532,\n"
+ " \"chat\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"type\": \"private\",\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"message_id\":1365,\n"
+ " \"from\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"text\":\"/start\"\n"
+ "}\n"
+ "}",
Update.class);
final CompletableFuture<Optional<BaseRequest<?, ?>>> gotFuture = start.process(tgChat, update);
assertDoesNotThrow(() -> gotFuture.get());
final Optional<BaseRequest<?, ?>> gotMessageOptional = gotFuture.get();
assertDoesNotThrow(gotMessageOptional::get);
final BaseRequest<?, ?> gotMessage = gotMessageOptional.get();
assertInstanceOf(SendMessage.class, gotMessage);
final String message = (String) gotMessage.getParameters().get("text");
assertEquals(
"**Hello Test Firstname! \uD83D\uDC4B**\n\n"
+ "This is _Mezzotre_, a simple bot focused on DnD content management! Please start by"
+ " choosing a language down below \uD83D\uDC47",
message);
assertEquals(1111111L, (Long) gotMessage.getParameters().get("chat_id"));
verify(fakeUUIDGenerator, times(3)).generateAsString();
assertEquals(
2,
new QCallbackQueryContext()
.entryGroup
.eq("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5")
.findCount());
assertEquals(2, new QCallbackQueryContext().findCount());
}
@Test
void shouldThrowErrorIfLocaleNonExists() {
when(fakeClock.now()).thenReturn(42L);
when(fakeUUIDGenerator.generateAsString())
.thenReturn("e86e6fa1-fdd4-4120-b85d-a5482db2e8b5")
.thenReturn("16507fbd-9f28-48a8-9de1-3ea1c943af67")
.thenReturn("0b0ac18e-f621-484e-aa8d-9b176be5b930");
final TgChat tgChat = new TgChat(1111111L, null);
final Update update =
gson.fromJson(
"{\n"
+ "\"update_id\":10000,\n"
+ "\"message\":{\n"
+ " \"date\":1441645532,\n"
+ " \"chat\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"type\": \"private\",\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"message_id\":1365,\n"
+ " \"from\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"text\":\"/start\"\n"
+ "}\n"
+ "}",
Update.class);
final CompletableFuture<Optional<BaseRequest<?, ?>>> gotFuture = start.process(tgChat, update);
assertThrows(ExecutionException.class, gotFuture::get);
}
} }

View File

@ -1,140 +0,0 @@
package com.github.polpetta.mezzotre.telegram.command;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.github.polpetta.mezzotre.i18n.LocalizedMessageFactory;
import com.github.polpetta.mezzotre.orm.model.TgChat;
import com.github.polpetta.types.json.ChatContext;
import com.google.gson.Gson;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.SendMessage;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.slf4j.Logger;
@Tag("velocity")
@Execution(ExecutionMode.CONCURRENT)
class StartTest {
private VelocityEngine velocityEngine;
private LocalizedMessageFactory localizedMessageFactory;
private Start start;
private static Gson gson;
@BeforeAll
static void beforeAll() {
gson = new Gson();
}
@BeforeEach
void setUp() {
velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "classpath");
velocityEngine.setProperty(
"resource.loader.classpath.class", ClasspathResourceLoader.class.getName());
velocityEngine.init();
localizedMessageFactory = new LocalizedMessageFactory(velocityEngine);
final Logger fakeLog = mock(Logger.class);
start = new Start(localizedMessageFactory, Executors.newSingleThreadExecutor(), fakeLog);
}
@Test
void shouldReceiveHelloIntroduction() throws Exception {
final TgChat fakeChat = mock(TgChat.class);
when(fakeChat.getLocale()).thenReturn("en-US");
when(fakeChat.getChatContext()).thenReturn(new ChatContext());
when(fakeChat.getId()).thenReturn(1111111L);
final Update update =
gson.fromJson(
"{\n"
+ "\"update_id\":10000,\n"
+ "\"message\":{\n"
+ " \"date\":1441645532,\n"
+ " \"chat\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"type\": \"private\",\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"message_id\":1365,\n"
+ " \"from\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"text\":\"/start\"\n"
+ "}\n"
+ "}",
Update.class);
final CompletableFuture<Optional<BaseRequest<?, ?>>> gotFuture =
start.process(fakeChat, update);
assertDoesNotThrow(() -> gotFuture.get());
final Optional<BaseRequest<?, ?>> gotMessageOptional = gotFuture.get();
assertDoesNotThrow(gotMessageOptional::get);
final BaseRequest<?, ?> gotMessage = gotMessageOptional.get();
assertInstanceOf(SendMessage.class, gotMessage);
final String message = (String) gotMessage.getParameters().get("text");
assertEquals(
"**Hello Test Firstname! \uD83D\uDC4B**\n\n"
+ "This is _Mezzotre_, a simple bot focused on DnD content management! Please start by"
+ " choosing a language down below. \uD83D\uDC47",
message);
assertEquals(1111111L, (Long) gotMessage.getParameters().get("chat_id"));
verify(fakeChat, times(1)).save();
}
@Test
void shouldThrowErrorIfLocaleNonExists() {
final TgChat fakeChat = mock(TgChat.class);
// Do not set Locale on purpose
when(fakeChat.getId()).thenReturn(1111111L);
final Update update =
gson.fromJson(
"{\n"
+ "\"update_id\":10000,\n"
+ "\"message\":{\n"
+ " \"date\":1441645532,\n"
+ " \"chat\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"type\": \"private\",\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"message_id\":1365,\n"
+ " \"from\":{\n"
+ " \"last_name\":\"Test Lastname\",\n"
+ " \"id\":1111111,\n"
+ " \"first_name\":\"Test Firstname\",\n"
+ " \"username\":\"Testusername\"\n"
+ " },\n"
+ " \"text\":\"/start\"\n"
+ "}\n"
+ "}",
Update.class);
final CompletableFuture<Optional<BaseRequest<?, ?>>> gotFuture =
start.process(fakeChat, update);
assertThrows(ExecutionException.class, gotFuture::get);
}
}