How Use Telegram Api in C# WIth SharpTelegram - c#

How Use Telegram API in C# With SharpTelegram
i use this https://github.com/Everbytes/SharpTL
seed message to phone number have telegram in c#
i need sample use of this lib tanx

You might want to take a look at this C# telegram Library instead: https://github.com/sochix/TLSharp
Also you might want to get started on learning their API and building your own library from scratch.
Here are some notes to get you started: https://stackoverflow.com/a/32809138/44080
Cheers

There is now WTelegramClient, using the latest Telegram Client API protocol (connecting as a user, not bot).
The library is very complete but also very easy to use. Follow the README on GitHub for an easy introduction.
To send a message to someone can be as simple as:
using TL;
using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var result = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+PHONENUMBER" } });
await client.SendMessageAsync(result.users[result.imported[0].user_id], "Hello");
//or by username:
//var result = await client.Contacts_ResolveUsername("USERNAME");
//await await client.SendMessageAsync(result.User, "Hello");

With C# telegram Library at https://github.com/sochix/TLSharp
TLSharpTests.cs contains examples:
public async Task ImportContactByPhoneNumberAndSendMessage()
{
// User should be already authenticated!
var store = new FileSessionStore();
var client = new TelegramClient(store, "session");
await client.Connect();
Assert.IsTrue(client.IsUserAuthorized());
var res = await client.ImportContactByPhoneNumber(NumberToSendMessage);
Assert.IsNotNull(res);
await client.SendMessage(res.Value, "Test message from TelegramClient");
}

Related

C# API - Provide download of files from Azure Blobstorage

I am currently working on a problem I've encountered while using Azure Blob Storage together with C# API. I also didn't find a fitting solution in the questions here since most of them just download files once and they're done.
What I want to achieve is to have an API as a proxy for handling file downloads for my mobile clients. Therefore I need fast response / fast first byte responses since the mobile applications have a rather low timeout of five seconds.
[HttpGet, Route("{id}")]
[Authorize(Policy = xxxxx)]
public async Task<FileStreamResult> Get(Guid tenantId, Guid id)
{
if (tenantId == default)
{
throw new ArgumentException($"Tenant id '{tenantId}' is not valid.");
}
if (id == default)
{
throw new ArgumentException($"Package id '{id}' is not valid.");
}
var assetPackage = await _assetPackageService.ReadPackage(myenum.myvalue, tenantId, id).ConfigureAwait(false);
if (assetPackage == null)
{
return File(new MemoryStream(), "application/octet-stream");
}
return File(assetPackage.FileStream, assetPackage.ContentType);
}
public async Task<AssetPackage> ReadPackage(AssetPackageContent packageContent, Guid tenantId, Guid packageId)
{
var blobRepository = await _blobRepositoryFactory.CreateAsync(_settings, tenantId.ToString())
.ConfigureAwait(false);
var blobPath = string.Empty;
//some missing irrelevant code
var blobReference = await blobRepository.ReadBlobReference(blobPath).ConfigureAwait(false);
if (blobReference == null)
{
return null;
}
var stream = new MemoryStream();
await blobReference.DownloadToStreamAsync(stream).ConfigureAwait(false);
stream.Seek(0, SeekOrigin.Begin);
return new AssetPackage(packageContent, stream, blobReference.Properties.ContentType);
}
I am aware that MemoryStream is terrible for downloading and stuff since it consumes the files into memory before distributing it to the client.
How would you tackle this? Is there a easy solution to have my API act as a proxy rather than downloading the whole file and then let the client download it again from my api?
Possible and working solution is - as silent mentioned - adding the Azure Storage to the Azure API Management. You could add authorization or work with SAS links which might or might not fit your application.
I followed this guide to setup my architecture and it works flawlessly. Thanks to silent for the initial idea.

Multiple Conversations For Direct Line Client

I'm trying to use the Microsoft.Bot.Connector.DirectLine .NET client to connect to my Direct Line Channel. My client application will have many conversations open at once (like 1000+).
What I'm trying to do is efficiently create a single Direct Line client object which can receive messages for all my conversations and NOT have a single client per conversation.
This below code is from:
https://learn.microsoft.com/en-us/azure/bot-service/bot-service-channel-directline-extension-net-client?view=azure-bot-service-4.0
The problem is that to create a new conversation I need to create a new client which I think would eventually exhaust use up a lot of sockets. Does anyone know if I can create a single connection and then listen for multiple conversations?
Thanks
static async Task Main(string[] args)
{
Console.WriteLine("What is your name:");
var UserName = Console.ReadLine();
var tokenClient = new DirectLineClient(
new Uri(endpoint),
new DirectLineClientCredentials(secret));
var conversation = await tokenClient.Tokens.GenerateTokenForNewConversationAsync();
var client = new DirectLineClient(
new Uri(endpoint),
new DirectLineClientCredentials(conversation.Token));
await client.StreamingConversations.ConnectAsync(
conversation.ConversationId,
ReceiveActivities);
var startConversation = await client.StreamingConversations.StartConversationAsync();
var from = new ChannelAccount() { Id = startConversation.ConversationId, Name = UserName };
var message = Console.ReadLine();
while (message != "end")
{
try
{
var response = await client.StreamingConversations.PostActivityAsync(
startConversation.ConversationId,
new Activity()
{
Type = "message",
Text = message,
From = from,
ChannelData = new Common.ChannelData() { FromNumber = "+17081234567"}
});
}
catch (OperationException ex)
{
Console.WriteLine(
$"OperationException when calling PostActivityAsync: ({ex.StatusCode})");
}
message = Console.ReadLine();
}
Console.ReadLine();
}
public static void ReceiveActivities(ActivitySet activitySet)
{
if (activitySet != null)
{
foreach (var a in activitySet.Activities)
{
if (a.Type == ActivityTypes.Message && a.From.Id == "MyBotName")
{
Console.WriteLine($"<Bot>: {a.Text}");
}
}
}
}
I think using the Direct Line streaming extensions would be problematic for your purposes. I'm guessing your custom SMS channel would itself be an app service. Since an app service can (and probably should, in your case) be scaled so that multiple instances are running simultaneously, suppose two SMS messages from the same conversation go to two instances of your channel. In addition to having each instance of your channel using many web sockets to talk to many bots, multiple instances of your channel may use duplicated web sockets to talk to the same bot. There's also the problem of each bot itself needing to support streaming extensions.
Rather than using using Direct Line streaming extensions, you might consider using traditional Direct Line. This would involve receiving activities from the bots by polling a Direct Line endpoint.
Since Direct Line is a channel itself that you'd be using on top of your own channel, you might also consider cutting out Direct Line altogether. That way you wouldn't have two channels between the user and the bot. You could send HTTP requests to each bot's endpoint directly, and the activities the bots would receive would contain the service URL for your channel, allowing your channel to receive messages from the bots.

Firestore real-time-updates in c#

