Skip to content
This repository was archived by the owner on Dec 5, 2021. It is now read-only.

Commit 38f088a

Browse files
committed
Reapply Events PR #679
1 parent 3c6f53b commit 38f088a

8 files changed

Lines changed: 586 additions & 89 deletions

File tree

README.md

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,257 @@ To download file you should call **GetFile** method
143143

144144
Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix/TLSharp/blob/master/TLSharp.Tests/TLSharpTests.cs#L167)
145145

146+
# Events Sample code
147+
```csharp
148+
using System;
149+
using System.Threading.Tasks;
150+
using TeleSharp.TL;
151+
using TLSharp.Core;
152+
using System.Linq;
153+
using TeleSharp.TL.Messages;
154+
using System.Collections.Generic;
155+
156+
namespace TLSharpPOC
157+
{
158+
class MainClass
159+
{
160+
const int APIId = 0;
161+
const string APIHash = "???";
162+
const string phone = "???";
163+
public static void Main(string[] args)
164+
{
165+
new MainClass().MainAsync(args).Wait();
166+
}
167+
168+
private async Task MainAsync(string[] args)
169+
{
170+
TelegramClient client = null;
171+
try
172+
{
173+
// -- if necessary, IP can be changed so the client can connect to the test network.
174+
Session session = null;
175+
// new Session(new FileSessionStore(), "session")
176+
//{
177+
// ServerAddress = "149.154.175.10",
178+
// Port = 443
179+
//};
180+
//Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}");
181+
client = new TelegramClient(APIId, APIHash, session);
182+
// subscribe an event to receive live messages
183+
client.Updates += Client_Updates;
184+
await client.ConnectAsync();
185+
Console.WriteLine($"Authorised: {client.IsUserAuthorized()}");
186+
TLUser user = null;
187+
// -- If the user has already authenticated, this step will prevent account from being blocked as it
188+
// -- reuses the data from last authorisation.
189+
if (client.IsUserAuthorized())
190+
user = client.Session.TLUser;
191+
else
192+
{
193+
var registered = await client.IsPhoneRegisteredAsync(phone);
194+
var hash = await client.SendCodeRequestAsync(phone);
195+
Console.Write("Code: ");
196+
var code = Console.ReadLine();
197+
if (!registered)
198+
{
199+
Console.WriteLine($"Sign up {phone}");
200+
user = await client.SignUpAsync(phone, hash, code, "First", "Last");
201+
}
202+
Console.WriteLine($"Sign in {phone}");
203+
user = await client.MakeAuthAsync(phone, hash, code);
204+
}
205+
206+
var contacts = await client.GetContactsAsync();
207+
Console.WriteLine("Contacts:");
208+
foreach (var contact in contacts.Users.OfType<TLUser>())
209+
{
210+
var contactUser = contact as TLUser;
211+
Console.WriteLine($"\t{contact.Id} {contact.Phone} {contact.FirstName} {contact.LastName}");
212+
}
213+
214+
215+
var dialogs = (TLDialogs) await client.GetUserDialogsAsync();
216+
Console.WriteLine("Channels: ");
217+
foreach (var channelObj in dialogs.Chats.OfType<TLChannel>())
218+
{
219+
var channel = channelObj as TLChannel;
220+
Console.WriteLine($"\tChat: {channel.Title}");
221+
}
222+
223+
Console.WriteLine("Groups:");
224+
TLChat chat = null;
225+
foreach (var chatObj in dialogs.Chats.OfType<TLChat>())
226+
{
227+
chat = chatObj as TLChat;
228+
Console.WriteLine($"Chat name: {chat.Title}");
229+
var request = new TLRequestGetFullChat() { ChatId = chat.Id };
230+
var fullChat = await client.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>(request);
231+
232+
var participants = (fullChat.FullChat as TeleSharp.TL.TLChatFull).Participants as TLChatParticipants;
233+
foreach (var p in participants.Participants)
234+
{
235+
if (p is TLChatParticipant)
236+
{
237+
var participant = p as TLChatParticipant;
238+
Console.WriteLine($"\t{participant.UserId}");
239+
}
240+
else if (p is TLChatParticipantAdmin)
241+
{
242+
var participant = p as TLChatParticipantAdmin;
243+
Console.WriteLine($"\t{participant.UserId}**");
244+
}
245+
else if (p is TLChatParticipantCreator)
246+
{
247+
var participant = p as TLChatParticipantCreator;
248+
Console.WriteLine($"\t{participant.UserId}**");
249+
}
250+
}
251+
252+
var peer = new TLInputPeerChat() { ChatId = chat.Id };
253+
var m = await client.GetHistoryAsync(peer, 0, 0, 0);
254+
Console.WriteLine(m);
255+
if (m is TLMessages)
256+
{
257+
var messages = m as TLMessages;
258+
259+
260+
foreach (var message in messages.Messages)
261+
{
262+
if (message is TLMessage)
263+
{
264+
var m1 = message as TLMessage;
265+
Console.WriteLine($"\t\t{m1.Id} {m1.Message}");
266+
}
267+
else if (message is TLMessageService)
268+
{
269+
var m1 = message as TLMessageService;
270+
Console.WriteLine($"\t\t{m1.Id} {m1.Action}");
271+
}
272+
}
273+
}
274+
else if (m is TLMessagesSlice)
275+
{
276+
bool done = false;
277+
int total = 0;
278+
while (!done)
279+
{
280+
var messages = m as TLMessagesSlice;
281+
282+
foreach (var m1 in messages.Messages)
283+
{
284+
if (m1 is TLMessage)
285+
{
286+
var message = m1 as TLMessage;
287+
Console.WriteLine($"\t\t{message.Id} {message.Message}");
288+
++total;
289+
}
290+
else if (m1 is TLMessageService)
291+
{
292+
var message = m1 as TLMessageService;
293+
Console.WriteLine($"\t\t{message.Id} {message.Action}");
294+
++total;
295+
done = message.Action is TLMessageActionChatCreate;
296+
}
297+
}
298+
m = await client.GetHistoryAsync(peer, total, 0, 0);
299+
}
300+
}
301+
}
302+
303+
// -- Wait in a loop to handle incoming updates. No need to poll.
304+
for (;;)
305+
{
306+
await client.WaitEventAsync();
307+
}
308+
}
309+
catch (Exception e)
310+
{
311+
Console.WriteLine(e);
312+
}
313+
}
314+
315+
private void Client_Updates(TelegramClient client, TLAbsUpdates updates)
316+
{
317+
Console.WriteLine($"Got update: {updates}");
318+
if (updates is TLUpdateShort)
319+
{
320+
var updateShort = updates as TLUpdateShort;
321+
Console.WriteLine($"Short: {updateShort.Update}");
322+
if (updateShort.Update is TLUpdateUserStatus)
323+
{
324+
var status = updateShort.Update as TLUpdateUserStatus;
325+
Console.WriteLine($"User {status.UserId} is {status.Status}");
326+
if (status.Status is TLUserStatusOnline)
327+
{
328+
try
329+
{
330+
var peer = new TLInputPeerUser() { UserId = status.UserId };
331+
client.SendMessageAsync(peer, "Você está online.").Wait();
332+
} catch {}
333+
}
334+
}
335+
}
336+
else if (updates is TLUpdateShortMessage)
337+
{
338+
var message = updates as TLUpdateShortMessage;
339+
Console.WriteLine($"Message: {message.Message}");
340+
MarkMessageRead(client, new TLInputPeerUser() { UserId = message.UserId }, message.Id);
341+
}
342+
else if (updates is TLUpdateShortChatMessage)
343+
{
344+
var message = updates as TLUpdateShortChatMessage;
345+
Console.WriteLine($"Chat Message: {message.Message}");
346+
MarkMessageRead(client, new TLInputPeerChat() { ChatId = message.ChatId }, message.Id);
347+
}
348+
else if (updates is TLUpdates)
349+
{
350+
var allUpdates = updates as TLUpdates;
351+
foreach (var update in allUpdates.Updates)
352+
{
353+
Console.WriteLine($"\t{update}");
354+
if (update is TLUpdateNewChannelMessage)
355+
{
356+
var metaMessage = update as TLUpdateNewChannelMessage;
357+
var message = metaMessage.Message as TLMessage;
358+
Console.WriteLine($"Channel message: {message.Message}");
359+
var channel = allUpdates.Chats[0] as TLChannel;
360+
MarkMessageRead(client,
361+
new TLInputPeerChannel() { ChannelId = channel.Id, AccessHash = channel.AccessHash.Value },
362+
message.Id );
363+
}
364+
}
365+
366+
foreach(var user in allUpdates.Users)
367+
{
368+
Console.WriteLine($"{user}");
369+
}
370+
371+
foreach (var chat in allUpdates.Chats)
372+
{
373+
Console.WriteLine($"{chat}");
374+
}
375+
}
376+
}
377+
378+
private void MarkMessageRead(TelegramClient client, TLAbsInputPeer peer, int id)
379+
{
380+
// An exception happens here but it's not fatal.
381+
try
382+
{
383+
var request = new TLRequestReadHistory();
384+
request.MaxId = id;
385+
request.Peer = peer;
386+
client.SendRequestAsync<bool>(request).Wait();
387+
}
388+
catch (InvalidOperationException e){
389+
System.Console.WriteLine(e.getMessage())
390+
}
391+
392+
}
393+
}
394+
}
395+
```
396+
146397
# Available Methods
147398

