public TLAbsInputPeer CreatePeerFromDialog(TLADialog dialog) { TLAbsInputPeer peer = null; if (dialog.Type == TLADialogType.Channel) { peer = new TLInputPeerChannel() { channel_id = dialog.Id, access_hash = dialog.AccessHash } } ; else if (dialog.Type == TLADialogType.Chat) { peer = new TLInputPeerChat() { chat_id = dialog.Id } } ; else if (dialog.Type == TLADialogType.User) { peer = new TLInputPeerUser() { user_id = dialog.Id, access_hash = dialog.AccessHash } } ; else { throw new TLCoreException("Type of TLDialog is unknown"); } return(peer); }
public async Task SendChatMessageAsync(int chatId, string message) { var tlChat = new TLInputPeerChat { chat_id = chatId }; await _messagesTL.SendMessageAsync(tlChat, message); }
public void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); var data = Toast.GetData(taskInstance); if (data != null) { if (data.ContainsKey("QuickMessage")) { var manualResetEvent = new ManualResetEvent(false); var text = data["QuickMessage"]; var messageText = text.Replace("\r\n", "\n").Replace('\v', '\n').Replace('\r', '\n'); var entitiesBase = Utils.GetEntities(ref messageText); var replyToMsgId = new int?(); var inputPeer = default(TLInputPeerBase); if (data.ContainsKey("from_id")) { inputPeer = new TLInputPeerUser { UserId = int.Parse(data["from_id"]), AccessHash = long.Parse(data["access_hash"]) }; } else if (data.ContainsKey("channel_id")) { inputPeer = new TLInputPeerChannel { ChannelId = int.Parse(data["channel_id"]), AccessHash = long.Parse(data["access_hash"]) }; replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : new int?(); } else if (data.ContainsKey("chat_id")) { inputPeer = new TLInputPeerChat { ChatId = int.Parse(data["chat_id"]) }; replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : new int?(); } TLVector<TLMessageEntityBase> entities = null; if (entitiesBase != null) { entities = new TLVector<TLMessageEntityBase>(entitiesBase); } var obj = new TLMessagesSendMessage { Peer = inputPeer, ReplyToMsgId = replyToMsgId, Message = messageText, Entities = entities, IsBackground = true, RandomId = TLLong.Random() }; ConnectionManager.Instance.UserId = SettingsHelper.UserId; ConnectionManager.Instance.SendRequest(new TLInvokeWithoutUpdates { Query = obj }, (message, ex) => { manualResetEvent.Set(); }, () => { manualResetEvent.Set(); }, ConnectionManager.DefaultDatacenterId, ConnectionType.Generic, RequestFlag.CanCompress | RequestFlag.FailOnServerError | RequestFlag.RequiresQuickAck | RequestFlag.Immediate); manualResetEvent.WaitOne(15000); } } deferral.Complete(); }
public IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count) { return(AsyncInfo.Run(async(token) => { var lastDate = 0; var lastMsgId = 0; var lastPeer = (TLInputPeerBase) new TLInputPeerEmpty(); var last = this.LastOrDefault(); if (last != null && last.TopMessageItem != null) { lastDate = last.TopMessageItem.Date; lastMsgId = last.TopMessage; if (last.Peer is TLPeerUser) { lastPeer = new TLInputPeerUser { UserId = last.Peer.Id }; } else if (last.Peer is TLPeerChat) { lastPeer = new TLInputPeerChat { ChatId = last.Peer.Id }; } else if (last.Peer is TLPeerChannel) { lastPeer = new TLInputPeerChannel { ChannelId = last.Peer.Id }; } } var response = await _protoService.GetDialogsAsync(lastDate, lastMsgId, lastPeer, 200); if (response.IsSucceeded) { foreach (var item in response.Result.Dialogs) { Add(item); } return new LoadMoreItemsResult { Count = (uint)response.Result.Dialogs.Count }; } return new LoadMoreItemsResult { Count = 20 }; })); }
private async Task UpdateChatChats() { rtbMain.SelectAll(); rtbMain.Selection.Text = ""; var selected = (GroupView)lbChatChats.SelectedItem; var peer = new TLInputPeerChat() { ChatId = selected.id }; currentPeer = peer; currentChatLastMessageId = 0; await UpdateChat(peer, currentChatLastMessageId); }
public async Task <TLAbsMessages> GetHistory(int id, long?hash, int limit, int offset, int maxId, HistoryPeer historyPeer) { await client.ConnectAsync(); TLAbsInputPeer peer = null; switch (historyPeer) { case HistoryPeer.Channel: if (hash == null) { throw new NullReferenceException("hash"); } peer = new TLInputPeerChannel { channel_id = id, access_hash = hash.Value }; break; case HistoryPeer.Chat: peer = new TLInputPeerChat { chat_id = id }; break; case HistoryPeer.User: if (hash == null) { throw new NullReferenceException("hash"); } peer = new TLInputPeerUser { user_id = id, access_hash = hash.Value }; break; default: throw new ArgumentOutOfRangeException(nameof(historyPeer), historyPeer, null); } return(await client.GetHistoryAsync(peer, offset, maxId, limit)); }
public async Task <bool> SendChatMessage(int chatId, string message) { await client.ConnectAsync(); var peer = new TLInputPeerChat { chat_id = chatId }; try { await client.SendMessageAsync(peer, message); return(true); } catch (InvalidOperationException e) { return(false); } }
public void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); var data = Toast.GetData(taskInstance); if (data != null) { if (data.ContainsKey("QuickMessage")) { var deviceInfoService = new DeviceInfoService(); var eventAggregator = new TelegramEventAggregator(); var cacheService = new InMemoryCacheService(eventAggregator); var updatesService = new UpdatesService(cacheService, eventAggregator); var transportService = new TransportService(); var connectionService = new ConnectionService(deviceInfoService); var statsService = new StatsService(); var manualResetEvent = new ManualResetEvent(false); var protoService = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, statsService); protoService.Initialized += (s, args) => { var text = data["QuickMessage"]; var messageText = text.Replace("\r\n", "\n").Replace('\v', '\n').Replace('\r', '\n'); var entitiesBase = Utils.GetEntities(ref messageText); var replyToMsgId = 0; var inputPeer = default(TLInputPeerBase); if (data.ContainsKey("from_id")) { inputPeer = new TLInputPeerUser { UserId = int.Parse(data["from_id"]), AccessHash = long.Parse(data["access_hash"]) }; } else if (data.ContainsKey("channel_id")) { inputPeer = new TLInputPeerChannel { ChannelId = int.Parse(data["channel_id"]), AccessHash = long.Parse(data["access_hash"]) }; replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : 0; } else if (data.ContainsKey("chat_id")) { inputPeer = new TLInputPeerChat { ChatId = int.Parse(data["chat_id"]) }; replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : 0; } TLVector <TLMessageEntityBase> entities = null; if (entitiesBase != null) { entities = new TLVector <TLMessageEntityBase>(entitiesBase); } var obj = new TLMessagesSendMessage { Peer = inputPeer, ReplyToMsgId = replyToMsgId, Message = messageText, Entities = entities, IsBackground = true, RandomId = TLLong.Random() }; protoService.SendInformativeMessageInternal <TLUpdatesBase>("messages.sendMessage", obj, result => { manualResetEvent.Set(); }, faultCallback: fault => { // TODO: alert user? manualResetEvent.Set(); }, fastCallback: () => { manualResetEvent.Set(); }); //var date = TLUtils.DateToUniversalTimeTLInt(protoService.ClientTicksDelta, DateTime.Now); //var message = TLUtils.GetMessage(SettingsHelper.UserId, inputPeer, TLMessageState.Sending, true, true, date, text, new TLMessageMediaEmpty(), TLLong.Random(), replyToMsgId); //var history = cacheService.GetHistory(inputPeer, 1); //cacheService.SyncSendingMessage(message, null, async (m) => //{ // await protoService.SendMessageAsync(message, () => // { // // TODO: fast callback // }); // manualResetEvent.Set(); //}); }; protoService.InitializationFailed += (s, args) => { manualResetEvent.Set(); }; //cacheService.Init(); protoService.Initialize(); manualResetEvent.WaitOne(15000); } } deferral.Complete(); }
public async void LoadFirstSlice() { var lastDate = 0; var lastMsgId = 0; var lastPeer = (TLInputPeerBase) new TLInputPeerEmpty(); var last = Items.LastOrDefault(); if (last != null && last.TopMessageItem != null) { lastDate = last.TopMessageItem.Date; lastMsgId = last.TopMessage; if (last.Peer is TLPeerUser) { lastPeer = new TLInputPeerUser { UserId = last.Peer.Id }; } else if (last.Peer is TLPeerChat) { lastPeer = new TLInputPeerChat { ChatId = last.Peer.Id }; } else if (last.Peer is TLPeerChannel) { lastPeer = new TLInputPeerChannel { ChannelId = last.Peer.Id }; } } //ProtoService.GetDialogsCallback(lastDate, lastMsgId, lastPeer, 200, (result) => //{ // var pinnedIndex = 0; // Execute.BeginOnUIThread(() => // { // foreach (var item in result.Dialogs) // { // if (item.IsPinned) // { // item.PinnedIndex = pinnedIndex++; // } // var chat = item.With as TLChat; // if (chat != null && chat.HasMigratedTo) // { // continue; // } // else // { // Items.Add(item); // } // } // IsFirstPinned = Items.Any(x => x.IsPinned); // PinnedDialogsIndex = pinnedIndex; // PinnedDialogsCountMax = config.PinnedDialogsCountMax; // }); //}); var response = await ProtoService.GetDialogsAsync(lastDate, lastMsgId, lastPeer, 200); if (response.IsSucceeded) { var config = CacheService.GetConfig(); var pinnedIndex = 0; var items = new List <TLDialog>(response.Result.Dialogs.Count); foreach (var item in response.Result.Dialogs) { if (item.IsPinned) { item.PinnedIndex = pinnedIndex++; } if (item.With is TLChat chat && chat.HasMigratedTo) { continue; } else { items.Add(item); } }
private async Task MainAsync(string[] args) { TelegramClient client = null; try { // -- if necessary, IP can be changed so the client can connect to the test network. Session session = null; // new Session(new FileSessionStore(), "session") //{ // ServerAddress = "149.154.175.10", // Port = 443 //}; //Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}"); client = new TelegramClient(APIId, APIHash); // subscribe an event to receive live messages //client.Updates += Client_Updates; await client.ConnectAsync(); Console.WriteLine($"Authorised: {client.IsUserAuthorized()}"); TLUser user = null; // -- If the user has already authenticated, this step will prevent account from being blocked as it // -- reuses the data from last authorisation. if (client.IsUserAuthorized()) { //user = client.Session.TLUser; } else { var registered = await client.IsPhoneRegisteredAsync(phone); var hash = await client.SendCodeRequestAsync(phone); Console.Write("Code: "); var code = Console.ReadLine(); if (!registered) { Console.WriteLine($"Sign up {phone}"); user = await client.SignUpAsync(phone, hash, code, "First", "Last"); } Console.WriteLine($"Sign in {phone}"); user = await client.MakeAuthAsync(phone, hash, code); } var contacts = await client.GetContactsAsync(); Console.WriteLine("Contacts:"); foreach (var contact in contacts.Users.OfType <TLUser>()) { var contactUser = contact as TLUser; Console.WriteLine($"\t{contact.Id} {contact.Phone} {contact.FirstName} {contact.LastName}"); } var dialogs = (TLDialogs)await client.GetUserDialogsAsync(); Console.WriteLine("Channels: "); foreach (var channelObj in dialogs.Chats.OfType <TLChannel>()) { var channel = channelObj as TLChannel; Console.WriteLine($"\tChat: {channel.Title}"); } Console.WriteLine("Groups:"); TLChat chat = null; foreach (var chatObj in dialogs.Chats.OfType <TLChat>()) { chat = chatObj as TLChat; Console.WriteLine($"Chat name: {chat.Title}"); var request = new TLRequestGetFullChat() { ChatId = chat.Id }; var fullChat = await client.SendRequestAsync <TeleSharp.TL.Messages.TLChatFull>(request); var participants = (fullChat.FullChat as TeleSharp.TL.TLChatFull).Participants as TLChatParticipants; foreach (var p in participants.Participants) { if (p is TLChatParticipant) { var participant = p as TLChatParticipant; Console.WriteLine($"\t{participant.UserId}"); } else if (p is TLChatParticipantAdmin) { var participant = p as TLChatParticipantAdmin; Console.WriteLine($"\t{participant.UserId}**"); } else if (p is TLChatParticipantCreator) { var participant = p as TLChatParticipantCreator; Console.WriteLine($"\t{participant.UserId}**"); } } var peer = new TLInputPeerChat() { ChatId = chat.Id }; var m = await client.GetHistoryAsync(peer, 0, 0, 0); Console.WriteLine(m); if (m is TLMessages) { var messages = m as TLMessages; foreach (var message in messages.Messages) { if (message is TLMessage) { var m1 = message as TLMessage; Console.WriteLine($"\t\t{m1.Id} {m1.Message}"); } else if (message is TLMessageService) { var m1 = message as TLMessageService; Console.WriteLine($"\t\t{m1.Id} {m1.Action}"); } } } else if (m is TLMessagesSlice) { bool done = false; int total = 0; while (!done) { var messages = m as TLMessagesSlice; foreach (var m1 in messages.Messages) { if (m1 is TLMessage) { var message = m1 as TLMessage; Console.WriteLine($"\t\t{message.Id} {message.Message}"); ++total; } else if (m1 is TLMessageService) { var message = m1 as TLMessageService; Console.WriteLine($"\t\t{message.Id} {message.Action}"); ++total; done = message.Action is TLMessageActionChatCreate; } } m = await client.GetHistoryAsync(peer, total, 0, 0); } } } //// -- Wait in a loop to handle incoming updates. No need to poll. //for (; ; ) //{ // await client.WaitEventAsync(); //} } catch (Exception e) { Console.WriteLine(e); } }
private async WTask.Task GetMessages(int uID, long uAccess, string type = "chat") { Loading(null, true); TLRequestMessagesGetHistory reqH = new TLRequestMessagesGetHistory(); reqH.setAddOffset(0); reqH.setLimit(100); reqH.setOffsetId(0); reqH.setOffsetDate(0); reqH.setMinId(0); reqH.setMaxId(999999); TLInputPeerUser upeer = new TLInputPeerUser(); TLInputPeerChat cpeer = new TLInputPeerChat(); TLInputPeerChannel chpeer = new TLInputPeerChannel(); switch (type.ToLower()) { case "user": upeer = new TLInputPeerUser(); upeer.setAccessHash(uAccess); upeer.setUserId(uID); reqH.setPeer(upeer); break; case "chat": cpeer = new TLInputPeerChat(); cpeer.setChatId(uID); reqH.setPeer(cpeer); break; case "channel": chpeer = new TLInputPeerChannel(); chpeer.setAccessHash(uAccess); chpeer.setChannelId(uID); reqH.setPeer(chpeer); break; default: break; } //var res = NewApi.Api().doRpcCall(reqH); var res = await WTask.Task.Run(() => NewApi.Api().doRpcCall(reqH)); string notify = ""; if (res == null) { notify = "درخواست نتیجه ای نداشت!"; //NotifyBar.ForeColor = Color.Orange; } else { MessagesDGV.Rows.Clear(); if (res.GetType() == typeof(TLMessages)) { try { TLMessages Messages = (TLMessages)res; foreach (var msg in Messages.getMessages()) { try { TLMessage message = (TLMessage)msg; MessagesDGV.Rows.Add(message.getDate(), message.getId(), message.getMessage(), uID, uAccess); } catch { } } } catch { } } else if (res.GetType() == typeof(TLMessagesSlice)) { try { TLMessagesSlice Messages = (TLMessagesSlice)res; foreach (var msg in Messages.getMessages()) { try { TLMessage message = (TLMessage)msg; MessagesDGV.Rows.Add(message.getDate(), message.getId(), message.getMessage(), uID, uAccess); } catch { } } } catch { } } else if (res.GetType() == typeof(TLChannelMessages)) { TLChannelMessages Messages = (TLChannelMessages)res; foreach (var msg in Messages.getMessages()) { try { TLMessage message = (TLMessage)msg; MessagesDGV.Rows.Add(message.getDate(), message.getId(), message.getMessage(), uID, uAccess); } catch { } } } } Loading(null, false, notify); }