使用 TLSharp 的电报身份验证

Telegram Authentication using TLSharp

我尝试使用 TLSharp v 0.1.0.209 为 Telegram 开发一个客户端,它除了接收消息和 运行 内容上的一些简单逻辑外什么都不做

我的代码目前看起来像这样

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TLSharp.Core;

namespace TelegramBot
{
    public sealed class Service
    {
        private TelegramClient client;

        public Service()
        {
            this.client = new TelegramClient(etc.Constants.AppApiId, etc.Constants.AppApiHash);
        }

        public async void Connect()
        {
            await this.client.ConnectAsync();
        }

        public async void Authenticate(String phoneNumber)
        {
            var hash = await client.SendCodeRequestAsync(phoneNumber);

            {
                Debugger.Break();
            }

            var code = "<code_from_telegram>"; // you can change code in debugger

            var user = await client.MakeAuthAsync(phoneNumber, hash, code);
        }
    }
}

我这样称呼它

static void Main(string[] args)
{
    Service bot = new Service();

    bot.Connect();
    bot.Authenticate(etc.Constants.PhoneNumber);

    Debugger.Break();
}

但是,我在调用 'SendCodeRequestAsync' 时得到 'NullPointerException'。我该如何解决/解决这个问题?号码以这种格式提供 '+12223334444'

问题是无法等待 async void 方法。它们抛出的任何异常也无法被捕获。它们仅用于事件处理程序或 event-handler-like 方法。

void 方法的等价物是 async Task,而不是 async void

在这种情况下,方法应更改为:

    public async Task Connect()
    {
        await this.client.ConnectAsync();
    }

    public async Task Authenticate(String phoneNumber)
    {
    //...
    }

并且 Main() 应更改为:

static void Main(string[] args)
{
    Service bot = new Service();

    bot.Connect().Wait();
    bot.Authenticate(etc.Constants.PhoneNumber).Wait();

    Debugger.Break();
}

或者,甚至更好:

static void Main(string[] args)
{
    Service bot = new Service();

    Authenticate(bot).Wait();

    Debugger.Break();
}

static async Task Authenticate(Service bot)
{
    await bot.Connect();
    await bot.Authenticate(etc.Constants.PhoneNumber);
}