TLSharp Send message to a group - c#

//get user dialogs
var dialogs = await client.GetUserDialogsAsync() as TLDialogs;
//find channel by title
var chat = dialogs.Chats
.Where(c => c.GetType() == typeof(TLChat))
.Cast<TLChat>()
.FirstOrDefault(c => c.Title == "zgzxbhsrbhdrbh");
//send message
await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = chat.Id },
"OUR_MESSAGE");
I`m trying this code, but it returns me InvalidOperationException: CHANNEL_INVALID. Can someone help?

You were quite right.
//Get dialogs
var dialogs = await client.GetUserDialogsAsync();
//get user chats
var chats = ((TeleSharp.TL.Messages.TLDialogsSlice)dialogs).Chats;
//find channel by title
var tlChannel = chats.Where(_ => _.GetType() == typeof(TLChannel))
.Select(_=>(TLChannel)_)
.Where(_=>_.Title.Contains("<Channel-Name>"))
.FirstOrDefault();
//send message
await client.SendMessageAsync(new TLInputPeerChannel()
{ ChannelId = tlChannel.Id, AccessHash =(long)tlChannel.AccessHash },
"OUR_MESSAGE");

There is a difference between sending to a group and sending to a channel
In your code, at the end of it, you called a command to send to a channel, and in the first one, you specified the type as a group. This is the latest exception. You can try this code and, God willing, the problem will be solved.
//get user dialogs
var dialogs = (TLDialogsSlice)await client.GetUserDialogsAsync();
//find channel by title
var chat = dialogs.Chats
.Where(c => c.GetType() == typeof(TLChat))
.Cast<TLChat>()
.FirstOrDefault(c => c.Title == "zgzxbhsrbhdrbh");
//send message
await client.SendMessageAsync(new TLInputPeerChat() { ChatId = chat.Id }, "OUR_MESSAGE");

Related

FILEREF_UPGRADE_NEEDED using GetFile function of TLSharp

I'm trying to dowload a file from a conversation in telegram. I`m using TLSharp lib...
Please check my code:
var result = await client.GetContactsAsync();
var user = result.Users
.OfType<TLUser>()
.FirstOrDefault(x => x.Phone == "<phoneNumber>");
var inputPeer = new TLInputPeerUser() { UserId = user.Id };
var res = await client.SendRequestAsync<TLMessages>(new TLRequestGetHistory() { Peer = inputPeer });
var document = res.Messages
.OfType<TLMessage>()
.Where(m => m.Media != null)
.Select(m => m.Media)
.OfType<TLMessageMediaDocument>()
.Select(md => md.Document)
.OfType<TLDocument>()
.First();
var resFile = await client.GetFile(
new TLInputDocumentFileLocation()
{
AccessHash = document.AccessHash,
Id = document.Id,
Version = document.Version
},
(int)Math.Pow(2, Math.Ceiling(Math.Log(document.Size, 2))) * 4);
This code is getting this exception:
FILEREF_UPGRADE_NEEDED
Please, there are any way to get a file from an conversation without get this error?
TLSharp seems no longer maintained. You might want to switch to WTelegramClient which is similar but better.
Then you can use the helper method that simplify the download process:
using (var stream = File.Create(outputFilename))
await client.DownloadFileAsync(document, stream);

EF Core async select InvalidOperationException

The following code
var merchant = await _dbContext.Merchants
.Include(m => m.Users)
.SingleAsync(m => m.MerchantId == id);
var userTasks = merchant.Users.Select(async u =>
{
var roles = await _userManager.GetRolesAsync(u);
return new MerchantUser
{
UserName = u.UserName,
Role = string.Join(",", roles)
};
}).ToList();
var users = await Task.WhenAll(userTasks);
return View(new MerchantViewModel
{
MerchantId = merchant.MerchantId,
MerchantName = merchant.Name,
MerchantUsers = users.ToList()
});
sometimes returns this error:
System.InvalidOperationException: A second operation started on this context before a previous operation completed.
However, this code does not. To my understanding, it's doing the same thing so I don't understand why it's failing.
var merchant = await _dbContext.Merchants
.Include(m => m.Users)
.SingleAsync(m => m.MerchantId == id);
var users = new List<MerchantUser>();
foreach (var user in merchant.Users)
{
var roles = await _userManager.GetRolesAsync(user);
users.Add(new MerchantUser
{
UserName = user.UserName,
Role = string.Join(",", roles)
});
}
return View(new MerchantViewModel
{
MerchantId = merchant.MerchantId,
MerchantName = merchant.Name,
MerchantUsers = users
});
var userTasks = merchant.Users.Select(async u => { … }).ToList();
var users = await Task.WhenAll(userTasks);
This will asynchronously start all those Select tasks at the same time and then wait for them to complete. So this will run multiple things in parallel. Since you are querying the user manager inside, this will not work since the underlying connection does not support parallel queries.
In contrast, your foreach loop will only run one query at a time, awaiting the GetRolesAsync before the next iteration begins. So instead of working in parallel, the roles will be read sequentially for all users.

