How to use Telegram API in C# to send a message
Asked Answered
H

9

49

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 ?

Hagan answered 7/7, 2015 at 14:25 Comment(3)
You should put more effort into your question if you want anyone to help you. Read the How to ask a good question guide.Sebastien
problems about using github projects is very strange when we download and use very easy from other sites like codeplex or codeproject but android project and some c# libraries in github and relations for required libraries is very hard things for students. and starter users in start using from githubPicayune
What did you eventually use for your project?Rad
G
30
  1. Install-Package Telegram.Bot
  2. Create a bot using the botfather
  3. get the api key using the /token command (still in botfather)
  4. 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

Giddy answered 6/11, 2015 at 6:26 Comment(6)
I'm trying your code, but it doesn't do anything.. I've created a bot, have I to do something else to use it?Yean
You confused guy with you library for Telegram Bot Api. He wants to use Telegram APILaceration
The subject of the question is about Telegram API not Telegram Bot API.Ringhals
I get this error: Invalid token format . My token is such as "3bd8d2839afbb0ba2cf566678b7b0bc2"Ingurgitate
@Ingurgitate , You must get your token form @BotFather, then you can use it in any Telegram Bot Libarary :)Historicism
@Giddy How can I connect once with singleton pattern? I mean I don't want to create a new API every time.Cecilycecity
J
24

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);
}
Jugular answered 3/8, 2019 at 20:50 Comment(4)
Very neat answer, no need to install packageEverhart
I'm using the same for the last one n a half year, absolutely no issue, easy and steadyHaddix
Thanks for the answer. Chat ID needs to be generated. Using @ChannelName is not working.Lungki
Nice, but you should wrap WebClient in a using statement.Furniture
L
14

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);
                }
            }
        }

    }
 }}
Lapointe answered 10/12, 2016 at 0:2 Comment(3)
I can not install TLSharp using Nuget because module DotNetZip doesn't compatible with AndroidKim
It's hard to use TLSharp, Telegram.Bot is more useful :)Historicism
Use Phone number directly instead of first_name like x.Phone == "91987...."Lovel
B
10

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");
Blasted answered 15/10, 2021 at 3:9 Comment(0)
P
5

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");
Palatalized answered 14/11, 2016 at 5:59 Comment(3)
The subject of the question is about Telegram API not Telegram Bot API.Ringhals
This is a good answer for some use cases e.g. automated publishing without having to create an appPortamento
@mychanel is not working. We need to enter chat ID.Lungki
F
3

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;
    }
}
Father answered 20/5, 2021 at 16:21 Comment(1)
It's a good idea to encode the message before putting it in the url variable, but the code worked fine for me.Pertinacity
J
1

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

Josephinejosephson answered 9/9, 2015 at 14:54 Comment(3)
I've seen a bot called ArzoBot written using this library if I'm not mistaken. Seems to work just fine!Madea
inline queries seem not to be received by this API? i used the code provided in the secion 'How can I use it?'Peroneus
The subject of the question is about Telegram API not Telegram Bot API.Ringhals
C
0

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

Cordless answered 13/3, 2020 at 14:18 Comment(0)
G
-5

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:

Gabriellegabrielli answered 7/7, 2015 at 21:7 Comment(6)
The question is not about bots, but the telegram API itself (for writing a client app)Lou
sure is not about bots. but using a bot is a simple way to reach the goal "send a simple message to a number".Gabriellegabrielli
Telegram bots cannot directly send messages to users using their phone number or even user ID. Bots can only send messages to chat_ids (representing a user or a group). So the user needs to start the conversation before the bot can send anything to them.Lou
exactly. and a bot can be used to receive updates from a system or even to control something, through a webhook. maybe that's the user wants. no need to create an account, no need to mess with telegram client apis, more difficult to manage. perhaps not everyone knows about this possibility, it is better to turn someone towards something which is not known to exist rather than not give answers, in my opinion.Gabriellegabrielli
The question is not about bots, but the telegram API itselfSappington
The subject of the question is about Telegram API not Telegram Bot API.Ringhals

© 2022 - 2024 — McMap. All rights reserved.