Compare commits

..

52 Commits

Author SHA1 Message Date
3e20835bc6 Update gradle.properties 2024-11-30 17:11:07 +06:00
c3ad2d4319 upgrade custom bot to include context data and additional context data 2024-11-30 14:42:21 +06:00
59fca968d7 update tgbotapi and include sample of context data in custom bot 2024-11-29 12:50:33 +06:00
f03ba5f177 Merge pull request #302 from InsanusMokrassar/renovate/telegram_bot_api_version
Update telegram_bot_api_version to v20.0.1
2024-11-13 13:53:07 +06:00
renovate[bot]
855d2c1296 Update telegram_bot_api_version to v20.0.1 2024-11-11 10:46:16 +00:00
280f5abce0 Merge pull request #294 from InsanusMokrassar/renovate/major-ktor-monorepo
Update dependency io.ktor:ktor-client-logging-jvm to v3
2024-11-04 01:39:22 +06:00
renovate[bot]
ed81e76ef8 Update dependency io.ktor:ktor-client-logging-jvm to v3 2024-11-03 19:39:16 +00:00
541b76b292 Merge pull request #301 from InsanusMokrassar/20.0.0
20.0.0
2024-11-02 00:34:52 +06:00
5b580b5a15 migration onto 20.0.0 2024-11-01 23:48:29 +06:00
86790ee414 add copyText sample button 2024-11-01 23:21:33 +06:00
0bbe430374 update ktgbotapi 2024-11-01 15:27:17 +06:00
b7d53a7410 Merge pull request #298 from InsanusMokrassar/19.0.0
19.0.0
2024-11-01 14:55:49 +06:00
73064db226 small adaptation 2024-10-30 18:09:23 +06:00
a50eda366d update dependencies and add webhooks sample 2024-10-30 14:38:46 +06:00
e34f0ec9d8 Update gradle-wrapper.properties 2024-10-22 17:36:59 +06:00
c2237f7e87 Merge pull request #297 from InsanusMokrassar/18.2.2
18.2.2
2024-10-22 17:35:39 +06:00
0bbc6a9555 Update gradle.properties 2024-10-22 17:22:41 +06:00
d4d8508abf add middlewares sample in custom bot 2024-10-15 13:52:26 +06:00
9acb64fda9 Merge pull request #291 from InsanusMokrassar/renovate/micro_utils_version
Update dependency dev.inmo:micro_utils.ktor.server to v0.22.4
2024-09-26 07:59:14 +06:00
renovate[bot]
760ae36207 Update dependency dev.inmo:micro_utils.ktor.server to v0.22.4 2024-09-26 01:59:00 +00:00
5c6b1b7171 Merge pull request #290 from InsanusMokrassar/renovate/serialization_version
Update dependency org.jetbrains.kotlinx:kotlinx-serialization-json to v1.7.3
2024-09-26 07:58:43 +06:00
6e06357541 Merge pull request #265 from InsanusMokrassar/renovate/ktor-monorepo
Update dependency io.ktor:ktor-client-logging-jvm to v2.3.12
2024-09-26 07:58:28 +06:00
38f46dfa3b Merge pull request #292 from InsanusMokrassar/renovate/telegram_bot_api_version
Update telegram_bot_api_version to v18.2.1
2024-09-26 07:57:57 +06:00
renovate[bot]
e7f7ef16ac Update telegram_bot_api_version to v18.2.1 2024-09-25 21:35:02 +00:00
renovate[bot]
d100a5a336 Update dependency org.jetbrains.kotlinx:kotlinx-serialization-json to v1.7.3 2024-09-19 18:27:24 +00:00
5f0f2ce76d Merge pull request #289 from InsanusMokrassar/18.2.0
18.2.0
2024-09-09 02:33:18 +06:00
14235e7bd4 update GiveawaysBot 2024-09-08 23:38:19 +06:00
6eafd89542 add println of giveaway content 2024-09-08 19:44:51 +06:00
ed2922045c add giveaways bot 2024-09-08 19:33:43 +06:00
21ec50c773 add opportunity to use test server in custom bot 2024-09-08 15:53:46 +06:00
ab362e8c3b start updating up to 18.2.0 2024-09-07 02:43:05 +06:00
346755b41c Merge pull request #282 from InsanusMokrassar/renovate/telegram_bot_api_version
Update telegram_bot_api_version to v18.1.0
2024-09-05 03:17:20 +06:00
renovate[bot]
a601674d71 Update telegram_bot_api_version to v18.1.0 2024-09-04 21:02:48 +00:00
renovate[bot]
cea610a0f8 Update dependency io.ktor:ktor-client-logging-jvm to v2.3.12 2024-09-02 02:00:00 +00:00
b6c92f754f Merge pull request #287 from InsanusMokrassar/18.0.0
18.0.0
2024-09-02 07:59:08 +06:00
023b810d07 update micro_utils dependency 2024-09-02 01:24:11 +06:00
0ec543d5c5 update sample of MemberUpdatedWatcher bot 2024-08-30 23:32:29 +06:00
777604e5a0 update new samples 2024-08-30 19:06:38 +06:00
999c33b2f5 Merge pull request #286 from Nik-mmzd/chatmemberupdated
Add MemberUpdatedWatcherBot example utilizing new 18.0.0 extensions
2024-08-30 18:42:18 +06:00
ca0427bfdd Merge branch '18.0.0' into chatmemberupdated 2024-08-30 18:41:59 +06:00
a62a14a599 migration onto 18.0.0 2024-08-30 18:40:39 +06:00
McModder
3efd3463a3 Add MemberUpdatedWatcherBot example utilizing new 18.0.0 extensions 2024-08-29 22:40:47 +03:00
590f9ec6d8 Merge pull request #280 from InsanusMokrassar/17.0.0
17.0.0
2024-08-15 19:17:08 +06:00
acdbd4d2ea update HelloBot 2024-08-15 01:51:10 +06:00
d2d913fca8 update telegram bots api 2024-08-14 23:33:43 +06:00
75726cac89 Merge pull request #276 from InsanusMokrassar/16.0.0
16.0.0
2024-08-12 08:13:59 +06:00
71b64689d0 Update gradle.properties 2024-08-12 02:32:28 +06:00
5ba2fc5bab update githab workflow 2024-08-11 19:52:15 +06:00
51a5bfb81a update gradle wrapper 2024-08-11 19:49:31 +06:00
35e330c016 update kotlin 2024-08-11 19:49:31 +06:00
90d447fbcf update up to 16.0.0 2024-08-11 19:49:31 +06:00
2c5da5da9f Merge pull request #278 from InsanusMokrassar/15.3.0
15.3.0
2024-08-02 19:29:33 +06:00
31 changed files with 812 additions and 38 deletions

