allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
repositories {
...
maven("https://jitpack.io")
}
dependencies {
implementation "com.github.ehsannarmani:EasyBot:latest_version"
}
dependencies {
implementation("com.github.ehsannarmani:EasyBot:latest_version")
}
Bot(
token = "put bot token here",
onUpdate = {
onText("test"){
reply("lib working fine")
}
}
).startPolling()
bot.startPolling(timeout = 60)
2. Use Webhook: In this type, automatically webserver will create with Ktor and automaticlly bot will call setWebhook (you don't need to setWebhook)
bot.launch(
port = 3000,
host = "127.0.0.1",
webhookUrl = "https://xxx.xx",
dropPendingUpdates = true of false
)
webhookUrl: webhook url must be your webserver address, if you are using this in your local system, you can use ngrok tool to get url from your local system like this:
ngrok http 3000
Note: You must enter the port that you entered in the launch method. it will give you address like: https://b114-94-131-98-78.eu.ngrok.io, use this address as webhookUrl in launch method
dropPendingUpdates: Also you can set this option for drop pending updates, if you set true for this param, pending updates in queue will not be considered and only new updates after launch will consider.
Bot(
...,
onUpdate = { update->
}
)
Bot(
...,
onUpdate = { update->
println(update?.message?.from?.id)
}
)
Note: for using better updates, read telegram bot document
Bot(
...,
onTextUpdate = { update->
println(update)
}
)
Also you can collect update shared flow from bot to get updates in other place of your code like this:
val bot = Bot(token = "...")
bot.update.collect { update->
println(update?.message?.text)
}
Note: to get update type, see this section.
Note: to get message type, see this section.
You can pass function for parameter onErrorThrown when you making instance from Bot to get errors like: serialization error and others:
Bot(
...,
onErrorThrown = { error->
}
)
val bot = Bot(...)
bot.sendMessage(TextMessage(
chatId = "@mrenk",
text = "Hello!",
parseMode = "markdown",
...
))
val bot = Bot(...)
bot.sendPhoto(PhotoMessage(
chatId = "@mrenk",
photo = "photo link here",
caption = "Hello!",
...
))
Note: for information about methods you can read telegram bot document.
You can use this methods in onUpdate,onTextUpdate,onErrorThrown functions without writing bot instance like this:
Bot(
...,
onUpdate = { update->
sendMessage(TextMessage(
chatId = update?.message?.chat?.id,
text = "Hello, bot working successfully"
))
sendPhoto(PhotoMessage(
chatId = update?.message?.chat?.id,
photo = "..."
))
...
}
)
bot.sendMessage(TextMessage(
chatId = "@mrenk",
text = "Hey!",
keyboard = InlineKeyboard(
keyboard = listOf(
listOf(
InlineKeyboardItem(text = "Key1",callbackData = "key1Data"),
InlineKeyboardItem(text = "Key2",callbackData = "key2Data"),
),
listOf(
InlineKeyboardItem(text = "Url",url = "https://github.com/ehsannarmani/EasyBot"),
)
)
)
))
onUpdate = { update->
if(update?.callbackQuery?.data == "key1Data"){
println("Key1 clicked!")
}
}
bot.sendMessage(TextMessage(
chatId = "@mrenk",
text = "Hey!",
keyboard = ReplyKeyboard(
keyboard = listOf(
listOf(
ReplyKeyboardItem(text = "Key1"),
ReplyKeyboardItem(text = "Key2"),
),
listOf(
ReplyKeyboardItem(text = "Contact",requestContact = true),
)
),
resizeKeyboard = true,
)
))
bot.sendMessage(TextMessage(
chatId = "@mrenk",
text = "Hey!",
keyboard = ForceReply()
))
bot.sendMessage(TextMessage(
chatId = "@mrenk",
text = "Hey!",
keyboard = RemoveKeyboard()
))
if (update.inlineQuery?.query == "hey"){
answerInlineQuery(AnswerInlineQuery(
inlineQueryId = update.inlineQuery?.id.toString(),
results = listOf(
InlineQueryResultArticle(
title = "this is result",
description = "this is description of result",
isPersonal = true,
...
)
)
))
}else if (update.inlineQuery?.query == "hi"){
answerInlineQuery(AnswerInlineQuery(
inlineQueryId = update.inlineQuery?.id.toString(),
results = listOf(
InlineQueryResultPhoto(
photoUrl = "url of photo",
...
)
)
))
}
...
Bot(
...,
onUpdate = { update->
onMessage{ message->
println("Any messages received!")
}
}
)
Bot(
...,
onUpdate = { update->
onText{ text->
println("a text message received!")
}
}
)
onText("hello"){
println("User sent to me hello")
}
Bot(
...,
onUpdate = { update->
onCommand("start"){
println("start command entered!")
}
}
)
Note: for default , this method call when messages contain command, for example if text entered '/start@EasyBot' this scope will call, if you dont want to this happen, you can pass false for second parameter of this method lile:
onCommand("start",false){
}
Bot(
...,
onUpdate = { update->
onPhoto{ photo->
println("a photo message received!")
}
onVoice{ voice->
println("a voice message received!")
}
onConatct{ contact->
println("a contact message received!")
}
// and all of other message types
}
)
Bot(
...,
onUpdate = { update->
onCallbackQuery{ callbackQuery->
print("callback query received")
}
}
)
onUpdate = { update->
onCallbackQuery("key1Data"){
println("key1Data pressed!")
}
}
Bot(
...,
onUpdate = { update->
onInlineQuery{ inlineQuery->
print("inline query update received!")
}
}
)
onUpdate = {update->
onInlineQuery("hi"){
println("hi inline query typed!")
}
}
onUpdate = { update->
onText("/start"){
reply("Hey! You started bot.")
}
}
You can delete messages with calling delete method on that message instead calling deleteMessage method
onUpdate = { update->
onCallbackQuery("key1Data"){ callbackQuery->
callbackQuery.message.delete()
}
onText("Violent content"){
update?.message?.delete()
}
}
You can edit text messages with calling editText method on that message instead calling editMessage method
onUpdate = { update->
onCallbackQuery("key1Data"){ callbackQuery->
callbackQuery.message.editText(text = "New message text")
}
}
You can edit messages keyboard with calling editKeyboard method on that message instead calling editMessage method
onUpdate = { update->
onCallbackQuery("key1Data"){ callbackQuery->
callbackQuery.message.editKeyboard(newKeyboard = InlineKeyboard(
keyboard= listOf(
listOf(
InlineKeyboardItem(text = "Key8", callbackData = "key8Data")
)
)
))
}
}
You can answer callback queries with calling answer method on callback query instead calling answerCallbackQuery method
onUpdate = { update->
onCallbackQuery("key1Data"){ callbackQuery->
callbackQuery.answer("Hey! you clicked on Key1 button!",alert= true)
}
}
bot.sendMessage(TextMessage(
chatId = "@mrenk",
text = "Hey!",
keyboard = InlineKeyboard(
keyboard = listOf(
listOf(
InlineKeyboardItem(text = "Key1",callbackData = "key1Data").onClick{ callbackQuery->
callbackQuery.answer("You clicked Key1!")
},
InlineKeyboardItem(text = "Key2",callbackData = "key2Data").onClick{
// do something
},
)
)
)
))
bot.sendMessage(TextMessage(
chatId = "@mrenk",
text = "Hey!",
keyboard = ReplyKeyboard(
keyboard = listOf(
listOf(
ReplyKeyboardItem(text = "Key1").onClick{ message->
reply("You clicked on Key1")
},
ReplyKeyboardItem(text = "Key2").onClick{
// do something
},
)
)
)
))
onUpdate = {
onMessage {
it.from.put(key = "foo",data = "this is data will saved in foo key")
it.from.put(key = "age",data = 22)
it.from.put(key = "grades",data = listOf(15,16,19,14))
}
}
Note: You can save data classes! But you must use Kotlinx Serialization library and mark your data class as @Serializable
@Serializable
data class Student(@SerialName("name") val name:String,@SerialName("age") val age:Int)
@Serializable
data class Teacher<T>(@SerialName("name") val name:String, @SerialName("subset") val subset:T)
Bot(
...,
onUpdate = {
onMessage {
it.from.put(key = "student",data = Student(name = "jax",age = 17))
it.from.put(key = "teacher",data = Teacher(name = "mr. jace",subset = Student(name = "alaska",age = 18)))
}
}
)
onUpdate = {
onMessage {
val stringData = it.from.get<String>(key = "foo")
val integerData:Int = it.from.get(key = "age")
val listData = it.from.get<List<Int>>(key = "grades")
val classData = it.from.get<Student>(key = "student")
}
}
onUpdate = {
onMessage {
val allStringDataSavedForUser = it.from.get<String>()
allStringDataSavedForUser.forEach{
val user = it.user
val key = it.key
val data = it.data
}
}
}
val allStringsSaved = bot.get<String>()
onUpdate = {
onMessage {
it.from.editData(key = "foo", newData = "x")
it.from.editData(key = "student", newData = Student(name = "alaska", age = 17))
}
}
onUpdate = {
onMessage {
it.from.deleteData<String>(key = "foo")
it.from.deleteData<Student>(key = "student")
}
}
onUpdate = { update->
update.message?.from?.register()
}
onUpdate = { update->
update.message?.from?.reRegister()
}
onUpdate = { update->
val self = update.message?.from?.getSelf()
}
onUpdate = { update->
val usersList = update.message?.from?.getUsers()
val usersCount = usersList.count()
...
}
onUpdate = { update ->
onMessage { msg ->
onCommand("start"){
step("name")
reply("send your name")
}
}
}
onUpdate = { update ->
onMessage { msg ->
onStep("name"){
reply("name received, your name is: $it")
}
}
}
onUpdate = { update ->
onMessage { msg ->
onCommand("start"){
step("name")
reply("send your name")
}
onStep("name"){ enteredName->
step("age")
reply("your name received , send your age")
}
onStep("age"){ enteredAge->
reply("your age received.")
}
}
}
onUpdate = { update->
when(update.updateType){
UpdateType.Message-> println("Message Update Received")
UpdateType.EditMessage-> println("A Message Edited")
UpdateType.ChannelPost-> println("A Channel Posted Something")
UpdateType.ChannelPostEdit -> println("A Channel Edited Some Posts")
UpdateType.JoinRequest -> println("Join Request Update Received")
UpdateType.InlineResult -> println("Inline Result Update Received")
UpdateType.PreCheckout -> println("PreCheckout Update Received")
UpdateType.Shipping -> println("Shipping Update Received")
UpdateType.CallbackQuery -> println("Callback Query Update Received")
UpdateType.InlineQuery -> println("Inline Query Update Received")
UpdateType.ChatMember -> println("Chat Member Update Received")
UpdateType.MyChatMember -> println("MyChatMember Update Received")
UpdateType.PollAnswer -> println("Someone put answer for a poll")
UpdateType.Poll -> println("Poll Update Received")
}
}
onUpdate = {
onMessage { msg ->
when(msg.messageType){
MessageType.Text -> print("Text Message Received")
MessageType.Photo -> print("Photo Message Received")
MessageType.Audio -> print("Audio Message Received")
MessageType.Voice -> print("Voice Message Received")
MessageType.Document -> print("Document Message Received")
MessageType.Gif -> print("Gif Message Received")
MessageType.Sticker -> print("Sticker Message Received")
MessageType.Poll -> print("Poll Message Received")
MessageType.Game -> print("Game Message Received")
MessageType.Invoice -> print("Invoice Message Received")
}
}
}