如何在 C# 中通过电报机器人发送消息
本文关键字:机器人 消息 | 更新日期: 2023-09-27 18:34:09
我是电报机器人程序员的新手,想编写一个简单的控制台应用程序来在电报上发送消息。
经过一些研究,我开发了这个代码,没有错误,但它不起作用,也不会发送我的信息。当我跟踪我的代码时,我发现结果对象的状态是"等待激活",这是什么意思?
我注册了我的机器人并有一个 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");
}
你可以
像这样构建自己的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.
}
这应该做你想要的。但请注意,它是未经测试的!
首先创建机器人
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);
}
}
试试吧
您可以使用此示例来接收发送消息,位置,内联键盘,文本键盘,照片和...
在此示例中,您可以看到由库创建的 GetUpdate 和 Webhook 代码
此示例基于 Telegram Bot API MrRoundRobin