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

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.

Related

How to make the bot know if its messaged someone before? C# based SteamBot

Ok, firstly, I'm not very advanced at this, xD
In public override void OnMessage (string message, EChatEntryType type) I want to execute a series of tests to figure out which response to send.
The first test is to see if the message starts with a command. I'm an admin for a CSGO server group called "Warmup Servers" and this will be a string of parts which will generate and feed back information into a separate log file.
So I'm working on a custom UserHandler.cs for my steambot. I plan on writing a simple script, so that I can do exec [botname] TGTOnline & exec [botname] TGTOffline to tell the bot if using its account. (Like playing games or something on that account).
To test if the message starts with any of the predefined responses. (More to be added later)
To test if the bot has sent a message before. I don't want someone to start a conversation with me and the bot to be sending its default response every time it recieves a message, it would be annoying for both parties.
So before the default message is called, I need to have a function which checks to see if the bot account (Both bot response or human response) has sent a message to the user recently (Last 5 Minutes) and if it has, tell the bot to do nothing...
However I have no clue on where to start with this script and would love some advice!
Here is my TGTUserHandler.cs section which relates:
using System;
using SteamKit2;
using System.Threading.Tasks;
using System.Collections.Generic;
using SteamTrade;
using SteamTrade.TradeOffer;
using SteamTrade.TradeWebAPI;
namespace SteamBot
{
public class TGTUserHandler : UserHandler
{
private bool TGTOnline = false;
private TaskCompletionSource<string> _UserReport;
public TGTUserHandler(Bot bot, SteamID sid) : base(bot, sid) { }
private bool HandleUserReport(string message)
{
if (_UserReport == null)
return false;
//to be scripted in the morning
_UserReport = null;
return true;
}
public override void OnMessage(string message, EChatEntryType type)
{
if (message.StartsWith("!"))
{
if (message.StartsWith("!help"))
{
SendChatMessage("Welcome to the TGTGaming Automated Bots, We have very limited commands and currently do not do any type of automated trade. Here is the list of current commands you can use:");
SendChatMessage("!WarmupServers [help | Report | Issue] | This command is used for all issues related to the WarmupServer's. Do `!Warmupservers help` for more information");
SendChatMessage("!getadmin | This command is used to contact a TGTGaming administrator. Please do `!getadmin help` for more information");
}
if (message.StartsWith("!WarmupServers"))
{
if (message.StartsWith("!WarmupServers help"))
{
SendChatMessage("Warmup Servers Automated Support by TGTGamer");
SendChatMessage("Commands:");
SendChatMessage("!WarmupServers Report | Used to report a user for specific reasons. This is step by step process");
SendChatMessage("!WarmupServers issue | Used to report a issue with the servers. This is a step by step process");
}
if (message.StartsWith("!WarmupServers Report"))
{
GetUserResponse("You have started the user reporting process, please confirm this is what you wanted to do. [y/n]");
if (message.StartsWith("y"))
{
SendChatMessage("A few quick questions first, please respond yes or no");
GetUserResponse("Are you still in the server?");
if (message.StartsWith("y"))
{
GetUserResponse("Is the User you wish to report still in your server?");
if (message.StartsWith("y"))
{
GetUserResponse("Is there a VIP in the server?");
if (message.StartsWith("y"))
{
SendChatMessage("Please ask the VIP to do a !startvote on this user with your reason.");
}
else
{
_UserReport = new TaskCompletionSource<string>();
return _UserReport.Task;
}
}
else
{
_UserReport = new TaskCompletionSource<string>();
return _UserReport.Task;
}
}
else
{
_UserReport = new TaskCompletionSource<string>();
return _UserReport.Task;
}
}
else
{
SendChatMessage("You have cancelled this action");
}
}
}
}
else
{
if (TGTOnline)
{
//general Responses
if (message.StartsWith("Hello"))
{
SendChatMessage("What's up?");
}
if (message.StartsWith("Heya"))
{
SendChatMessage("Hello");
}
if (message.StartsWith("Hi"))
{
SendChatMessage("Heya");
}
else
{
//defualt response
SendChatMessage(Bot.ChatResponse);
}
}
else
{
//defualt response
SendChatMessage(Bot.ChatResponse);
}
}
}
}
}
All and any help will be appreciated.
Kind regards.
TGT
External Links you may find useful:
Bot Github: https://github.com/Jessecar96/SteamBot/
UserHandler.cs: https://github.com/Jessecar96/SteamBot/blob/master/SteamBot/UserHandler.cs
Footnotes:
Steam Subscriber Agreement:
The steam Subscriber Agreement States the following:
You may not use Cheats, automation software (bots), mods, hacks, or
any other unauthorized third-party software, to modify or automate any
Subscription Marketplace process.
As I am using this bot to automate 3rd party server actions (Rcon Kick's, Server restarts & such) it is within the steam subscriber agreement acceptance for bots. If I then started to sell or buy automatically with this bot, it would breach the subscriber agreement.

How to programmatically pair a bluetooth device

I recently bought a Lilypad Simblee BLE Board and I'd like to pair it programmatically to my computer (using the 32feet.NET library in C#).
I'm aware the "How to programmatically pair a bluetooth device" has already been asked on StackOverflow (here for example), however for some reason, all my attempts to pair the device programmatically have failed. Indeed, I successfully paired the device with the "Manage Bluetooth devices" window in Windows 10 Settings panel (Settings > Devices > Bluetooth).
Firstly, I don't know the pairing method (either legacy or SSP) to use with my device. Windows never asked me for a PIN or something, so I guess it's SSP, but I'm unsure.
I searched on Google how to do a SSP pairing request with 32feet.NET: I found this.
However, once it discovered my device (the device discovery works properly), the pairing request instantly fails.
My code:
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
namespace HLK_Client
{
class HLKBoard
{
public event HLKBoardEventHandler HLKBoardConnectionComplete;
public delegate void HLKBoardEventHandler(object sender, HLKBoardEventArgs e);
private BluetoothClient _bluetoothClient;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
private BluetoothDeviceInfo _hlkBoardDevice;
private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
private BluetoothWin32Authentication _bluetoothAuthenticator;
public HLKBoard()
{
_bluetoothClient = new BluetoothClient();
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
_bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
_bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);
_bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
}
public void ConnectAsync()
{
_inRangeBluetoothDevices.Clear();
_hlkBoardDevice = null;
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
}
private void PairWithBoard()
{
Console.WriteLine("Pairing...");
bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);
if (pairResult)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Fail"); // Instantly fails
}
}
private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e)
{
_inRangeBluetoothDevices.AddRange(e.Devices);
}
private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e)
{
for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i)
{
if (_inRangeBluetoothDevices[i].DeviceName == "HLK")
{
_hlkBoardDevice = _inRangeBluetoothDevices[i];
PairWithBoard();
return;
}
}
HLKBoardConnectionComplete(this, new HLKBoardEventArgs(false, "Didn't found any \"HLK\" discoverable device"));
}
private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e)
{
e.Confirm = true; // Never reach this line
}
}
}
Why does the pairing request fail?
The answer to the question you linked has a plausible suggestion... did you read it?
Also you should look at this question as well.
32feet library is built around legacy pairing, so that you either need to know the pin of the device you are connecting to, or you supply it with a null to get a popup window to enter a pin.
It also says that the windows function used by 32feet is deprecated in newer versions of windows. If that's true, the reason it's failing instantly is because you've passed a null pin in your pairing request and for it to proceed windows needs to show a dialog which no longer exists.
What happens if you try to connect with the pin "0000" or "1234" ?
I'm looking at the source code of WindowsBluetoothSecurity.cs in 32feet.net and I see if a pairing request fails, it logs the error code to Debug.WriteLine, any chance you could post that error code here?
One good work around to this problem might be to import BluetoothAuthenticateDeviceEx and use that manually to complete the pairing request. If you don't want to do this manually, it looks like in the latest version of the 32feet source, there is actually a SSP pairing method that utilises this method but it's not public and it's not used anywhere so you'll need to access it via reflection:
typeof(BluetoothSecurity)
.GetMethod("PairRequest", BindingFlags.Static | BindingFlags.NonPublic)
.Invoke(null, new object[] { _hlkBoardDevice.DeviceAddress, BluetoothAuthenticationRequirements.MITMProtectionNotRequired });

