46

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 ?

SandRock
  • 5,276
  • 3
  • 30
  • 49
Hadi Delphi
  • 469
  • 1
  • 4
  • 5
  • You should put more effort into your question if you want anyone to help you. Read the [How to ask a good question](http://stackoverflow.com/help/how-to-ask) guide. – Nasreddine Jul 07 '15 at 14:27
  • 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 github – saber tabatabaee yazdi Nov 20 '15 at 09:17
  • What did you eventually use for your project? – Charles Okwuagwu Feb 23 '16 at 11:26

9 Answers9

29
  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

code
  • 5,690
  • 4
  • 17
  • 39
arlak
  • 440
  • 4
  • 5
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);
}
TECNO
  • 162
  • 2
  • 3
  • 15
VVP
  • 349
  • 2
  • 6
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);
                }
            }
        }

    }
 }}
8

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");
Wizou
  • 1,336
  • 13
  • 24
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");
habiat
  • 1,245
  • 3
  • 16
  • 22
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;
    }
}
  • 1
    It's a good idea to encode the message before putting it in the url variable, but the code worked fine for me. – Simone Aug 05 '21 at 13:26
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

Community
  • 1
  • 1
mrtaikandi
  • 6,753
  • 16
  • 62
  • 93
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

-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:

mirko
  • 3
  • 1
  • 1
  • 6
  • 2
    The question is not about bots, but the telegram API itself (for writing a client app) – SepehrM Aug 11 '15 at 07:16
  • 1
    sure is not about bots. but using a bot is a *simple* way to reach the goal "send a simple message to a number". – mirko Aug 21 '15 at 20:04
  • 2
    Telegram bots cannot directly send messages to users using their phone number or even user ID. Bots can only send messages to `chat_id`s (representing a user or a group). So the user needs to start the conversation before the bot can send anything to them. – SepehrM Aug 22 '15 at 06:55
  • 2
    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. – mirko Aug 26 '15 at 15:31
  • 2
    The question is not about bots, but the telegram API itself – Milad Dec 20 '15 at 16:45
  • The subject of the question is about Telegram API not Telegram Bot API. – Alireza Zojaji Apr 21 '17 at 07:48