【问题标题】:Telegram Authentication using TLSharp使用 TLSharp 进行电报身份验证
【发布时间】:2017-01-16 13:01:47
【问题描述】:

我尝试使用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

标签: c# telegram


【解决方案1】:

问题是不能等待async void 方法。他们抛出的任何异常也不能被捕获。它们仅用于事件处理程序或类似事件处理程序的方法。

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);
}

【讨论】:

    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 2017-06-13
    • 2017-03-11
    相关资源
    最近更新 更多