Cppgram  1.0.0
Easy and modern C++14 Telegram Bot API wrapper
message_command.hpp
1 #ifndef CPPGRAM_MESSAGE_COMMAND_HPP
2 #define CPPGRAM_MESSAGE_COMMAND_HPP
3 
4 #include "command.hpp"
5 #include "cppgram/types/update.hpp"
6 
7 namespace cppgram
8 {
9 namespace commands
10 {
17 template <class T> class MessageCommand : public Command<T>
18 {
19  public:
20  typedef std::function<void( T &, const types::Message & )> MessageClosure;
21 
28  MessageCommand( std::string &command, MessageClosure script )
29  : command( "/" + command )
30  , script( script )
31  {
32  }
33 
40  virtual void callClosure( T &bot, const types::Update &update )
41  {
42  bot.setChatId( update.message->chat.id );
43  script( bot, update.message.value() );
44  }
45 
53  virtual bool isValid( const types::Update &update )
54  {
55  // If there isn't at least a command in the message
56  if ( update.message->entities.size() == 0 )
57  {
58  return false;
59  }
60 
61  types::MessageEntity entity = update.message->entities[0];
62 
63  // If the first entity is not a bot_command
64  if ( entity.type != EMessageEntity::bot_command )
65  {
66  return false;
67  }
68 
69  // If the command is not the first text in the message
70  if ( entity.offset != 0 )
71  {
72  return false;
73  }
74 
75  // Get the string that corresponds to the bot_command
76  std::string entity_text = update.message->text->substr( 0, entity.length );
77 
78  // and the command is found in the message
79  if ( entity_text.find( command ) != std::string::npos )
80  {
81  return true;
82  }
83 
84  return false;
85  }
86 
87  private:
89  const EUpdate type = EUpdate::eMessage;
90 
92  std::string command;
93 
95  MessageClosure script;
96 };
97 }
98 }
99 
100 #endif
int offset
Offset in UTF-16 code units to the start of the entity.
Definition: message_entity.hpp:33
virtual bool isValid(const types::Update &update)
Does the update trigger this command?
Definition: message_command.hpp:53
Definition: enums.hpp:37
EMessageEntity type
Type of the entity.
Definition: message_entity.hpp:30
Triggered by bot command in messages.
Definition: message_command.hpp:17
Entity in the message.
Definition: message_entity.hpp:24
Abstract class for bot commands.
Definition: command_handler.hpp:15
int length
Length of the entity in UTF-16 code units.
Definition: message_entity.hpp:33
main namespace for Cppgram
virtual void callClosure(T &bot, const types::Update &update)
Forward the update to another function.
Definition: message_command.hpp:40
MessageCommand(std::string &command, MessageClosure script)
Construct a message command.
Definition: message_command.hpp:28