【发布时间】:2022-03-07 19:39:43
【问题描述】:
我在 C# 中使用 Telegram API 时遇到问题。 我想用特定电话号码在电报中创建一个联系人,这样我就可以直接向我的联系人中没有的电话号码发送消息。
如何使用 c# 在电报中创建具有特定电话号码的联系人?
我尝试使用 TLSharp 来执行此操作,但没有找到任何方法。
【问题讨论】:
我在 C# 中使用 Telegram API 时遇到问题。 我想用特定电话号码在电报中创建一个联系人,这样我就可以直接向我的联系人中没有的电话号码发送消息。
如何使用 c# 在电报中创建具有特定电话号码的联系人?
我尝试使用 TLSharp 来执行此操作,但没有找到任何方法。
【问题讨论】:
Telegram Bot API 中没有任何内容:https://core.telegram.org/bots/api
【讨论】:
现在有 WTelegramClient 库,使用最新的 Telegram Client API 协议(以用户身份连接,而不是机器人)。
该库非常完整,但使用起来也非常简单。关注README on GitHub简单介绍。
要通过电话号码创建联系人并向其发送消息,整个 Program.cs 将非常简单:
using TL;
using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var contact = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+PHONENUMBER" } });
await client.SendMessageAsync(contact.users[0], "Hello");
【讨论】:
TLSharp 现在有了 ImportContactsAsync 方法,你可以这样使用它:
var list = new List<TLInputPhoneContact>
{
new TLInputPhoneContact() { Phone = phoneNumberTo, FirstName = defaultName, LastName = defaultLastname, ClientId = 0}
};
await client.ImportContactsAsync(list);
浪费了几个小时试图在互联网上找到如何做到这一点,但没有找到,希望它能帮助遇到同样问题的人。
【讨论】:
class Program
{
static string Config(string what)
{
switch (what)
{
case "api_id": return "1536894510";
case "api_hash": return "d6f1a012ba7d4bebdde2ddbe45989e9bf6d";
case "phone_number": return "+989034750547";
case "verification_code": Console.Write("Code: "); return Console.ReadLine();
case "first_name": return "John"; // if sign-up is required
case "last_name": return "Doe"; // if sign-up is required
case "password": return "MaX13750123"; // if user has enabled 2FA
default: return null; // let WTelegramClient decide the default config
}
}
static async Task Main(string[] args)
{
Console.WriteLine("Hello This is test app!");
using var client = new WTelegram.Client(Config); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
for (int i = 0; i < 100; i++)
{
try
{
var contact = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+989025390023", first_name = "Iran", last_name = "Tester" } });
object p = await client.SendMessageAsync(contact.users[contact.users.Keys.First()], "Hello");
}
catch (Exception)
{
throw;
}
finally
{
}
}
}
}
真正有效的正确代码
【讨论】: