Telegram C# example send message
Asked Answered
D

7

13

I can't find an example of sending message by telegram protocol from C#. I tried to use this but failed. Can you give me any examples?

Durward answered 31/3, 2015 at 8:26 Comment(2)
what is your problem?Anneal
First message after one year member ? Well welcome to SO. If you want some help, you have to help yourself first. What have you tried so far ?Cheat
I
13

TLSharp is basic implementation of Telegram API on C#. See it here https://github.com/sochix/TLSharp

Innutrition answered 10/4, 2015 at 13:46 Comment(8)
I got API hash by registering here(my.telegram.org/auth) .. however executing above code failed stating your hash is not registered.Giulia
How about receiving messages over that line? Is it possible too?Assistant
Yep, it'll be possible if we found a contributor or someone donates for this featureInnutrition
dear @SochiX i am using your library but it is so hard to understand and use because of documentation weeknessSiriasis
It's open-source so you're welcome to contribute for documentation improvement!Innutrition
hey SochiX I may be interested in contributing to your library; btw I'm wondering if it uses simple PUSH mode? see #29543214Juliojulis
Dear @SochiX i am using your library but it doesn't work, await client.ConnectAsync(); is success but i can't get contacts with this method GetContactsAsync()Rosenblum
This library is abandonedSackman
T
3

You can use the WTelegramClient library to connect to Telegram Client API protocol (as a user, not a 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");

Twosome answered 15/10, 2021 at 3:50 Comment(0)
A
2

For my bot I use Telegram.Bot nuget package. Full sample code is here.

Here is example of sending message in reply to incoming message.

// create bot instance
var bot = new TelegramBotClient("YourApiToken");

// test your api configured correctly
var me = await bot.GetMeAsync();
Console.WriteLine($"{me.Username} started");

// start listening for incoming messages
while (true) 
{
    //get incoming messages
    var updates = await bot.GetUpdatesAsync(offset);
    foreach (var update in updates)
    {
        // send response to incoming message
        await bot.SendTextMessageAsync(message.Chat.Id,"The Matrix has you...");
    }
}
Attainder answered 6/1, 2018 at 22:36 Comment(1)
The question is about the Telegram API. Not about bot api.Interdenominational
P
0

at the first step you have to generate a bot in botfather then use the code in bellow in C#

    private void SendMessage(string msg)
    {
        string url = "https://api.telegram.org/{botid}:{botkey}/sendMessage?chat_id={@ChanalName}&text={0}";
        WebClient Client = new WebClient();
        /// If you need to use proxy 
        if (Program.UseProxy)
        {
            /// proxy elements are variable in Program.cs
            Client.Proxy = new WebProxy(Program.ProxyUrl, Program.ProxyPort);
            Client.Proxy.Credentials = new NetworkCredential("hjolany", "klojorasic");
        }
        Client.DownloadString(string.Format(url, msg));
        }));
    }
Publicspirited answered 31/3, 2015 at 8:27 Comment(1)
The question is about Telegram API not BOT Api.Interdenominational
O
0

The simplest way is to send http request directly to the Telegram BOT API as url string, you may test those url strings even in your browser, please see details in my another answer here: https://mcmap.net/q/906181/-how-to-use-telegram-api-in-c-to-send-a-message

Omphale answered 3/8, 2019 at 21:8 Comment(0)
O
0

This is safer and independent:

Sub sendMessage(token As String, chat_id As String, Text As String)
    ServicePointManager.SecurityProtocol = 3072
    Dim url = $"https://api.telegram.org/bot{token}/sendMessage"
    Using web As New WebClient
        Dim data As New NameValueCollection
        data.Add("chat_id", chat_id)
        data.Add("text", Text)
        web.UploadValues(url, data)
    End Using
End Sub

Example

Dim botToken = "23213:geY9y9h098978HY0-h987U9Yhyu"
Dim channel = -1003249204990
Dim Msg = "hi how are you"
sendMessage(botToken, channel, Msg)
Orelee answered 23/7 at 17:18 Comment(0)
B
-1

Telegram has an official API that can do exactly what you need, you will have to look into http requests though..

Here is the documentation on sending a message:

Function

messages.sendMessage

Params

peer    InputPeer   User or chat where a message will be sent
message string  Message text
random_id   long    Unique client message ID required to prevent message resending

Query example

(messages.sendMessage (inputPeerSelf) "Hello, me!" 12345678901)

Return errors

Code    Type    Description
400 BAD_REQUEST PEER_ID_INVALID Invalid peer
400 BAD_REQUEST MESSAGE_EMPTY   Empty or invalid UTF8 message was sent
400 BAD_REQUEST MESSAGE_TOO_LONG    Message was too long.

Current maximum length is 4096 UTF8 characters

For the full documentation go here.

Beers answered 31/3, 2015 at 8:38 Comment(7)
I see official API, but i can't understand how to use that. Some solutions have quick start with authorization and etc.Durward
this is a pretty good explanation on how to authenticate though, if you know http requests with c# this wouldn't be really hard to implement.Beers
I agree, but some solutions has implemented protocol on async request and support encryption.Durward
it's ok how we can send the query to DC and wait for replay i read to many about serlizing and TL languae and payload but i didn't succed to send query to send authcodeSeasonal
@KhalidOmar how far have you been able to go? Have you gone beyond the AuthKey part? I wish there is better documentations, it makes it harder than it actually isReaves
@CharlesO I decide to go with telegram-bot it's easy to use and have a good lib at GitHub telegram.org/blog/bot-revolution github.com/MrRoundRobin/telegram.botSeasonal
@KhalidOmar if it gives you what you need. that's fine. I have not looked at the bot in detail though.Reaves

© 2022 - 2024 — McMap. All rights reserved.