【问题标题】:how to send message via telegram Bot in c#?如何在 C# 中通过电报 Bot 发送消息?
【发布时间】:2017-10-26 06:03:04
【问题描述】:

我是电报机器人程序员的新手,想编写一个简单的控制台应用程序来在电报上发送消息。

research 之后,我开发了这段代码没有错误,但它不起作用,也没有发送我的消息。 当我跟踪我的代码时,我发现结果对象的状态是“等待激活”,这是什么意思?

我注册了我的机器人并拥有一个 API 访问令牌并在此代码上使用它。

请指导我:)

static void Main(string[] args)
    {

        Task<Message> result;
        result= DoSomethingAsync();

        Console.WriteLine();
    }
    static async Task<Message> DoSomethingAsync()
    {
        var Bot = new Telegram.Bot.Api("my API access Token");
       return await Bot.SendTextMessage("@blablavla", "test message");
    }

【问题讨论】:

  • 您需要使用result = await DoSomethingAsync()(正如我在现在已删除的答案中指出的那样),但这在Main() 方法中是不可能的。见stackoverflow.com/questions/9208921/…
  • 我也有同样的问题,你能解决吗?

标签: c# telegram telegram-bot


【解决方案1】:

您可以像这样构建自己的async main-方法:

static void Main(string[] args)
{
    MainAsync(args).Wait();

    Console.ReadKey();
}

static async Task MainAsync(string[] args)
{
    Message result;
    Console.WriteLine("Sending Message...");
    result = await DoSomethingAsync();
    Console.WriteLine("Message sent...");
    Console.WrtieLine(result);
}

static async Task<Message> DoSomethingAsync()
    {
        var Bot = new Telegram.Bot.Api("my API access Token");
        return Bot.SendTextMessage("@blablavla", "test message"); // It's your last call to an async function in an async function, no need to await it here.
    }

这应该做你想做的事。但请注意,它未经测试!

【讨论】:

    【解决方案2】:

    首先创建你的机器人

    Telegram.Bot.Api bot = new Telegram.Bot.Api("my API access Token");
    

    然后用你想要的任何方法编写这样的代码。当此方法运行时,它会在每条要发送的消息之后将您的消息发送给用户。并会在控制台中通知你。

    int offset = 0;
                while (true)
                {
                    Telegram.Bot.Types.Update[] updates = bot.GetUpdates(offset).Result;
                    foreach (var update in updates)
                    {
                        offset = update.Id + 1;
                        if (update.Message == null)
                            continue;
    
                        Console.WriteLine("Sending Message...");
                        bot.SendTextMessage(update.Message.Chat.Id, "your text");
                        Console.WriteLine("Message sent...");
                        update.Message.Text);
                    }
                }
    

    试试看

    【讨论】:

      【解决方案3】:

      您可以使用This Example 发送消息、位置、内嵌键盘、文本键盘、照片和...

      在此示例中,您可以看到由您的库创建的 GetUpdate 和 Webhook 代码

      此示例基于 Telegram Bot API MrRoundRobin

      【讨论】:

      • 请改为链接,把你的例子放在这里
      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 2018-11-27
      • 2021-06-11
      • 2017-04-08
      • 1970-01-01
      • 2016-05-09
      • 2020-08-31
      • 2017-05-16
      相关资源
      最近更新 更多