View File

@@ -10,6 +10,7 @@ jobs:
- uses: actions/checkout@v2
- name: Install dependencies
run: |
sudo apt update
sudo apt install -y libcurl4-openssl-dev
- name: Set up JDK 17
uses: actions/setup-java@v1

1
.gitignore vendored
View File

@@ -1,4 +1,5 @@
.idea
.kotlin
out/*
*.iml
target

2
.template/bot/.env Normal file
View File

@@ -0,0 +1,2 @@
title=$prompt
subtitle=Subtitle of {{$title}}

View File

@@ -0,0 +1,9 @@
# {{$title}}
## Launch
```bash
../gradlew run --args="BOT_TOKEN"
```

View File

@@ -0,0 +1,22 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName="{{$title}}Kt"
{{$subtitle}}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
}

View File

@@ -0,0 +1,34 @@
import dev.inmo.kslog.common.KSLog
import dev.inmo.kslog.common.LogLevel
import dev.inmo.kslog.common.defaultMessageFormatter
import dev.inmo.kslog.common.setDefaultKSLog
import dev.inmo.micro_utils.coroutines.subscribeSafelyWithoutExceptions
import dev.inmo.tgbotapi.extensions.api.bot.getMe
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
/**
* This place can be the playground for your code.
*/
suspend fun main(vararg args: String) {
val botToken = args.first()
val isDebug = args.any { it == "debug" }
if (isDebug) {
setDefaultKSLog(
KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
println(defaultMessageFormatter(level, tag, message, throwable))
}
)
}
telegramBotWithBehaviourAndLongPolling(botToken, CoroutineScope(Dispatchers.IO)) {
// start here!!
val me = getMe()
println(me)
allUpdatesFlow.subscribeSafelyWithoutExceptions(this) { println(it) }
}.second.join()
}

View File