SignalR library throws error when it application run without debug points and work fine while debugging

I have created a .net core chat application using SignalR and I need move to next user by clicking next button. When I click the next button it will trigger the method "getRemoteClientNext" inside the Hub class
public async Task getRemoteClientNext(string RemoteUserId)
{
var name = Context.User.Identity.Name;
var CurrentAppUser = _userManager.FindByNameAsync(name);
if(RemoteUserId != null) {
using (var db = _dBContext)
{
var remotename = db.Users.Find(RemoteUserId);
var RemoteUser = db.Connections.Where(c => c.UsersId != CurrentAppUser.Result.Id && c.UsersId != RemoteUserId && c.RemoteConnected == false).AsEnumerable().GroupBy(c => c.UsersId);
//var remoteConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id || u.UsersId == RemoteUserId).ToList();
//remoteConnection.ForEach(i => i.RemoteConnected = false);
var currntUserConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id).AsEnumerable().FirstOrDefault();
currntUserConnection.RemoteConnected = false;
db.SaveChanges();
var RemoteUserConnection = db.Connections.Where(u => u.UsersId == RemoteUserId).AsEnumerable().FirstOrDefault();
if (RemoteUserConnection != null)
{
RemoteUserConnection.RemoteConnected = false;
}
db.SaveChanges();
var connec = db.Connections.Where(c => c.UsersId == RemoteUserId);
if (connec.Count() == 0)
{
await Clients.Caller.SendAsync("ClienErrors", "The user is no longer connected");
}
else
{
foreach (var connection in connec)
{
await Clients.Client(connection.ConnectionID).SendAsync("maintainConnectionStatus", "Connecting a remote user......");
}
}
await Clients.Caller.SendAsync("maintainConnectionStatus", "Connecting a remote user......");
if (RemoteUser.Count() == 0)
{
await Clients.Caller.SendAsync("maintainConnectionStatus", "Connecting a remote user......");
}
else
{
var selectedRemoteUser = RemoteUser.First().ToList();
var currentUserConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id).AsEnumerable().FirstOrDefault();
// selectedRemoteUser.ForEach(c => c.RemoteConnected = true, c.Remo) ;
foreach(Connections con in selectedRemoteUser)
{
con.RemoteConnected = true;
con.RemoteConnectionID = currentUserConnection.ConnectionID;
currentUserConnection.RemoteConnectionID = con.ConnectionID;
}
// var currentUserConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id).AsEnumerable().FirstOrDefault();
var RemoteId = selectedRemoteUser.Select(u => u.UsersId).FirstOrDefault();
var RemoteName = db.Users.Find(RemoteId);
currentUserConnection.RemoteConnected = true;
db.SaveChanges();
//var RemoteId = selectedRemoteUser.Select(u => u.UsersId).FirstOrDefault();
//var RemoteName = db.Users.Find(RemoteId);
var connec2 = db.Connections.Where(c => c.UsersId == RemoteId);
if (connec2.Count() ==0)
{
await Clients.Caller.SendAsync("ClienErrors", "The user is no longer connected");
}
else
{
foreach (var connection in connec2)
{
await Clients.Client(connection.ConnectionID).SendAsync("SendRemoteUserId", CurrentAppUser.Result.Id, CurrentAppUser.Result.FirstName);
}
}
await Clients.Caller.SendAsync("SendRemoteUserId", RemoteId, RemoteName.FirstName);
}
}
}
}
in java script the event is like
document.getElementById("next").addEventListener("click", function (event) {
connection.invoke("getRemoteClientNext", RemoteUserId);
});
The issue I got is when I click the next button "getRemoteClientNext" will be triggered and work fine when it is debugging. If I disable all the debug points and run the application this will not work. But other functions like sending the chat messages using hub are working finely. Then I check the console and I saw the error message
Uncaught (in promise) Error: An unexpected error occurred invoking 'getRemoteClientNext' on the server.
at _this.callbacks. (signalr.js:2088)
at HubConnection.processIncomingData (signalr.js:2182)
at WebSocketTransport.HubConnection.connection.onreceive (signalr.js:1905)
at WebSocket.webSocket.onmessage (signalr.js:3949)
I removed the SignalR and try to install it again but it is not working and in add client side library also only showing Jquery.SignalR.js and Jquery.SignalR.min.js files. So I added Signalr.js file manually from another project.
Can any one tell me why this is happening is it error in SignalR library
This smells like a race condition just as SomeStudent suggested. Reading through the first couple of lines of code inside the getRemoteClient() method, you are missing an await.
I can't say with 100% certainty this will fix it, but I'm certain it could become a problem even if this wasn't the culprit.
// Add await here.
var CurrentAppUser = await _userManager.FindByNameAsync(name);

