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

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

Related

M2Mqtt in C# is not connected, doesn't give data

I have a project creating a websocket client side (Subscriber) to a MQTT publisher. I am quite new to C# and MQTT protocol. I follow some youtube video to make finish my very first lines connecting to this MQTT publisher to get all the train going in and out Helsinki station.
broker: "rata.digitraffic.fi"
Port: 80
Topic: trains-by-station/HKI (HKI abbr for Helsinki)
I use M2Mqtt library in dotnet to build the subscriber, somehow the client_MqttMsgPublishReceived function is never triggered. the client.IsConnected always returned false value!
You can find info of this mqtt protocol in the url below.
https://www.digitraffic.fi/rautatieliikenne/#websocket-mqtt
It gives me example in JavaScripts and it seems to run fine with the example of each MQTT. But when I tried to do it with my PC, it doesn't give me any thing, but
Hello World!!!
False
and the cmd window on hold.
SOOOO FRUSTRATING right now. it would be much appreciate if anyone can help me out.
BTW, I am using win10, I tried with dotnet 4/5/6 and m2mqtt 4.3.0.
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System;
namespace m2qttSubscriber
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!!!!");
MqttClient client = new MqttClient("rata.digitraffic.fi",
80,
false,
MqttSslProtocols.None,
null,
null);
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
string clientID = "myclientid_" + RandomDigits(4);
client.Connect(clientID);
Console.WriteLine(client.IsConnected);
client.Subscribe(new string[] { "trains-by-station/HKI" },
new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE}) ;
}
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Console.WriteLine("SOme thing is received");
string payload = Encoding.Default.GetString(e.Message);
Console.WriteLine("Recevied {0} from", payload);
}
static public string RandomDigits(int length)
{
var random = new Random();
string s = string.Empty;
for (int i = 0; i < length; i++)
s = String.Concat(s, random.Next(10).ToString());
return s;
}
}
}
As per the comments the library used (uPLibrary.Networking.M2Mqtt) does not support MQTT over Websockets (which is what rata.digitraffic.fi:80 offers).
If you are able to use standard MQTT (over TCP/IP) then rata-mqtt.digitraffic.fi:1883 works (OP succeeded with MqttClient client = new MqttClient("rata-mqtt.digitraffic.fi", 1883, false, MqttSslProtocols.None, null, null);) and this is generally preferable to using WebSockets (there are some situations where you have to use WebSockets; e.g. code running in a browser or to bypass some filters/proxies).
Alternatively there are other libraries that do offer support for MQTT over Websockets.

Asynchronous functions in Xamarin C# Android - Application stuck with thread

I'm trying to figure out a bug in my C# Xamarin Android code. Simple thing this application is ought to do - connect to the REST API, download the contents as a string for further analysis. At first my mistake was not including async tasks and using voids instead, but when I changed them the code seems to be stuck at point of retrieval of data.
String content;
private void OnClick1(object sender, EventArgs e)
{
output.Text = "";
GetJSONTextFromWeb("https://ameobea.me/osutrack/api/get_changes.php?user=XXXXXX&mode=0", "XXXXXX", "0");
while (content==null)
{
DoNothing();
}
output.Text = content;
}
private async Task GetJSONTextFromWeb(String address, String user, String modeID)
{
URL url = new URL(address);
URLConnection conn = url.OpenConnection();
//conn.AddRequestProperty("user", user); those lines are
//conn.AddRequestProperty("mode", modeID); removed for investigation.
//conn.Connect(); //this one caused the same issue.
content = (String)conn.Content; //Here the code seems to freeze without any warning.
}
private void DoNothing()
{
//literally. Made to await for the result.
}
Anyone knows the possible reason?
I'd suggest swapping out the use of that particular library in favor of the System.Http assembly, it's supported in Xamarin and is a lot better documented. I'd change your above code to something like below (Don't forget to declare System.Net.Http in the same place that you've declared your other assemblies).
using System.Net.Http;
async private void OnClick1(object sender, EventArgs e)
{
output.Text = "";
// await the return of a string from the url address
// awaiting this removes the need for the pointless while loop you were doing
content = await GetJSONTextFromWeb("https://ameobea.me/osutrack/api/get_changes.php?user=XXXXXX&mode=0");
output.Text = content;
}
private async Task<string> GetJSONTextFromWeb(String address)
{
// The library you were using is a poorly documented port from a JAVA library
// I'd suggest using the http library, it's supported in Xamarin and has better docs
var client = new HttpClient();
var data = await client.GetStringAsync(address);
return data;
}

