Tutorial API Telegram - Membuat sistem kirim pesan ke telegram berbasis android
Membuat sistem kirim pesan ke telegram berbasis android
Tutorial sederhana untuk pemula bagaimana membuat sistem pengirim pesan ke bot api telegram,
Pertama buat project baru di android studio, empity kemudian buat layout activity_main.xml berikut contoh code nya :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/home_dua">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/imagebackground"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_alignParentTop="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:background="@drawable/fitur"
android:paddingTop="20dp"
android:scaleType="fitEnd" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/imagebackground"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:text="Kirim pesan ke telegram"
android:textSize="15sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<EditText
android:id="@+id/edit_text_message"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@drawable/button_round_1"
android:backgroundTint="@color/graybackground"
android:hint="Tulis pesan disini"
android:inputType="text"
android:padding="10dp"
android:textColor="@color/black"
android:textColorHint="@color/gray"
android:textSize="12dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<TextView
android:id="@+id/text_view_result"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/coloraccent"
android:backgroundTint="@color/blue_400"
android:inputType="text"
android:padding="10dp"
android:textColor="@color/black"
android:textColorHint="@color/gray"
android:textSize="12dp" />
</LinearLayout>
<Button
android:id="@+id/button_send"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="20dp"
android:background="@drawable/button_del"
android:text="Kirim"
android:textColor="@color/white" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="15dp" />
<ListView
android:id="@+id/list_view_messages"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:layout_width="match_parent"
android:layout_height="15dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
kemudian masuka implementation retrofit di build.gradle :
plugins {
id 'com.android.application'
}
android {
compileSdk 33
defaultConfig {
applicationId "com.input.sendtelegram"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'androidx.appcompat:appcompat-resources:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
implementation 'org.jsoup:jsoup:1.11.3'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
}
Buatlah class dengan nama MainActivity kemudian masukan code dibawah ini :
package com.input.sendtelegram;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.input.sendtelegram.api.TelegramApiClient;
import com.input.sendtelegram.item.Message;
import com.input.sendtelegram.item.MessageAdapter;
import com.input.sendtelegram.json.TelegramResponse;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextMessage;
private Button buttonSend;
private TextView textViewResult;
String disableback;
ImageView images;
private ListView listViewMessages;
private List<Message> messageList;
private MessageAdapter messageAdapter;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
disableback = "false";
editTextMessage = findViewById(R.id.edit_text_message);
buttonSend = findViewById(R.id.button_send);
textViewResult = findViewById(R.id.text_view_result);
images = findViewById(R.id.imagebackground);
listViewMessages = findViewById(R.id.list_view_messages);
buttonSend.setOnClickListener(this);
// Membuat adapter untuk menampilkan daftar pesan
messageList = new ArrayList<>();
messageAdapter = new MessageAdapter(this, messageList);
listViewMessages.setAdapter(messageAdapter);
// Mengambil daftar pesan dari SharedPreferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Set<String> messageSet = sharedPreferences.getStringSet("messages", new HashSet<>());
for (String messageString : messageSet) {
try {
JSONObject messageJson = new JSONObject(messageString);
String chatId = messageJson.getString("chatId");
String text = messageJson.getString("text");
Date sentDate = new Date(messageJson.getLong("sentDate"));
messageList.add(new Message(chatId, text, sentDate));
} catch (JSONException e) {
e.printStackTrace();
}
}
messageAdapter.notifyDataSetChanged();
}
@Override
public void onClick(View v) {
if (v == buttonSend) {
String chatId = "5583058455";
String message = editTextMessage.getText().toString();
TelegramApiClient telegramApiClient = TelegramApiClient.getInstance();
telegramApiClient.sendMessage(chatId, message, new Callback<TelegramResponse>() {
@Override
public void onResponse(Call<TelegramResponse> call, Response<TelegramResponse> response) {
if (response.body().isOk) {
textViewResult.setText("Pesan berhasil dikirim");
// Menyimpan pesan yang berhasil dikirim ke SharedPreferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
Set<String> messageSet = sharedPreferences.getStringSet("messages", new HashSet<>());
JSONObject messageJson = new JSONObject();
try {
messageJson.put("chatId", chatId);
messageJson.put("text", message);
messageJson.put("sentDate", new Date().getTime());
messageSet.add(messageJson.toString());
editor.putStringSet("messages", messageSet);
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
// Menambahkan pesan ke daftar dan memperbarui adapter
messageList.add(new Message(chatId, message, new Date()));
messageAdapter.notifyDataSetChanged();
} else {
textViewResult.setText("Pesan gagal dikirim.");
}
}
@Override
public void onFailure(Call<TelegramResponse> call, Throwable t) {
textViewResult.setText("Error: " + t.getMessage());
}
});
}
}
}
Kemudian buat layout item untuk menyimpan item pesan yang sudah terkirim ke telegram dengan nama item_message.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_view_messages"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/text_view_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:textSize="16sp" />
<TextView
android:id="@+id/text_view_sent_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:textColor="#2196F3"
android:textSize="16sp" />
</LinearLayout>
</RelativeLayout>
Buatlah nama package baru misal com.telegram.example.json. kemudian buat class di folder tersebut dengan nama TelegramResponse kemudian masukan code diabwah ini :
package com.input.sendtelegram.json;
import com.google.gson.annotations.SerializedName;
public class TelegramResponse {
@SerializedName("ok")
public boolean isOk;
@SerializedName("description")
public String description;
}
Kemudian kita harus membuat item message nya agar menampilkan semua item pesan yang terkirim ke telegram :
Buat folder package dengan nama item kemudian buat class dengan nama Message :
package com.input.sendtelegram.item;
import java.util.Date;
public class Message {
private String chatId;
private String text;
private Date sentDate;
public Message(String chatId, String text, Date sentDate) {
this.chatId = chatId;
this.text = text;
this.sentDate = sentDate;
}
public String getChatId() {
return chatId;
}
public String getText() {
return text;
}
public Date getSentDate() {
return sentDate;
}
}
Selanjutnya buat adapter dengan nama MessageAdapter kemudian masukan code dibawah ini :
package com.input.sendtelegram.item;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.input.sendtelegram.R;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
public class MessageAdapter extends ArrayAdapter<Message> {
public MessageAdapter(Context context, List<Message> messages) {
super(context, 0, messages);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_telegram, parent, false);
}
// TextView textViewChatId = convertView.findViewById(R.id.text_view_chat_id);
TextView textViewText = convertView.findViewById(R.id.text_view_text);
TextView textViewSentDate = convertView.findViewById(R.id.text_view_sent_date);
// textViewChatId.setText(message.getChatId());
textViewText.setText(message.getText());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
textViewSentDate.setText(dateFormat.format(message.getSentDate()));
return convertView;
}
}
Kemudian kita buat folder package dengan nama api di dalam folder tersebut nanti kita akan menaruh koneksi api ke telegramnya, buatlah clas dengan nama TelegramApiClient :
package com.input.sendtelegram.api;
import com.input.sendtelegram.json.TelegramResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class TelegramApiClient {
private static final String TELEGRAM_API_BASE_URL = "https://api.telegram.org/bot{BOT TOKEN LETAKAN DISINI}/";
private static TelegramApiClient instance;
private TelegramApiService apiService;
private TelegramApiClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(TELEGRAM_API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(TelegramApiService.class);
}
public static TelegramApiClient getInstance() {
if (instance == null) {
instance = new TelegramApiClient();
}
return instance;
}
public void sendMessage(String chatId, String text, Callback<TelegramResponse> callback) {
Call<TelegramResponse> call = apiService.sendMessage(chatId, text);
call.enqueue(callback);
}
}
Lalu buat class TelegramApiService salin code dibawah ini :
package com.input.sendtelegram.api;
import com.input.sendtelegram.json.TelegramResponse;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface TelegramApiService {
@FormUrlEncoded
@POST("sendMessage")
Call<TelegramResponse> sendMessage(
@Field("chat_id") String chatId,
@Field("text") String text
);
}
Berikut toturial sederhana bagaimana membuat sistem pengiriman pesan berbasis android menggunakan api telegram , jika artikel ini kurang dimengerti kamu bisa download langsung source codenya di github Download Via Github.
Apa Reaksi Anda?