I'm trying to subscribe to real-time updates with Cloud Firestore in c# using Google.Cloud.Firestore.V1Beta1. I'm using the following code, which receives updates for a short time, until the stream is closed. Has anyone got FirestoreClient.Listen to work?
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize streaming call, retrieving the stream object
FirestoreClient.ListenStream duplexStream = firestoreClient.Listen();
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
IAsyncEnumerator<ListenResponse> responseStream = duplexStream.ResponseStream;
while (await responseStream.MoveNext())
{
ListenResponse response = responseStream.Current;
Console.WriteLine(response);
}
});
// Send requests to the server
var citiesPath = string.Format("projects/{0}/databases/{1}/documents/cities/CJThcwCipOtIEAm2tEMY", projectId, databaseId);
// Initialize a request
var dt = new DocumentsTarget { };
dt.Documents.Add(citiesPath);
ListenRequest request = new ListenRequest
{
Database = new DatabaseRootName(projectId, databaseId).ToString(),
AddTarget = new Target
{
Documents = dt
}
};
// Stream a request to the server
await duplexStream.WriteAsync(request);
// Await the response handler.
// This will complete once all server responses have been processed.
Console.WriteLine("Awaiting responseHandlerTask");
await responseHandlerTask;
Edit 1:
I've tried setting the expiration explicitly to never expire, but still no luck, I get 5 minutes in then receive a RST_STREAM.
//Setup no expiration for the listen
CallSettings listenSettings = CallSettings.FromCallTiming(CallTiming.FromExpiration(Expiration.None));
// Initialize streaming call, retrieving the stream object
FirestoreClient.ListenStream duplexStream = firestoreClient.Listen(listenSettings);
Edit 2:
It seems like a bit of a kludge, but I found it works to keep track of the last resetToken, catch the exception, then restart the request with the request token. I've updated the code that makes the original request to take an optional resumeToken.
ListenRequest request = new ListenRequest
{
Database = new DatabaseRootName(projectId, databaseId).ToString(),
AddTarget = new Target
{
Documents = dt
}
};
if (resumeToken != null)
{
Console.WriteLine(string.Format("Resuming a listen with token {0}", resumeToken.ToBase64()));
request.AddTarget.ResumeToken = resumeToken;
}
// Stream a request to the server
await duplexStream.WriteAsync(request);
It's not perfect, but I think it's the way Google implemented it in Node.js. It does result in an API call every 5 minutes, so there is some expense to it. Maybe that's the why it works this way?
Thanks
Until Jon finishes the official support, you can use something I put together if you need it right away. https://github.com/cleversolutions/FirebaseDotNetRamblings/blob/master/FirebaseDocumentListener.cs Its an extension method you can drop into your project and use like this:
//Create our database connection
FirestoreDb db = FirestoreDb.Create(projectId);
//Create a query
CollectionReference collection = db.Collection("cities");
Query qref = collection.Where("Capital", QueryOperator.Equal, true);
//Listen to realtime updates
FirebaseDocumentListener listener = qref.AddSnapshotListener();
//Listen to document changes
listener.DocumentChanged += (obj, e) =>
{
var city = e.DocumentSnapshot.Deserialize<City>();
Console.WriteLine(string.Format("City {0} Changed/Added with pop {1}", city.Name, city.Population));
};

Discord C# User Join messages

I'm using Discord.Net in C#, making a bot. My bot works fantastic so far, but I want it to automatically assign users a specific role when they join a specific server. I've never actually learned any C#, only a bit of C++ so I know the basic Grammar. How would I go about this?
I'm assuming I would use UserJoined, but doing this heeds results telling me to use it before or after a += or -+ (Which I understand, but I don't understand it's usefullness in this given scenario)
You gave little information to work with but here is how to do it in all releases (so far):
This is IN the dependency map but below the "handlecommand", CommandHandleAsync or HandleCommandAsync:
client.UserJoined += AnnounceJoinedUser; //Hook into the UserJoined event of the client.
This is under the dependency map:
public async Task AnnounceJoinedUser(SocketGuildUser user) //Welcomes the new user
{
var channel = client.GetChannel(/*/TextChannelID/*/) as SocketTextChannel; // Gets the channel to send the message in
await channel.SendMessageAsync($"Welcome {user.mention} to {channel.Guild.Name}"); //Welcomes the new user
}
In case any of you wanted to send a message directly to the joining user
client.UserJoined += HandleUserJoinedAsync;
private async Task HandleUserJoinedAsync(SocketGuildUser gUser)
{
if (gUser.IsBot || gUser.IsWebhook) return;
var dmChannel = await gUser.GetOrCreateDMChannelAsync();
await dmChannel.SendMessageAsync("Witaj");
}
For all those who need an answer, in this period, I leave you this piece of code, just to send a message to a user's join, (1 line):
Client.UserJoined += join;
private async Task join(SocketGuildUser user)
{
await (user.Guild.DefaultChannel).SendMessageAsync("Text")
return;
}

How to use Telegram API in C# to send a message

