首页 > 解决方案 > 为什么电报不响应此代码中的命令?

问题描述

我是使用 C# 进行 Telegram 机器人编程的新手。我创建了一个简单的机器人,但这不起作用。控制台完全运行程序,但机器人显示我没有任何命令响应。而且我看不到机器人中的按钮。我知道出了点问题,但我不知道在哪里。请帮帮我,这对我来说很给力我该怎么办?这是我的代码:

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 包提前非常感谢

标签: c#botstelegramtelegram-bot

解决方案


首先从catch子句中剪切代码并将它们粘贴到try中。初始化我并像这样更新变量:

var me = bot.MakeRequestAsync(new GetMe()).Result;

var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;


推荐阅读