Click here to Skip to main content
15,889,876 members
Articles / Programming Languages / C#

Remote Folder Explorer in C# with Telegram API

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
29 Aug 2023CPOL6 min read 5.8K   252   14   1
Bot program and an API program to send and receive commands between controlling computer and target device using Telegram API
In this article, I show how to implement a Bot program and an API program, designed to send and receive commands between a controlling computer and a target device using Telegram API.

Image 1

Image 2

Image 3

Introduction

The first program is the Bot (BotServiceApp), and its task is to implement the commands that will send from the controlling computer. It will be equipped with an interface to show and analyze data traffic. This program should be run on the target device.

Program API (RemoteFolderExplorer) will run on the controlling computer. The task of this program is to send commands, receive responses, and analyze them in order to display them on the user interface.

To make it easier to understand the working mechanisms, I made the following image:

Image 4

Let's assume that we're exploring a specific folder in the explorer program on our device. Here, the program will create a new command instance (a set of variables summarized in a class), and this class will be translated into JSON. The command will be then sent to the Telegram Bot through the Telegram Server. At this moment, the Bot Program receives the command and translates it again into the class of the same type from which it was translated. The command will then be executed on the target computer. After that, the program will create a response and translate it into JSON, and send it back to our device. Finally, it will be translated and analyzed and displayed on the user interface in the explorer program in the controlling computer.

To get our Program to work, we need three things:

  1. Create a Telegram Bot to send or receive commands from it
  2. The token for the Bot we created
  3. The API ID and API Hash that enable us to connect the API with Server

In this article, we will learn how to get all of them.

Let's begin.

Create Telegram Bot and Get its Token

The First Step

Open your telegram. In the search field, type @Botfather, then click on the first Bot in the search list, as shown in the picture:

Image 5

The Second Step

After clicking on the Botfather, a new window will open in the Telegram, as shown below:

Image 6

In this window, enter the start command in the input field, as shown below, then a list of all available commands will appear, also as shown in the image below:

Image 7

The Third Step

Click the command, /newbot. The BotFather will now ask you about the name of your Bot. Choose the name of the Bot and put it in the input field. Then the Bot Father will ask again about the username of the Bot, so put the username in the input field and don't forget that the name must end with the word Bot.

The following shows the step:

Image 8

Create Telegram API

Definition: It is a library that enables us to fully control our Telegram account from sending messages to receiving messages to controlling our Bot.

Obtaining authorization to control our Telegram account: To be able to get authorization to control your Telegram account, you must follow the next steps:

  1. We open the following link https://my.telegram.org/apps. We put our number, then click on Next, and then a message will arrive on our Telegram account with the confirmation code. We then take the code and put it in the input field and click Next.
  2. We enter the panel to create our own Telegram application, as shown below:

Image 9

Now we will need to fill in the first and second fields, point to the desktop platform, click on create application, and then a new window will appear containing our ID and hash.

Create the Explorer Program

After we have obtained the necessary information to control the Bot (token) and control our Telegram account (ID and hash), we can start programming our own set of programs.

We will start by programming the explorer program, which will send commands, receive responses from the target computer, and display data in an understandable way on our device.

First, we need to install the necessary libraries in our project. The following libraries are required to get our program working:

  • WTelegramClient

    Using the Paket-Manager-Console, enter the following commands:

    NuGet\Install-Package WTelegramClient -Version 3.5.3
  • Newtonsoft.Json

    Using the Paket-Manager-Console, enter the following commands:

    NuGet\Install-Package Newtonsoft.Json -Version 13.0.3

Now we are ready to start programming. First, we need to connect to the Telegram server. The following code will take care of establish connection with Telegram:

C#
.
.
.
WTelegram.Client _client;
.
.

private async void Connect(int ApiID, string ApiHash, string Phone) {

  _client = new WTelegram.Client(ApiID, ApiHash);
  await DoLogin(Phone);

}

In the above code, we define a new instance of Client class as input we have enter our telegram hash a telegram id after that, we try to login with our number in the Telegram server.

C#
private async Task DoLogin(string loginInfo) {
  string what = await _client.Login(loginInfo);
  if (what != null) {
    Log.Debug(what + ", , is required to connect with telegram Server ");
    return;
  } else {
    Log.Info( " successfully connected with telegram Server ");
  }
}

For the DoLogin method, we try to connect with Telegram server using the login method in our client instance. If we already have a valid session file, the method will return null and we will successfully be connected with the Telegram API, otherwise the method will return the name if the missing or required field (which most commonly value will be the confirm code) and this code will get as a Telegram message after you input the API ID and hash.

C#
await DoLogin(Confirm_Code);