How do I know if a telegram user joined my channel?

I am writing a C# desktop app.in this app I write a telegram Id of a user and it says that user is member of the channel or not. my bot is admin of the channel.
I use telegram.bot v9 nugget and searched about this issue all day.
I tried using GetChatMembersCountAsync() in v13 and a lot of other methods but didn't work.
static private Api bot = new Api("Token");
long id;
string channel="#ChannelName";
public Main()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
id = long.Parse(textBox7.Text);
if (IsMember(id,channel))
MessageBox.Show("This user is member of channel");
else
MessageBox.Show("This user is not a member of channel");
}
private bool IsMember(long id,string channelName)
{
//??????????????
}
Is there a method for a telegram bot access to list of members of a channel? what should I write in the IsMember() method?
Thank you very much
This problem solved by updating telegram.bot nugget to v10 and using GetChatMemberAsync method.
private bool IsMember(long id,string channelName)
{
var t = bot.GetChatMemberAsync(channelName, id);
if (t.Result.Status.ToString().Length > 25)
return false;
return true;
}
thank you
You can use getChatMember method to do that, see following example.
Regarding to Telegram Bot API documentation currently there is no method available for bots to get a list of chat members (channel or group).
Here is a small trick:
You can check the updates (messages) came from Telegram to your webhook, if new_chat_members field has a value and the chat_id field indicates that it's from your channel, then you may save the information about the recent users who joined your channel.

sending email in xamarin forms

I'm trying to send an email in my xamarin forms project, I have tried both in the iPhone simulator and on an iPhone device. When I push the send email button on the iPhone, nothing happens, not even a debug error. I have also made sure i am logged in with my email on the device.
I have used serviceDependency and followed the setup at this link:
https://developer.xamarin.com/recipes/ios/shared_resources/email/send_an_email/
my interface:
public interface InterfaceEmail
{
void sendEmail();
}
iOS implementation:
[assembly: Xamarin.Forms.Dependency(typeof(SendEmail))]
namespace myProject.iOS
{
public partial class SendEmail : InterfaceEmail
{
MFMailComposeViewController mailController;
public SendEmail() {}
public void sendEmail()
{
if (MFMailComposeViewController.CanSendMail)
{
mailController = new MFMailComposeViewController();
mailController.SetToRecipients (new string[] {"my#email.com"});
mailController.SetSubject ("test mail");
mailController.SetMessageBody ("This is a test", false);
mailController.Finished += (object sender, MFComposeResultEventArgs e) =>
{
Console.WriteLine(e.Result.ToString());
e.Controller.DismissViewController(true, null);
};
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailController, true, null);
}}}}
Implementation in my shared code:
async void Handle_ToolbarButton(object sender, System.EventArgs e)
{
var action = await DisplayActionSheet("What do you want to do?", "Abort", null, "Send email");
if(action == "Send email")
{
DependencyService.Get<InterfaceEmail>().sendEmail();
}
}
Does anyone have an idea on what could be wrong here?
For a better way to send email without even writing platform specific code install this nuget into your solution
xam.plugin.Messaging(https://www.nuget.org/packages/Xam.Plugins.Messaging/)
Then write the code below in PCL
var email = new EmailMessageBuilder()
.To("to.plugins#xamarin.com")
.Subject("Xamarin Messaging Plugin")
.Body("Well hello there from Xam.Messaging.Plugin")
.Build();
You can also add attachments. For more details please go through https://github.com/cjlotz/Xamarin.Plugins/blob/master/Messaging/Details.md
Probably it is related to this bug:
https://bugzilla.xamarin.com/show_bug.cgi?id=58933
Just remove DisplayActionSheet.
Or if you want to use it, then there is a temporary solution in this Xamarin forum topic
Add
await Task.Delay(100);
after DisplayActionSheet
The iPhone simulator will always return false to CanSendMail as it can not send mail. On a physical device, you will need to configure at least on e mail account.
Also:
Typo in:
[assembly: Xamarin.Forms.Dependency(typeof(sendEmail))]
Should be:
[assembly: Xamarin.Forms.Dependency(typeof(SendEmail))]
Typo in:
mailController.Finnished += ~~~~~
Should be:
mailController.Finished += ~~~~~

How Use Telegram Api in C# WIth SharpTelegram

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

Categories