Test connection with TLSharp

I'm trying to send a message with TLSharp but cant,i dont get errors,it just execute the code and do nothing;
This is my method.
public virtual async Task SendMessageTest()
{
string NumberToSendMessage = "+55199999999";
if (string.IsNullOrWhiteSpace(NumberToSendMessage))
throw new Exception("TESTE");
// this is because the contacts in the address come without the "+" prefix
var normalizedNumber = NumberToSendMessage.StartsWith("+") ?
NumberToSendMessage.Substring(1, NumberToSendMessage.Length - 1) :
NumberToSendMessage;
var client = NewClient();
var tsk = client.ConnectAsync();
await client.ConnectAsync();
var result = await client.GetContactsAsync();
var user = result.users.lists
.OfType<TLUser>()
.FirstOrDefault(x => x.phone == normalizedNumber);
if (user == null)
{
throw new System.Exception("Number was not found in Contacts List of user: " + NumberToSendMessage);
}
await client.SendTypingAsync(new TLInputPeerUser() { user_id = user.id });
Thread.Sleep(3000);
await client.SendMessageAsync(new TLInputPeerUser() { user_id = user.id }, "TEST");
}
This is my code,is says is wait for activation,what should i do?
I'm trying to use this method also,but it doenst return nothing too.
I'm new to TelegramApi,what i'm doing wrong?
await client.ConnectAsync();
You should authorize first! And only after that you can call other methods. Look at the examples here.
In general you should write something like this:
var hash = await client.SendCodeRequestAsync(NotRegisteredNumberToSignUp);
var code = Console.ReadLine(); //Input the code, that was sent to your phone
var loggedInUser = await client.MakeAuthAsync(NotRegisteredNumberToSignUp, hash, code);

Outlook Contacts API - Paging Results

I'm trying to display ALL the Outlook contacts for a selected account. When an account has a few thousand contacts, the following code only shows the first n contacts. The contactResults object has a MorePagesAvailable property and a GetNextPageAsync() method available, but I clearly do NOT know how to use them. Can someone please enlighten me.
string token = (string)Session["access_token"];
string email = (string)Session["user_email"];
// Since we have the token locally from the Session, just return it here
OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"), async () => { return token; });
client.Context.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>((sender, e) => InsertXAnchorMailboxHeader(sender, e, email));
var contactResults = await client.Me.Contacts
.OrderBy(c => c.DisplayName)
.Take(2500)
.Select(c => new DisplayContact(c))
.ExecuteAsync();
foreach (DisplayContact displayContact in contactResults.CurrentPage)
System.Diagnostics.Debug.WriteLine(displayContact);
var contactResults = await client.Me.Contacts
.OrderBy(c => c.DisplayName)
.Select(c => new DisplayContact(c))
.ExecuteAsync();
while (true)
{
foreach (DisplayContact displayContact in contactResults.CurrentPage)
System.Diagnostics.Debug.WriteLine(displayContact);
if (contactResults.MorePagesAvailable)
contactResults = await contactResults.GetNextPageAsync();
else
break;
}

Categories

Resources