After we get the confirm code, we will use the DoLogin method again to input the confirm code and then, we will successfully connect with Telegram API.

It's important to note that after we successfully connect with Telegram, we don't need to input the confirm code again because the library will create a session file to use it to connect automatically with telegram after inputting our ID, hash, and our number.

So now, we are connected with the Telegram API and we are ready to start. The next step will be create a thread that organizes the incoming response and the outgoing requests. Something like this will do the job:

C#
public delegate void SetSignalWaitingForFile(CommandInfo Info);
public delegate void SetSignalFileIsNowAvailable(bool Error, CommandInfo Info);
public class WaitingForFileThread {

  private object syncRoot = new object();
  public CommandInfo CommandInfo {
    get;
    set;
  }
  public bool SignalSet {
    get;
    set;
  }
  public bool Error {
    get;
    set;
  }
  public Client _client {
    get;
    set;
  }
  public IPeerInfo TargetUser {
    get;
    set;
  }

  public event SetSignalWaitingForFile SetSignalWaitingForFile;

  public event SetSignalFileIsNowAvailable SetSignalFileIsNowAvailable;

  public void StartWaitingAsync() {

    lock(this.syncRoot)
    ThreadPool.QueueUserWorkItem(_ = > ThreadProc());
  }
  public void Set(bool _Error) {
    lock(this.syncRoot) {
      if (!this.SignalSet) {
        this.SignalSet = true;
        this.Error = _Error;
      }
    }
  }

  async void ThreadProc() {
    Error = false;
    this.SignalSet = false;
    SetSignalWaitingForFile(CommandInfo);
    string jsontxt = JsonConvert.SerializeObject(CommandInfo);
    await _client.SendMessageAsync(TargetUser.ToInputPeer(), jsontxt);
    while (!this.SignalSet) {}
    if (!Error)
      SetSignalFileIsNowAvailable(false, this.CommandInfo);
    else
      SetSignalFileIsNowAvailable(true, this.CommandInfo);
  }
}

This class will convert the commands into JSON and send it to the Telegram Bot to be revised later from the target device. This class will also create a thread that will be waiting for response from the target device and trigger an event after receiving the expected response. This event will take care of processing the response and display it on the app.

Create the Bot Program

As I have already explained, for the Bot, we create a separate program so that we can run it on the target PC.

First, we need to install the necessary libraries in our project.

  • Telegram.Bot

    Using the Paket-Manager-Console, enter the following commands:

    NuGet\Install-Package Telegram.Bot -Version 19.0.0
  • Newtonsoft.Json

    Using the Paket-Manager-Console, enter the following commands:

    NuGet\Install-Package Newtonsoft.Json -Version 13.0.3
  • System.Management

    Using the Paket-Manager-Console, enter the following commands:

    NuGet\Install-Package System.Management -Version 7.0.2
  • SharpAESCrypt.dll

    Using the Paket-Manager-Console, enter the following commands:

    NuGet\Install-Package SharpAESCrypt.dll -Version 1.3.4

Now we can start programming. First, we need to connect to the Telegram server. The code below takes care of connecting to Telegram. Remember, we are working with the Bot API now and not the API used by Telegram.

C#
async Task HandleUpdateAsync(ITelegramBotClient Client,
           Update update, CancellationToken cancellationToken) {

  var chatId = update.Message.Chat.Id;

  try {
    string msg = update.Message.Text;
    if (msg == " Hi ")
      await BotClient.SendTextMessageAsync(chatId, " Hello World ");
  } catch (Exception exc) {

    await BotClient.SendTextMessageAsync(chatId, exc.Message);
  }
}
C#
Task HandlePollingErrorAsync(ITelegramBotClient botClient,
     Exception exception, CancellationToken cancellationToken) {
  return Task.CompletedTask;
}
C#
.
.
.

BotClient = new TelegramBotClient(tocken_tb.Text);
var receiverOptions = new ReceiverOptions {
  AllowedUpdates = Array.Empty <updatetype>()
};

BotClient.ReceiveAsync(
  updateHandler: HandleUpdateAsync,
  pollingErrorHandler: HandlePollingErrorAsync,
  receiverOptions: receiverOptions,
  cancellationToken: CTS.Token
);
.
.
. </updatetype>

In the structure of the program, we rely heavily on the command pattern. This will greatly organize our code and save us a lot of work.

Image 10

Note: In the explorer program, I have disabled the encrypt and decrypt button. Although they are fully functional, sometimes they trigger an error, so enable them at your discretion.

In the following video, I show you how to use the program:

History

  • 29th August, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mystery1234-Sep-23 0:52
professionalMystery1234-Sep-23 0:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.