Skype bot (translation from VB) not working

I was following a tutorial on youtube on how to create a simple Skype bot. It was written in VB and with my limited knowledge I did my best to recreate it in C#
I stumbled upon "handles" which I can only assume is related to the eventhandler in C#
This is the code I've got so far but when I message myself from another skype account it doesn't respond. I've made sure to accept the little popup on skype that allows 3rd party software.
public partial class Form1 : Form
{
Skype oSkype = new Skype();
string trigger = "!";
public Form1()
{
InitializeComponent();
oSkype.Attach(7, false);
oSkype.MessageStatus += new _ISkypeEvents_MessageStatusEventHandler(oSkype_MessageStatus);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void oSkype_MessageStatus(ChatMessage pMessage, TChatMessageStatus Status)
{
if (Status == TChatMessageStatus.cmsReceived || Status == TChatMessageStatus.cmsSent)
{
string msg = pMessage.Body;
Chat c = pMessage.Chat;
if (msg.StartsWith(trigger))
{
listBox1.Items.Add(DateTime.Now.ToLongTimeString() + ": " + pMessage.Sender.Handle + " sent you a message");
msg = msg.Remove(0, 1).ToLower();
if (msg == "test")
{
c.SendMessage("Test");
}
else
{
c.SendMessage("Unrecognizable command.");
}
}
}
}
}
The code from the tutorial that I was following had this instead:
oSkype_MessageStatus(pMessage as ChatMessage, Status as TChatMessageStatus) Handles oSkype.MessageStatus
The closest to what I could come to implement this in c# was to add the void to the eventhandler in public Form1() which you can see in my code.
Thanks in advance!
Skype4Com's chat functions are not supported in the newer Skype versions. They were deprecated somewhere in-between 2013-2014.
From Skype's blog post Feature evolution and support for the Skype Desktop API:
Iā€™m happy to share that we will be extending support for two of the most widely used features ā€“ call recording and compatibility with hardware devices ā€“ until we determine alternative options or retire the current solution. Although chat via third party applications, will cease to work as previously communicated.
It has been a while since I have worked with COM Skype bots, but your code seems to be fine.
Nevertheless, I would suggest you to move to a modern approach on bots. Please check out the new Microsoft Bot Framework

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

LiveConnectClient missing eventhandlers Live SDK 5.3 WP8

hi there :) il get right to it.
Problem :
when i try to instanciate LiveConnectClient and then try to access the event : GetCompleted
which supose to be in the LiveConnectClient is not showing and on all the examples i been looking at even those on here are using it. this is not the only class this is happening on it is also happening on LiveAuthClient as well no events even the post on the net says there should be.
i tried to reinstall Vs2012 and sdk wp8 and live sdk from scratch but have not solved it
for refrence i using this example to see if i can it to work :
//event triggered when Skydrive sign in status is changed
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
//if the user is signed in
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Accessing SkyDrive...";
//get the folders in their skydrive
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(btnSignin_GetCompleted);
client.GetAsync("me/skydrive/files?filter=folders,albums");
}
//otherwise the user isn't signed in
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
i got no luck solving it and running out of ideas. So im hoping one of u boys out there can shed some light on it or lend a hand with dew wise words :)
thanks in advance. and i do apologies if this is to long a post.
regards jens
Indeed, it seems like those events have been removed in the latest versions of the SDK. You don't need them though, thanks to the async/await keywords. First, mark your method as async, then call the GetAsync method with the await keyword. And place afterward the code you would normally put in the GetCompleted event:
private async void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
//if the user is signed in
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Accessing SkyDrive...";
//get the folders in their skydrive
var result = await client.GetAsync("me/skydrive/files?filter=folders,albums");
// Do here what you would normally do in btnSignin_GetCompleted
}
//otherwise the user isn't signed in
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}

Categories