S
S
Smilley2017-03-12 00:31:37
C++ / C#
Smilley, 2017-03-12 00:31:37

What is the best way to implement a telegram bot?

Colleagues, good afternoon. Please help me to correctly implement the telegram bot. The question is:
How to process incoming commands to the bot correctly? At the moment there are two assumptions:
1) A big, big string of ifs. Doesn't seem like much of an option to me.
2) Implement something like this:

async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;
            if (message == null || message.Type != MessageType.TextMessage) return;
            try
            {
                this.GetType().GetMethod(message.Text.Substring(0, message.Text.IndexOf(" ")).ToLower().Replace("/", "")).Invoke(this, new object[] { message });
            }
            catch (Exception ex)
            {
                if (message.Chat.Type == ChatType.Private)
                {
                    var usage = @"Usage:
                            /inline   - send inline keyboard
                            /keyboard - send custom keyboard
                            /photo    - send a photo
                            /request  - request location or contact
                            ";
                    await Bot.SendTextMessageAsync(message.Chat.Id, usage, replyMarkup: new ReplyKeyboardHide());
                }
            }
        }

        public async void test(object args)
        {
            var message = (Message)args;
            await Bot.SendTextMessageAsync(message.Chat.Id, "echo", replyMarkup: new ReplyKeyboardHide());
        }

Those. under each code the method to do.
Maybe there are other ways? Now I just started making a bot and I would like to choose the right architecture from the start.
Thanks in advance.
Update:
Implemented something like the following -
//Dictionary, который сам заполняется
Dictionary<string, Type> CommandsDictionary = new Dictionary<string, Type>();
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
{
    if (type.ToString().EndsWith("ChatCommand"))
    {
         foreach (var str in (string[])type.GetProperty("Commands").GetValue(type))
         {
              CommandsDictionary.Add(str, type);
         }
     }
}
// Реализация тестовой команды
public static class TestChatCommand
{
    private static string[] commands = { "Test", "test", "Тест", "тест" };
    public static string[] Commands => commands;
    public static async void Execute(TelegramBotClient Bot, Message message)
    {
         await Bot.SendTextMessageAsync(message.Chat.Id, "I'm working!");
    }
}
//Ну и собственно поиск команды
try
{
    Type type;
     var command = message.Text.Replace("/", "");
     if (CommandsDictionary.TryGetValue(command, out type))
     {
          type.GetMethod("Execute").Invoke(type, new object[] { Bot, message });
    }
}

How terrible, please rate? Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2017-03-12
@Smilley

A dictionary in which the key is a command, and the value is the handler of this command "CommandExecutor"
All handlers are classes inherited from a single class "CommandExecutor", which can register itself in this dictionary, and which has the Execute method, which actually and will be called when a message arrives from the same dictionary.

A
AdaStreamer, 2017-03-12
@AdaStreamer

In general, there are already frameworks for these tasks. Which ones - depends on your programming language.
Personally, my solution is metaprogramming, but I write in python, everything is simple with dynamic typing. IMHO, sharp is not the best choice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question