@@ -0,0 +1,208 @@
#!/usr/bin/env kotlin
/**
* Generates files and folders as they have been put in the folder. Envs uses common syntax, but
* values may contains {{${'$'}sampleVariable}} parts, where {{${'$'}sampleVariable}} will be replaced with variable value.
* Example:
*
* .env:
* sampleVariable=${'$'}prompt # require request from command line
* sampleVariable2=just some value
* sampleVariable3=${'$'}{sampleVariable}.${'$'}{sampleVariable2}
*
* Result variables:
* sampleVariable=your input in console # lets imagine you typed it
* sampleVariable2=just some value
* sampleVariable3=your input in console.just some value
*
* To use these variables in template, you will need to write {{${'$'}sampleVariable}}.
* You may use it in text of files as well as in files/folders names.
*
* Usage: kotlin generator.kts [args] folders...
* Args:
* -e, --env: Path to file with args for generation; Use "${'$'}prompt" as values to read variable value from console
* -o, --outputFolder: Folder where templates should be used. Folder of calling by default
* folders: Folders-templates
*/
import java.io.File
val console = System.console()
fun String.replaceWithVariables(envs: Map<String, String>): String {
var currentString = this
var changed = false
do {
changed = false
envs.forEach { (k, v) ->
val previousString = currentString
currentString = currentString.replace("{{$${k}}}", v)
changed = changed || currentString != previousString
}
} while (changed)
return currentString
}
fun requestVariable(variableName: String, defaultValue: String?): String {
console.printf("Enter value for variable $variableName${defaultValue ?.let { " [$it]" } ?: ""}: ")
return console.readLine().ifEmpty { defaultValue } ?: ""
}
fun readEnvs(content: String, presets: Map<String, String>): Map<String, String> {
val initialEnvs = mutableMapOf<String, String>()
content.split("\n").forEach {
val withoutComment = it.replace(Regex("\\#.*"), "")
runCatching {
val (key, value) = withoutComment.split("=")
val existsValue = presets[key]
if (value == "\$prompt") {
initialEnvs[key] = requestVariable(key, existsValue)
} else {
initialEnvs[key] = requestVariable(key, value.replaceWithVariables(initialEnvs))
}
}
}
var i = 0
val readEnvs = initialEnvs.toMutableMap()
while (i < readEnvs.size) {
val key = readEnvs.keys.elementAt(i)
val currentValue = readEnvs.getValue(key)
val withReplaced = currentValue.replaceWithVariables(readEnvs)
var changed = false
if (withReplaced != currentValue) {
i = 0
readEnvs[key] = withReplaced
} else {
i++
}
}
return presets + readEnvs
}
var envFile: File? = null
var outputFolder: File = File("./") // current folder by default
val templatesFolders = mutableListOf<File>()
var extensions: List<String>? = null
fun readParameters() {
var i = 0
while (i < args.size) {
val arg = args[i]
when (arg) {
"--env",
"-e" -> {
i++
envFile = File(args[i])
}
"--extensions",
"-ex" -> {
i++
extensions = args[i].split(",")
}
"--outputFolder",
"-o" -> {
i++
outputFolder = File(args[i])
}
"--help",
"-h" -> {
println("""
Generates files and folders as the have been put in the folder. Envs uses common syntax, but
values may contains {{${'$'}sampleVariable}} parts, where {{${'$'}sampleVariable}} will be replaced with variable value.
Example:
.env:
sampleVariable=${'$'}prompt # require request from command line
sampleVariable2=just some value
sampleVariable3=${'$'}{sampleVariable}.${'$'}{sampleVariable2}
Result variables:
sampleVariable=your input in console # lets imagine you typed it
sampleVariable2=just some value
sampleVariable3=your input in console.just some value
To use these variables in template, you will need to write {{${'$'}sampleVariable}}.
You may use it in text of files as well as in files/folders names.
Usage: kotlin generator.kts [args] folders...
Args:
-e, --env: Path to file with args for generation; Use "${'$'}prompt" as values to read variable value from console
-o, --outputFolder: Folder where templates should be used. Folder of calling by default
folders: Folders-templates
""".trimIndent())
Runtime.getRuntime().exit(0)
}
else -> {
val potentialFile = File(arg)
println("Potential file/folder as template: ${potentialFile.absolutePath}")
runCatching {
if (potentialFile.exists()) {
println("Adding file/folder as template: ${potentialFile.absolutePath}")
templatesFolders.add(potentialFile)
}
}.onFailure { e ->
println("Unable to use folder $arg as template folder")
e.printStackTrace()
}
}
}
i++
}
}
readParameters()
val envs: MutableMap<String, String> = envFile ?.let { readEnvs(it.readText(), emptyMap()) } ?.toMutableMap() ?: mutableMapOf()
println(
"""
Result environments:
${envs.toList().joinToString("\n ") { (k, v) -> "$k=$v" }}
Result extensions:
${extensions ?.joinToString()}
Input folders:
${templatesFolders.joinToString("\n ") { it.absolutePath }}
Output folder:
${outputFolder.absolutePath}
""".trimIndent()
)
fun File.handleTemplate(targetFolder: File, envs: Map<String, String>) {
println("Handling $absolutePath")
val localEnvs = File(absolutePath, ".env").takeIf { it.exists() } ?.let {
println("Reading .env in ${absolutePath}")
readEnvs(it.readText(), envs)
} ?: envs
println(
"""
Local environments:
${localEnvs.toList().joinToString("\n ") { (k, v) -> "$k=$v" }}
""".trimIndent()
)
val newName = name.replaceWithVariables(localEnvs)
println("New name $newName")
when {
!exists() -> return
isFile -> {
val content = useLines {
it.map { it.replaceWithVariables(localEnvs) }.toList()
}.joinToString("\n")
val targetFile = File(targetFolder, newName)
targetFile.writeText(content)
println("Target file: ${targetFile.absolutePath}")
}
else -> {
val folder = File(targetFolder, newName)
println("Target folder: ${folder.absolutePath}")
folder.mkdirs()
listFiles() ?.forEach { fileOrFolder ->
fileOrFolder.handleTemplate(folder, localEnvs)
}
}
}
}
templatesFolders.forEach { folderOrFile ->
folderOrFile.handleTemplate(outputFolder, envs)
}

View File

