Почему телеграмма не отвечает на команды из этого кода? - PullRequest
0 голосов
/ 11 февраля 2020

Я новичок в программировании ботов Telegram с C#. Я создал простого бота, но это не работает. Консоль полностью запускает программу, но бот не показывает мне никаких команд. И я не вижу кнопки в боте. Я знаю, что-то не так, но я не знаю, где. Пожалуйста, помогите мне, это очень сила для меня Что мне делать? Это мой код:

using System;
using System.Linq;
using System.Threading.Tasks;
using NetTelegramBotApi;
using NetTelegramBotApi.Requests;
using NetTelegramBotApi.Types;
using System.Text;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        private static string token = "<PRIVATE-KEY>"; //Telegram token
        private static ReplyKeyboardMarkup mainMenu; //Declare a menu
        private static ReplyKeyboardMarkup secondMenu;
        static void Main(string[] args)
        {

            //Set Items as button for main menu

            mainMenu = new ReplyKeyboardMarkup
            {
                Keyboard = new KeyboardButton[][]
                 {
                     new KeyboardButton[]
                     {
                         new KeyboardButton("Text 1"),
                         new KeyboardButton("Text 2"),
                         new KeyboardButton("Text 3")
                     },
                     new KeyboardButton[]
                     {
                         new KeyboardButton("Text 4"),
                         new KeyboardButton("Text 5"),
                         new KeyboardButton("Text 6")
                     }
                 }
            };

            //Set Items as button for second menu
            secondMenu = new ReplyKeyboardMarkup
            {
                Keyboard = new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton("Second 1"),
                        new KeyboardButton("Second 2")
                    },
                    new KeyboardButton[]
                    {
                        new KeyboardButton("Back")
                    }
                }
            };

            Task.Run(() => RunBot());
            Console.ReadLine();
        }

        public static async Task RunBot()
        {
            var bot = new TelegramBot(token);
            var me = await bot.MakeRequestAsync(new GetMe());
            Console.WriteLine("User name is {0}", me.Username);
            long offset = 0;
            int whileCount = 0;
            while (true)
            {
                Console.WriteLine("While is {0}", whileCount);
                whileCount++;

                //Check user creates a request

                var updates = await bot.MakeRequestAsync(new GetUpdates() { Offset = offset });
                Console.WriteLine("update count is {0}", updates.Count());
                Console.WriteLine("------------------------------");
                try
                {

                }
                catch (Exception e)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1; // Get offset of update
                        var text = update.Message.Text; //Get message from users

                        /*
                         * These lines check, that which button has been selected by user
                         * Do something for each button
                         */

                        if (text == "/start")
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "سلاااااام. این اولین ربات تلگرامی هست که ساختم. پیش به سوی موفقیت و پول زیاد ")
                            { ReplyMarkup = mainMenu };
                            await bot.MakeRequestAsync(req); //Run req Command
                            continue; //Loop continues
                        }
                        else if (text != null && text.Contains("Text 1"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "You clicked on Text 1")
                            { ReplyMarkup = mainMenu }; //Send message to user
                            await bot.MakeRequestAsync(req); //Run req command
                            continue; //Loop continues
                        }
                        else if (text != null && text.Contains("Text 2"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "You clicked on Text 2")
                            { ReplyMarkup = mainMenu }; //Send message to user
                            await bot.MakeRequestAsync(req); //Run req command
                            continue; //Loop continues
                        }
                        else if (text != null && text.Contains("Text 3"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "You clicked on Text 3")
                            { ReplyMarkup = mainMenu };
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else if (text != null && text.Contains("Text 4"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "You clicked on Text 4")
                            { ReplyMarkup = mainMenu };
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else if (text != null && text.Contains("Text 5"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "You clicked on Text 5")
                            { ReplyMarkup = mainMenu };
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else if (text != null && text.Contains("Text 6"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "You clicked on Text 6")
                            { ReplyMarkup = secondMenu };
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else if (text != null && text.Contains("Second 1"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "Please wait a moment")
                            { ReplyMarkup = secondMenu};
                            await bot.MakeRequestAsync(req);
                            /*
                             * This using is for sending a video to a user
                             */
                             using(var stream = System.IO.File.Open("D://Projects//Visual studio project//resources//test.mp4", System.IO.FileMode.Open))
                            {
                               var req2 = new SendVideo(update.Message.Chat.Id, new FileToSend(stream, "test.mp4"))
                               { ReplyMarkup = secondMenu};
                               await bot.MakeRequestAsync(req2);
                                continue;

                            }

                        }
                        else if(text != null && text.Contains("Second 2"))
                        {
                            /**
                             * This using is for sending a photo to a user
                             */
                            using (var stream = System.IO.File.Open("d://Photo//car.jpg", System.IO.FileMode.Open))
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(stream, "car.jpg"))
                                { ReplyMarkup = secondMenu};
                                await bot.MakeRequestAsync(req);
                                continue;
                            }
                        }
                        else if(text != null && text.Contains("Back"))
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "Back to main menu")
                            { ReplyMarkup = mainMenu };
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "Undefined message!!!")
                            { ReplyMarkup = mainMenu };
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                    }
                }
            }
        }
    }
}

Я использовал пакет NetTelegramBotApi Заранее большое спасибо

1 Ответ

0 голосов
/ 12 февраля 2020

Сначала вырежьте коды из предложения catch и вставьте их в try. инициализируйте меня и обновите переменные следующим образом:

var me = bot.MakeRequestAsyn c (new GetMe ()). Result;

var updates = bot.MakeRequestAsyn c (new GetUpdates () {Смещение = смещение}). Результат;

...