I want use Telegram API in C# for send a simple message to a number. I found some lib's on GitHub but I am not able to use them.
Can anyone give a simple code ? Can I simply make HTTP calls ?
Install-Package Telegram.Bot
Create a bot using the botfather
get the api key using the /token command (still in botfather)
use this code:
var bot = new Api("your api key here");
var t = await bot.SendTextMessage("#channelname or chat_id", "text message");
You can now pass a channel username (in the format #channelusername)
in the place of chat_id in all methods (and instead of from_chat_id in
forwardMessage). For this to work, the bot must be an administrator in
the channel.
https://core.telegram.org/bots/api
Here is the easiest way I found so far. I found it here, thanks to Paolo Montalto https://medium.com/#xabaras/sending-a-message-to-a-telegram-channel-the-easy-way-eb0a0b32968
After creating a Telegram bot via BotFather and getting your destination IDs
via https://api.telegram.org/bot[YourApiToken]/getUpdates
you can send a message to your IDs by issuing an HTTP GET request to Telegram BOT API using the following URL https://api.telegram.org/bot[YourApiToken]/sendMessage?chat_id=[DestitationID]&text=[MESSAGE_TEXT]
Details on a simple way to create a bot and get IDs may be found here: https://programmingistheway.wordpress.com/2015/12/03/send-telegram-messages-from-c/
You can test those url strings even directly in browser.
Here is a simple method I use in C# to send messages, without dependency on any bot api related dll and async calls complication:
using System.Net;
...
public string TelegramSendMessage(string apilToken, string destID, string text)
{
string urlString = $"https://api.telegram.org/bot{apilToken}/sendMessage?chat_id={destID}&text={text}";
WebClient webclient = new WebClient();
return webclient.DownloadString(urlString);
}
use this code :)
with https://github.com/sochix/TLSharp
using TeleSharp.TL;
using TLSharp;
using TLSharp.Core;
namespace TelegramSend
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TelegramClient client;
private async void button1_Click(object sender, EventArgs e)
{
client = new TelegramClient(<your api_id>, <your api_key>);
await client.ConnectAsync();
}
string hash;
private async void button2_Click(object sender, EventArgs e)
{
hash = await client.SendCodeRequestAsync(textBox1.Text);
//var code = "<code_from_telegram>"; // you can change code in debugger
}
private async void button3_Click(object sender, EventArgs e)
{
var user = await client.MakeAuthAsync(textBox1.Text, hash, textBox2.Text);
}
private async void button4_Click(object sender, EventArgs e)
{
//get available contacts
var result = await client.GetContactsAsync();
//find recipient in contacts
var user = result.users.lists
.Where(x => x.GetType() == typeof(TLUser))
.Cast<TLUser>()
.Where(x => x.first_name == "ZRX");
if (user.ToList().Count != 0)
{
foreach (var u in user)
{
if (u.phone.Contains("3965604"))
{
//send message
await client.SendMessageAsync(new TLInputPeerUser() { user_id = u.id }, textBox3.Text);
}
}
}
}
}}
There is now WTelegramClient, using the latest Telegram Client API protocol (connecting as a user, not bot).
The library is very complete but also very easy to use. Follow the README on GitHub for an easy introduction.
To send a message to someone can be as simple as:
using TL;
using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var result = await client.Contacts_ResolveUsername("USERNAME");
await client.SendMessageAsync(result.User, "Hello");
//or by phone number:
//var result = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+PHONENUMBER" } });
//client.SendMessageAsync(result.users[result.imported[0].user_id], "Hello");
1-first create a channel in telegram (for example #mychanel)
2-create a telegram bot (for example #myTestBot) and get api token for next step
3-add #myTestBot to your channel(#mychanel) as administrator user
4-use below code for send message:
var bot = new TelegramBotClient("api_token_bot");
var s = await bot.SendTextMessageAsync("#mychanel", "your_message");
this code work for me:
using System.Net;
public class TelegramBot
{
static readonly string token = "123456789:AAHsxzvZLfFAsfAY3f78b8t6MXw3";
static readonly string chatId = "123456789";
public static string SendMessage(string message)
{
string retval = string.Empty;
string url = $"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatId}&text={message}";
using(var webClient = new WebClient())
{
retval = webClient.DownloadString(url);
}
return retval;
}
}
I've written a client library for accessing Telegram bot's API and its source code is available in the Github. You can browse to the Telebot.cs file to see a sample of how to send a message to the bot API.
Github URL: github.com/mrtaikandi/Telebot
Nuget URL: nuget.org/packages/Telebot
Same unexplicable errors.
Solution: elevate the framework dastination to minimum 4.6; errors disappear.
Perhaps official support pages at
https://telegrambots.github.io/book/1/quickstart.html
are a little bit confusing saying: "...a .NET project targeting versions 4.5+"
bye
Just look and learn how to make a POST HTTP request with your favorite language.
Then learn how to use Telegram Bot API with the documentation:
https://core.telegram.org/bots
https://core.telegram.org/bots/api

Categories