@@ -4,10 +4,23 @@ import dev.inmo.kslog.common.defaultMessageFormatter
import dev.inmo.kslog.common.setDefaultKSLog
import dev.inmo.micro_utils.coroutines.subscribeSafelyWithoutExceptions
import dev.inmo.tgbotapi.extensions.api.bot.getMe
import dev.inmo.tgbotapi.extensions.behaviour_builder.BehaviourContextData
import dev.inmo.tgbotapi.extensions.behaviour_builder.buildSubcontextInitialAction
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage
import dev.inmo.tgbotapi.types.update.abstracts.Update
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
private var BehaviourContextData.update: Update?
get() = get("update") as? Update
set(value) = set("update", value)
private var BehaviourContextData.commonMessage: CommonMessage<*>?
get() = get("commonMessage") as? CommonMessage<*>
set(value) = set("commonMessage", value)
/**
* This place can be the playground for your code.
*/
@@ -15,6 +28,7 @@ suspend fun main(vararg args: String) {
val botToken = args.first()
val isDebug = args.any { it == "debug" }
val isTestServer = args.any { it == "testServer" }
if (isDebug) {
setDefaultKSLog(
@@ -24,11 +38,47 @@ suspend fun main(vararg args: String) {
)
}
telegramBotWithBehaviourAndLongPolling(botToken, CoroutineScope(Dispatchers.IO)) {
telegramBotWithBehaviourAndLongPolling(
botToken,
CoroutineScope(Dispatchers.IO),
testServer = isTestServer,
builder = {
includeMiddlewares {
addMiddleware {
doOnRequestReturnResult { result, request, _ ->
println("Result of $request:\n\n$result")
null
}
}
}
},
subcontextInitialAction = buildSubcontextInitialAction {
add {
data.update = it
}
}
) {
// start here!!
val me = getMe()
println(me)
allUpdatesFlow.subscribeSafelyWithoutExceptions(this) { println(it) }
onCommand("start") {
println(data.update)
println(data.commonMessage)
}
onCommand(
"additional_command",
additionalSubcontextInitialAction = { update, commonMessage ->
data.commonMessage = commonMessage
}
) {
println(data.update)
println(data.commonMessage)
}
allUpdatesFlow.subscribeSafelyWithoutExceptions(this) {
println(it)
}
}.second.join()
}

View File

@@ -7,7 +7,7 @@ import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAn
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onMedia
import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile
import dev.inmo.tgbotapi.types.actions.TypingAction
import dev.inmo.tgbotapi.types.actions.*
import dev.inmo.tgbotapi.types.media.TelegramMediaAudio
import dev.inmo.tgbotapi.types.media.TelegramMediaDocument
import dev.inmo.tgbotapi.types.media.TelegramMediaPhoto
@@ -34,13 +34,27 @@ suspend fun main(args: Array<String>) {
val content = it.content
val pathedFile = bot.getFileAdditionalInfo(content.media)
val outFile = File(directoryOrFile, pathedFile.filePath.filenameFromUrl)
runCatching {
bot.downloadFile(content.media, outFile)
}.onFailure {
it.printStackTrace()
withTypingAction(it.chat.id) {
runCatching {
bot.downloadFile(content.media, outFile)
}.onFailure {
it.printStackTrace()
}.onSuccess { _ ->
reply(it, "Saved to ${outFile.absolutePath}")
}
}.onSuccess { _ ->
reply(it, "Saved to ${outFile.absolutePath}")
withAction(it.chat.id, TypingAction) {
val action = when (content) {
is PhotoContent -> UploadPhotoAction
is AnimationContent,
is VideoContent -> UploadVideoAction
is StickerContent -> ChooseStickerAction
is MediaGroupContent<*> -> UploadPhotoAction
is DocumentContent -> UploadDocumentAction
is VoiceContent,
is AudioContent -> RecordVoiceAction
is VideoNoteContent -> UploadVideoNoteAction
}
withAction(it.chat.id, action) {
when (content) {
is PhotoContent -> replyWithPhoto(
it,

9
GiveawaysBot/README.md Normal file
View File

@@ -0,0 +1,9 @@
# CustomBot
Printing giveaways
## Launch
```bash
../gradlew run --args="BOT_TOKEN"
```

21
GiveawaysBot/build.gradle Normal file
View File

@@ -0,0 +1,21 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName="GiveawaysBotKt"
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
}

View File

@@ -0,0 +1,57 @@
import dev.inmo.kslog.common.KSLog
import dev.inmo.kslog.common.LogLevel
import dev.inmo.kslog.common.defaultMessageFormatter
import dev.inmo.kslog.common.setDefaultKSLog
import dev.inmo.micro_utils.coroutines.subscribeSafelyWithoutExceptions
import dev.inmo.tgbotapi.extensions.api.bot.getMe
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGiveawayCompleted
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGiveawayContent
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGiveawayCreated
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onGiveawayWinners
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
/**
* This place can be the playground for your code.
*/
suspend fun main(vararg args: String) {
val botToken = args.first()
val isDebug = args.any { it == "debug" }
val isTestServer = args.any { it == "testServer" }
if (isDebug) {
setDefaultKSLog(
KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
println(defaultMessageFormatter(level, tag, message, throwable))
}
)
}
telegramBotWithBehaviourAndLongPolling(botToken, testServer = isTestServer) {
// start here!!
val me = getMe()
println(me)
onGiveawayCreated {
println(it)
}
onGiveawayCompleted {
println(it)
}
onGiveawayWinners {
println(it)
}
onGiveawayContent {
println(it)
}
// allUpdatesFlow.subscribeSafelyWithoutExceptions(this) {
// println(it)
// }
}.second.join()
}

View File

@@ -3,7 +3,10 @@ import dev.inmo.tgbotapi.extensions.api.bot.getMe
import dev.inmo.tgbotapi.extensions.api.chat.get.getChat
import dev.inmo.tgbotapi.extensions.api.send.reply
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onContentMessage
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onMentionWithAnyContent
import dev.inmo.tgbotapi.extensions.utils.extensions.raw.sender_chat
import dev.inmo.tgbotapi.extensions.utils.extensions.raw.text
import dev.inmo.tgbotapi.extensions.utils.formatting.linkMarkdownV2
import dev.inmo.tgbotapi.extensions.utils.formatting.textMentionMarkdownV2
import dev.inmo.tgbotapi.extensions.utils.ifFromChannelGroupContentMessage
@@ -23,22 +26,35 @@ suspend fun main(vararg args: String) {
telegramBotWithBehaviourAndLongPolling(botToken, CoroutineScope(Dispatchers.IO)) {
val me = getMe()
onMentionWithAnyContent(me) { message ->
onContentMessage(
initialFilter = initialFilter@{ it.text ?.contains(me.username ?.full ?: return@initialFilter false) == true }
) { message ->
val answerText = when (val chat = message.chat) {
is PreviewChannelChat -> {
val answer = "Hi everybody in this channel \"${chat.title}\""
reply(message, answer, MarkdownV2)
return@onMentionWithAnyContent
val sender = message.sender_chat
val answer = "Hi everybody in this channel \"${chat.title}\"" + if (sender != null) {
" and you, " + when (sender) {
is BusinessChat -> "business chat (wat) ${sender.original}"
is PrivateChat -> "${sender.lastName} ${sender.firstName}"
is GroupChat -> "group ${sender.title}"
is ChannelChat -> "channel ${sender.title}"
is UnknownChatType -> "wat chat (${sender})"
}
} else {
""
}
reply(message, answer.escapeMarkdownV2Common(), MarkdownV2)
return@onContentMessage
}
is PreviewPrivateChat -> {
reply(message, "Hi, " + "${chat.firstName} ${chat.lastName}".textMentionMarkdownV2(chat.id), MarkdownV2)
return@onMentionWithAnyContent
return@onContentMessage
}
is PreviewGroupChat -> {
message.ifFromChannelGroupContentMessage<Unit> {
val answer = "Hi, ${it.senderChat.title}"
reply(message, answer, MarkdownV2)
return@onMentionWithAnyContent
return@onContentMessage
}
"Oh, hi, " + when (chat) {
is SupergroupChat -> (chat.username ?.username ?: getChat(chat).inviteLink) ?.let {
@@ -51,7 +67,7 @@ suspend fun main(vararg args: String) {
}
is PreviewBusinessChat -> {
reply(message, "Hi, " + "${chat.original.firstName} ${chat.original.lastName} (as business chat :) )".textMentionMarkdownV2(chat.original.id), MarkdownV2)
return@onMentionWithAnyContent
return@onContentMessage
}
is UnknownChatType -> "Unknown :(".escapeMarkdownV2Common()
}

View File

@@ -33,6 +33,6 @@ kotlin {
}
dependencies {
implementation 'io.ktor:ktor-client-logging-jvm:2.3.7'
implementation 'io.ktor:ktor-client-logging-jvm:3.0.1'
}

View File

@@ -45,6 +45,9 @@ fun InlineKeyboardBuilder.includePageButtons(page: Int, count: Int) {
}
}
}
row {
copyTextButton("Command copy button", "/inline $page $count")
}
row {
if (page - 1 > 2) {
@@ -84,11 +87,13 @@ suspend fun activateKeyboardsBot(
bot.buildBehaviourWithLongPolling(CoroutineScope(currentCoroutineContext() + SupervisorJob())) {
onCommandWithArgs("inline") { message, args ->
val numberOfPages = args.firstOrNull() ?.toIntOrNull() ?: 10
val numberArgs = args.mapNotNull { it.toIntOrNull() }
val numberOfPages = numberArgs.getOrNull(1) ?: numberArgs.firstOrNull() ?: 10
val page = numberArgs.firstOrNull() ?.takeIf { numberArgs.size > 1 } ?.coerceAtLeast(1) ?: 1
reply(
message,
replyMarkup = inlineKeyboard {
includePageButtons(1, numberOfPages)
includePageButtons(page, numberOfPages)
}
) {
regular("Your inline keyboard with $numberOfPages pages")

View File

@@ -1,7 +1,21 @@
import dev.inmo.kslog.common.KSLog
import dev.inmo.kslog.common.LogLevel
import dev.inmo.kslog.common.defaultMessageFormatter
import dev.inmo.kslog.common.setDefaultKSLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun main(args: Array<String>) {
val isDebug = args.any { it == "debug" }
if (isDebug) {
setDefaultKSLog(
KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
println(defaultMessageFormatter(level, tag, message, throwable))
}
)
}
withContext(Dispatchers.IO) { // IO for inheriting of it in side of activateKeyboardsBot
activateKeyboardsBot(args.first()) {
println(it)

View File

@@ -0,0 +1,10 @@
# MemberUpdatedWatcherBot
This bot will watch for some ChatMemberUpdated events using new extensions from 18.0.0
## Launch
```bash
../gradlew run --args="BOT_TOKEN"
```

View File

@@ -0,0 +1,21 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName="MemberUpdatedWatcherKt"
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
}

View File

@@ -0,0 +1,98 @@
import dev.inmo.kslog.common.*
import dev.inmo.tgbotapi.extensions.api.*
import dev.inmo.tgbotapi.extensions.api.bot.*
import dev.inmo.tgbotapi.extensions.api.send.*
import dev.inmo.tgbotapi.extensions.behaviour_builder.*
import dev.inmo.tgbotapi.extensions.behaviour_builder.filters.chatMemberGotRestrictedFilter
import dev.inmo.tgbotapi.extensions.behaviour_builder.filters.chatMemberGotRestrictionsChangedFilter
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.*
import dev.inmo.tgbotapi.extensions.behaviour_builder.utils.*
import dev.inmo.tgbotapi.extensions.utils.*
import dev.inmo.tgbotapi.types.chat.member.*
import dev.inmo.tgbotapi.utils.*
@OptIn(PreviewFeature::class)
suspend fun main(args: Array<String>) {
val token = args.first()
val isDebug = args.any { it == "debug" }
if (isDebug) {
setDefaultKSLog(
KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
println(defaultMessageFormatter(level, tag, message, throwable))
}
)
}
val internalLogger = KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
println(defaultMessageFormatter(level, tag ?: "ChatMemberUpdates", message, throwable))
}
val bot = telegramBot(token)
bot.buildBehaviourWithLongPolling {
val me = getMe()
val filterSelfUpdates = SimpleFilter<ChatMemberUpdated> {
it.member.id == me.id
}
// This bot updates
onChatMemberJoined(initialFilter = filterSelfUpdates) {
internalLogger.i("Bot was added to chat")
send(it.chat.id, "I was added to chat. Please grant me admin permissions to make me able to watch other users' events")
}
onChatMemberGotPromoted(initialFilter = filterSelfUpdates) {
internalLogger.i("Bot was granted admin permissions")
send(it.chat.id, "I was promoted to admin. I now can watch other users' events")
}
onChatMemberGotDemoted(initialFilter = filterSelfUpdates) {
internalLogger.i("Admin permissions were revoked")
send(it.chat.id, "I'm no longer an admin. Admin permissions are required to watch other users' events")
}
// All users updates
onChatMemberJoined {
val member = it.member
internalLogger.i("${member.firstName} joined the chat: ${it.oldChatMemberState::class.simpleName} => ${it.newChatMemberState::class.simpleName}")
send(it.chat.id, "Welcome ${member.firstName}")
}
onChatMemberLeft {
val member = it.member
internalLogger.i("${member.firstName} left the chat: ${it.oldChatMemberState::class.simpleName} => ${it.newChatMemberState::class.simpleName}")
send(it.chat.id, "Goodbye ${member.firstName}")
}
onChatMemberGotPromoted {
val newState = it.newChatMemberState.administratorChatMemberOrThrow()
internalLogger.i("${newState.user.firstName} got promoted to ${newState.customTitle ?: "Admin"}: ${it.oldChatMemberState::class.simpleName} => ${it.newChatMemberState::class.simpleName}")
send(it.chat.id, "${newState.user.firstName} is now an ${newState.customTitle ?: "Admin"}")
}
onChatMemberGotDemoted {
val member = it.member
internalLogger.i("${member.firstName} got demoted: ${it.oldChatMemberState::class.simpleName} => ${it.newChatMemberState::class.simpleName}")
send(it.chat.id, "${member.firstName} is now got demoted back to member")
}
onChatMemberGotPromotionChanged {
val member = it.member
val message = "${member.firstName} has the permissions changed: ${it.oldChatMemberState::class.simpleName} => ${it.newChatMemberState::class.simpleName}"
internalLogger.i(message)
send(it.chat.id, message)
}
onChatMemberUpdated(
initialFilter = chatMemberGotRestrictedFilter + chatMemberGotRestrictionsChangedFilter,
) {
val member = it.member
val message = "${member.firstName} has the permissions changed: ${it.oldChatMemberState::class.simpleName} => ${it.newChatMemberState::class.simpleName}"
internalLogger.i(message)
send(it.chat.id, message)
}
}.join()
}

View File

@@ -48,6 +48,7 @@ suspend fun main(vararg args: String) {
when (it) {
is Reaction.CustomEmoji -> regular("") + customEmoji(it.customEmojiId) + regular("(customEmojiId: ${it.customEmojiId})")
is Reaction.Emoji -> regular("${it.emoji}")
is Reaction.Paid -> regular("• Some paid reaction")
is Reaction.Unknown -> regular("• Unknown emoji ($it)")
}
regular("\n")

View File

@@ -18,5 +18,5 @@ dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
implementation 'io.ktor:ktor-client-logging-jvm:2.3.7'
implementation 'io.ktor:ktor-client-logging-jvm:3.0.1'
}

View File

@@ -106,7 +106,7 @@ suspend fun main(args: Array<String>) {
suspend fun BehaviourContext.getUserChatPermissions(chatId: ChatId, userId: UserId): ChatPermissions? {
val chatMember = getChatMember(chatId, userId)
return chatMember.restrictedChatMemberOrNull() ?: chatMember.whenMemberChatMember {
return chatMember.restrictedMemberChatMemberOrNull() ?: chatMember.whenMemberChatMember {
getChat(chatId).extendedGroupChatOrNull() ?.permissions
}
}

View File

@@ -12,10 +12,7 @@ import dev.inmo.tgbotapi.extensions.api.send.send
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.*
import dev.inmo.tgbotapi.extensions.utils.extensions.sameChat
import dev.inmo.tgbotapi.extensions.utils.types.buttons.dataButton
import dev.inmo.tgbotapi.extensions.utils.types.buttons.flatInlineKeyboard
import dev.inmo.tgbotapi.extensions.utils.types.buttons.inlineKeyboard
import dev.inmo.tgbotapi.extensions.utils.types.buttons.payButton
import dev.inmo.tgbotapi.extensions.utils.types.buttons.*
import dev.inmo.tgbotapi.extensions.utils.withContentOrNull
import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile
import dev.inmo.tgbotapi.types.RawChatId
@@ -30,6 +27,7 @@ import dev.inmo.tgbotapi.types.message.content.TextContent
import dev.inmo.tgbotapi.types.message.textsources.TextSourcesList
import dev.inmo.tgbotapi.types.payments.LabeledPrice
import dev.inmo.tgbotapi.types.payments.stars.StarTransaction
import dev.inmo.tgbotapi.types.request.RequestId
import dev.inmo.tgbotapi.utils.bold
import dev.inmo.tgbotapi.utils.buildEntities
import dev.inmo.tgbotapi.utils.regular

View File

@@ -182,7 +182,7 @@ fun main() {
val hex = Color.Hex(r, g, b)
webApp.setHeaderColor(hex)
(this as? HTMLButtonElement) ?.style ?.backgroundColor = hex.value
textContent = "Header color: ${hex.value.uppercase()} (click to change)"
textContent = "Header color: ${webApp.headerColor ?.uppercase()} (click to change)"
}
addEventListener("click", {
updateHeaderColor()
@@ -192,6 +192,38 @@ fun main() {
document.body ?.appendElement("p", {})
document.body ?.appendElement("button") {
fun updateBackgroundColor() {
val (r, g, b) = Random.nextUBytes(3)
val hex = Color.Hex(r, g, b)
webApp.setBackgroundColor(hex)
(this as? HTMLButtonElement) ?.style ?.backgroundColor = hex.value
textContent = "Background color: ${webApp.backgroundColor ?.uppercase()} (click to change)"
}
addEventListener("click", {
updateBackgroundColor()
})
updateBackgroundColor()
} ?: window.alert("Unable to load body")
document.body ?.appendElement("p", {})
document.body ?.appendElement("button") {
fun updateBottomBarColor() {
val (r, g, b) = Random.nextUBytes(3)
val hex = Color.Hex(r, g, b)
webApp.setBottomBarColor(hex)
(this as? HTMLButtonElement) ?.style ?.backgroundColor = hex.value
textContent = "Bottom bar color: ${webApp.bottomBarColor ?.uppercase()} (click to change)"
}
addEventListener("click", {
updateBottomBarColor()
})
updateBottomBarColor()
} ?: window.alert("Unable to load body")
document.body ?.appendElement("p", {})
fun Element.updateCloudStorageContent() {
clear()
webApp.cloudStorage.getAll {
@@ -287,6 +319,16 @@ fun main() {
}
show()
}
secondaryButton.apply {
setText("Secondary button")
onClick {
document.body ?.log("Secondary button clicked")
hapticFeedback.notificationOccurred(
HapticFeedbackType.Warning
)
}
show()
}
onSettingsButtonClicked {
document.body ?.log("Settings button clicked")
}

View File

@@ -63,10 +63,7 @@ suspend fun main(vararg args: String) {
val bot = telegramBot(telegramBotAPIUrlsKeeper)
createKtorServer(
"0.0.0.0",
args.getOrNull(2) ?.toIntOrNull() ?: 8080,
additionalEngineEnvironmentConfigurator = {
parentCoroutineContext += Dispatchers.IO
}
args.getOrNull(2) ?.toIntOrNull() ?: 8080
) {
routing {
val baseJsFolder = File("WebApp/build/dist/js/")

28
WebHooks/README.md Normal file
View File

@@ -0,0 +1,28 @@
# WebHooks
Launches webhook-based simple bot. Use `/start` with bot to get simple info about webhooks
## Launch
```bash
../gradlew run --args="BOT_TOKEN https://sample.com it/is/subpath 8080 debug"
```
Required arguments:
1. Token
2. Arguments starting with `https://`
Optional arguments:
* Any argument == `debug` to enable debug mode
* Any argument **not** starting with `https://` and **not** equal to `debug` as **subpath** (will be used as
subroute to place listening of webhooks)
* Any argument as number of port
Sample: `TOKEN https://sample.com it/is/subpath 8080` will result to:
* `TOKEN` used as token
* Bot will set up its webhook info as `https://sample.com/it/is/subpath`
* Bot will set up to listen webhooks on route `it/is/subpath`
* Bot will start to listen any incoming request on port `8080` and url `0.0.0.0`

23
WebHooks/build.gradle Normal file
View File

@@ -0,0 +1,23 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName="WebHooksKt"
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
implementation "dev.inmo:micro_utils.ktor.server:$micro_utils_version"
implementation "io.ktor:ktor-server-cio:$ktor_version"
}

View File

@@ -0,0 +1,87 @@
import dev.inmo.kslog.common.KSLog
import dev.inmo.kslog.common.LogLevel
import dev.inmo.kslog.common.defaultMessageFormatter
import dev.inmo.kslog.common.setDefaultKSLog
import dev.inmo.micro_utils.ktor.server.createKtorServer
import dev.inmo.tgbotapi.bot.ktor.telegramBot
import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands
import dev.inmo.tgbotapi.extensions.api.send.reply
import dev.inmo.tgbotapi.extensions.api.webhook.setWebhookInfo
import dev.inmo.tgbotapi.extensions.behaviour_builder.buildBehaviour
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
import dev.inmo.tgbotapi.extensions.utils.updates.retrieving.includeWebhookHandlingInRoute
import dev.inmo.tgbotapi.types.BotCommand
import dev.inmo.tgbotapi.types.chat.PrivateChat
import dev.inmo.tgbotapi.utils.buildEntities
import io.ktor.server.routing.*
/**
* Launches webhook-based simple bot. Required arguments:
*
* 1. Token
* *. Arguments starting with `https://`
*
* Optional arguments:
*
* *. Any argument == `debug` to enable debug mode
* *. Any argument **not** starting with `https://` and **not** equal to `debug` as **subpath** (will be used as
* subroute to place listening of webhooks)
* *. Any argument as number of port
*
* Sample: `TOKEN https://sample.com it/is/subpath 8080` will result to:
*
* * `TOKEN` used as token
* * Bot will set up its webhook info as `https://sample.com/it/is/subpath`
* * Bot will set up to listen webhooks on route `it/is/subpath`
* * Bot will start to listen any incoming request on port `8080` and url `0.0.0.0`
*/
suspend fun main(args: Array<String>) {
val botToken = args.first()
val address = args.first { it.startsWith("https://") }
val subpath = args.drop(1).firstOrNull { it != address && it != "debug" }
val port = args.firstNotNullOfOrNull { it.toIntOrNull() } ?: 8080
val isDebug = args.any { it == "debug" }
if (isDebug) {
setDefaultKSLog(
KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
println(defaultMessageFormatter(level, tag, message, throwable))
}
)
}
val bot = telegramBot(botToken)
val behaviourContext = bot.buildBehaviour (defaultExceptionsHandler = { it.printStackTrace() }) {
onCommand("start", initialFilter = { it.chat is PrivateChat }) {
reply(
it,
buildEntities {
+"Url: $address" + "\n"
+"Listening server: 0.0.0.0" + "\n"
+"Listening port: $port"
}
)
}
setMyCommands(BotCommand("start", "Get webhook info"))
}
val webhookInfoSubpath = subpath ?.let { "/" + it.removePrefix("/") } ?: "" // drop leading `/` to add it in the beginning for correct construction of subpath
bot.setWebhookInfo(address + webhookInfoSubpath)
createKtorServer(
"0.0.0.0",
port,
) {
routing {
if (subpath == null) {
includeWebhookHandlingInRoute(behaviourContext, block = behaviourContext.asUpdateReceiver)
} else {
route(subpath) {
includeWebhookHandlingInRoute(behaviourContext, block = behaviourContext.asUpdateReceiver)
}
}
}
}.start(true)
}

View File

@@ -1,12 +1,12 @@
kotlin.code.style=official
org.gradle.parallel=true
# Due to parallel compilation project require next amount of memory on full build
org.gradle.jvmargs=-Xmx2344m
kotlin.daemon.jvmargs=-Xmx2g -Xms500m
org.gradle.jvmargs=-Xmx3148m
kotlin.daemon.jvmargs=-Xmx3g -Xms500m
kotlin_version=1.9.23
telegram_bot_api_version=15.3.0
micro_utils_version=0.21.2
serialization_version=1.6.3
ktor_version=2.3.11
kotlin_version=2.1.0
telegram_bot_api_version=21.0.0
micro_utils_version=0.23.1
serialization_version=1.7.3
ktor_version=3.0.1

View File

@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip

View File

@@ -52,4 +52,10 @@ include ":BusinessConnectionsBot"
include ":StarTransactionsBot"
include ":GiveawaysBot"
include ":CustomBot"
include ":MemberUpdatedWatcherBot"
include ":WebHooks"