148399
For your convenience TLSharp have wrappers for several Telegram API methods. You could add your own, see details below.

TLSharp.Core/Network/Exceptions.cs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
using System;
2+
namespace TLSharp.Core.Network
3+
{
4+
public class FloodException : Exception
5+
{
6+
public TimeSpan TimeToWait { get; private set; }
7+
8+
internal FloodException(TimeSpan timeToWait)
9+
: base($"Flood prevention. Telegram now requires your program to do requests again only after {timeToWait.TotalSeconds} seconds have passed ({nameof(TimeToWait)} property)." +
10+
" If you think the culprit of this problem may lie in TLSharp's implementation, open a Github issue please.")
11+
{
12+
TimeToWait = timeToWait;
13+
}
14+
}
15+
16+
public class BadMessageException : Exception
17+
{
18+
internal BadMessageException(string description) : base(description)
19+
{
20+
}
21+
}
22+
23+
internal abstract class DataCenterMigrationException : Exception
24+
{
25+
internal int DC { get; private set; }
26+
27+
private const string REPORT_MESSAGE =
28+
" See: https://github.com/sochix/TLSharp#i-get-a-xxxmigrationexception-or-a-migrate_x-error";
29+
30+
protected DataCenterMigrationException(string msg, int dc) : base(msg + REPORT_MESSAGE)
31+
{
32+
DC = dc;
33+
}
34+
}
35+
36+
internal class PhoneMigrationException : DataCenterMigrationException
37+
{
38+
internal PhoneMigrationException(int dc)
39+
: base($"Phone number registered to a different DC: {dc}.", dc)
40+
{
41+
}
42+
}
43+
44+
internal class FileMigrationException : DataCenterMigrationException
45+
{
46+
internal FileMigrationException(int dc)
47+
: base($"File located on a different DC: {dc}.", dc)
48+
{
49+
}
50+
}
51+
52+
internal class UserMigrationException : DataCenterMigrationException
53+
{
54+
internal UserMigrationException(int dc)
55+
: base($"User located on a different DC: {dc}.", dc)
56+
{
57+
}
58+
}
59+
60+
internal class NetworkMigrationException : DataCenterMigrationException
61+
{
62+
internal NetworkMigrationException(int dc)
63+
: base($"Network located on a different DC: {dc}.", dc)
64+
{
65+
}
66+
}
67+
68+
69+
}

0 commit comments

Comments
 (0)