mirror of
https://github.com/InsanusMokrassar/TelegramBotAPI-examples.git
synced 2025-12-05 05:45:39 +00:00
Compare commits
67 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 467a3a1710 | |||
| 5810bc5930 | |||
| 2cf2c4264e | |||
|
|
3d5c2ee4b8 | ||
| 360c6b4364 | |||
|
|
bb6a0a125a | ||
| 6a61da2eb7 | |||
| 8cd75673f5 | |||
| d294d0ef59 | |||
| 2ab8ccbfdf | |||
| d12e9aa032 | |||
| 76f151586e | |||
| 1c437690e4 | |||
| 222c7ec8ee | |||
| 59778a3add | |||
| 3e20835bc6 | |||
| c3ad2d4319 | |||
| 59fca968d7 | |||
| f03ba5f177 | |||
|
|
855d2c1296 | ||
| 280f5abce0 | |||
|
|
ed81e76ef8 | ||
| 541b76b292 | |||
| 5b580b5a15 | |||
| 86790ee414 | |||
| 0bbe430374 | |||
| b7d53a7410 | |||
| 73064db226 | |||
| a50eda366d | |||
| e34f0ec9d8 | |||
| c2237f7e87 | |||
| 0bbc6a9555 | |||
| d4d8508abf | |||
| 9acb64fda9 | |||
|
|
760ae36207 | ||
| 5c6b1b7171 | |||
| 6e06357541 | |||
| 38f46dfa3b | |||
|
|
e7f7ef16ac | ||
|
|
d100a5a336 | ||
| 5f0f2ce76d | |||
| 14235e7bd4 | |||
| 6eafd89542 | |||
| ed2922045c | |||
| 21ec50c773 | |||
| ab362e8c3b | |||
| 346755b41c | |||
|
|
a601674d71 | ||
|
|
cea610a0f8 | ||
| b6c92f754f | |||
| 023b810d07 | |||
| 0ec543d5c5 | |||
| 777604e5a0 | |||
| 999c33b2f5 | |||
| ca0427bfdd | |||
| a62a14a599 | |||
|
|
3efd3463a3 | ||
| 590f9ec6d8 | |||
| acdbd4d2ea | |||
| d2d913fca8 | |||
| 75726cac89 | |||
| 71b64689d0 | |||
| 5ba2fc5bab | |||
| 51a5bfb81a | |||
| 35e330c016 | |||
| 90d447fbcf | |||
| 2c5da5da9f |
1
.github/workflows/build.yml
vendored
1
.github/workflows/build.yml
vendored
@@ -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
1
.gitignore
vendored
@@ -1,4 +1,5 @@
|
||||
.idea
|
||||
.kotlin
|
||||
out/*
|
||||
*.iml
|
||||
target
|
||||
|
||||
2
.template/bot/.env
Normal file
2
.template/bot/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
title=$prompt
|
||||
subtitle=Subtitle of {{$title}}
|
||||
9
.template/bot/{{$title}}/README.md
Normal file
9
.template/bot/{{$title}}/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# {{$title}}
|
||||
|
||||
|
||||
|
||||
## Launch
|
||||
|
||||
```bash
|
||||
../gradlew run --args="BOT_TOKEN"
|
||||
```
|
||||
22
.template/bot/{{$title}}/build.gradle
Normal file
22
.template/bot/{{$title}}/build.gradle
Normal 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"
|
||||
}
|
||||
34
.template/bot/{{$title}}/src/main/kotlin/{{$title}}.kt
Normal file
34
.template/bot/{{$title}}/src/main/kotlin/{{$title}}.kt
Normal 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()
|
||||
}
|
||||
208
.template/module_generator.main.kts
Executable file
208
.template/module_generator.main.kts
Executable 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)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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
9
GiveawaysBot/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# CustomBot
|
||||
|
||||
Printing giveaways
|
||||
|
||||
## Launch
|
||||
|
||||
```bash
|
||||
../gradlew run --args="BOT_TOKEN"
|
||||
```
|
||||
21
GiveawaysBot/build.gradle
Normal file
21
GiveawaysBot/build.gradle
Normal 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"
|
||||
}
|
||||
57
GiveawaysBot/src/main/kotlin/GiveawaysBot.kt
Normal file
57
GiveawaysBot/src/main/kotlin/GiveawaysBot.kt
Normal 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()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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.3'
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
10
MemberUpdatedWatcherBot/README.md
Normal file
10
MemberUpdatedWatcherBot/README.md
Normal 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"
|
||||
```
|
||||
21
MemberUpdatedWatcherBot/build.gradle
Normal file
21
MemberUpdatedWatcherBot/build.gradle
Normal 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"
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -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.3'
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,7 +12,7 @@ import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onSticke
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onText
|
||||
import dev.inmo.tgbotapi.types.StickerType
|
||||
import dev.inmo.tgbotapi.types.message.textsources.CustomEmojiTextSource
|
||||
import dev.inmo.tgbotapi.types.message.textsources.regular
|
||||
import dev.inmo.tgbotapi.types.message.textsources.regularTextSource
|
||||
import dev.inmo.tgbotapi.types.message.textsources.separateForText
|
||||
import dev.inmo.tgbotapi.types.stickers.StickerSet
|
||||
import dev.inmo.tgbotapi.utils.bold
|
||||
@@ -62,7 +62,7 @@ suspend fun activateStickerInfoBot(
|
||||
}.distinct().map {
|
||||
getStickerSet(it)
|
||||
}.distinct().flatMap {
|
||||
it.buildInfo() + regular("\n")
|
||||
it.buildInfo() + regularTextSource("\n")
|
||||
}.separateForText().map { entities ->
|
||||
reply(it, entities)
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ import dev.inmo.tgbotapi.extensions.utils.types.buttons.*
|
||||
import dev.inmo.tgbotapi.types.BotCommand
|
||||
import dev.inmo.tgbotapi.types.chat.PrivateChat
|
||||
import dev.inmo.tgbotapi.types.keyboardButtonRequestUserLimit
|
||||
import dev.inmo.tgbotapi.types.message.textsources.mention
|
||||
import dev.inmo.tgbotapi.types.request.RequestId
|
||||
import dev.inmo.tgbotapi.utils.mention
|
||||
import dev.inmo.tgbotapi.utils.row
|
||||
|
||||
suspend fun main(args: Array<String>) {
|
||||
@@ -287,7 +287,7 @@ suspend fun main(args: Array<String>) {
|
||||
it,
|
||||
) {
|
||||
+"You have shared "
|
||||
+mention(
|
||||
mention(
|
||||
when (it.chatEvent.requestId) {
|
||||
requestIdUserOrBot -> "user or bot"
|
||||
requestIdUserNonPremium -> "non premium user"
|
||||
|
||||
@@ -11,6 +11,9 @@ buildscript {
|
||||
plugins {
|
||||
id "org.jetbrains.kotlin.multiplatform"
|
||||
id "org.jetbrains.kotlin.plugin.serialization"
|
||||
|
||||
id "org.jetbrains.kotlin.plugin.compose" version "$kotlin_version"
|
||||
id "org.jetbrains.compose" version "$compose_version"
|
||||
}
|
||||
|
||||
apply plugin: 'application'
|
||||
@@ -27,12 +30,15 @@ kotlin {
|
||||
dependencies {
|
||||
implementation kotlin('stdlib')
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$serialization_version"
|
||||
implementation "dev.inmo:tgbotapi.core:$telegram_bot_api_version"
|
||||
implementation compose.runtime
|
||||
}
|
||||
}
|
||||
|
||||
jsMain {
|
||||
dependencies {
|
||||
implementation "dev.inmo:tgbotapi.webapps:$telegram_bot_api_version"
|
||||
implementation compose.web.core
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +47,7 @@ kotlin {
|
||||
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"
|
||||
implementation compose.desktop.currentOs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
3
WebApp/src/commonMain/kotlin/CustomEmojiIdToSet.kt
Normal file
3
WebApp/src/commonMain/kotlin/CustomEmojiIdToSet.kt
Normal file
@@ -0,0 +1,3 @@
|
||||
import dev.inmo.tgbotapi.types.CustomEmojiId
|
||||
|
||||
val CustomEmojiIdToSet = CustomEmojiId("5424939566278649034")
|
||||
@@ -1,22 +1,35 @@
|
||||
import androidx.compose.runtime.*
|
||||
import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions
|
||||
import dev.inmo.tgbotapi.types.CustomEmojiId
|
||||
import dev.inmo.tgbotapi.types.userIdField
|
||||
import dev.inmo.tgbotapi.types.webAppQueryIdField
|
||||
import dev.inmo.tgbotapi.webapps.*
|
||||
import dev.inmo.tgbotapi.webapps.accelerometer.AccelerometerStartParams
|
||||
import dev.inmo.tgbotapi.webapps.cloud.*
|
||||
import dev.inmo.tgbotapi.webapps.events.*
|
||||
import dev.inmo.tgbotapi.webapps.gyroscope.GyroscopeStartParams
|
||||
import dev.inmo.tgbotapi.webapps.haptic.HapticFeedbackStyle
|
||||
import dev.inmo.tgbotapi.webapps.haptic.HapticFeedbackType
|
||||
import dev.inmo.tgbotapi.webapps.orientation.DeviceOrientationStartParams
|
||||
import dev.inmo.tgbotapi.webapps.popup.*
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.request.*
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import io.ktor.http.*
|
||||
import io.ktor.http.content.TextContent
|
||||
import kotlinx.browser.document
|
||||
import kotlinx.browser.window
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.dom.appendElement
|
||||
import kotlinx.dom.appendText
|
||||
import kotlinx.dom.clear
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.jetbrains.compose.web.attributes.InputType
|
||||
import org.jetbrains.compose.web.css.DisplayStyle
|
||||
import org.jetbrains.compose.web.css.Color as ComposeColor
|
||||
import org.jetbrains.compose.web.css.backgroundColor
|
||||
import org.jetbrains.compose.web.css.display
|
||||
import org.jetbrains.compose.web.dom.*
|
||||
import org.jetbrains.compose.web.dom.Text
|
||||
import org.jetbrains.compose.web.renderComposable
|
||||
import org.w3c.dom.*
|
||||
import kotlin.random.Random
|
||||
import kotlin.random.nextUBytes
|
||||
@@ -32,245 +45,356 @@ fun main() {
|
||||
val client = HttpClient()
|
||||
val baseUrl = window.location.origin.removeSuffix("/")
|
||||
|
||||
window.onload = {
|
||||
val scope = CoroutineScope(Dispatchers.Default)
|
||||
runCatching {
|
||||
renderComposable("root") {
|
||||
val scope = rememberCoroutineScope()
|
||||
val isSafeState = remember { mutableStateOf<Boolean?>(null) }
|
||||
val logsState = remember { mutableStateListOf<Any?>() }
|
||||
|
||||
scope.launchSafelyWithoutExceptions {
|
||||
val response = client.post("$baseUrl/check") {
|
||||
setBody(
|
||||
Json.encodeToString(
|
||||
WebAppDataWrapper.serializer(),
|
||||
WebAppDataWrapper(webApp.initData, webApp.initDataUnsafe.hash)
|
||||
)
|
||||
// Text(window.location.href)
|
||||
// P()
|
||||
|
||||
LaunchedEffect(baseUrl) {
|
||||
val response = client.post("$baseUrl/check") {
|
||||
setBody(
|
||||
Json.encodeToString(
|
||||
WebAppDataWrapper.serializer(),
|
||||
WebAppDataWrapper(webApp.initData, webApp.initDataUnsafe.hash)
|
||||
)
|
||||
)
|
||||
}
|
||||
val dataIsSafe = response.bodyAsText().toBoolean()
|
||||
|
||||
if (dataIsSafe) {
|
||||
isSafeState.value = true
|
||||
logsState.add("Data is safe")
|
||||
} else {
|
||||
isSafeState.value = false
|
||||
logsState.add("Data is unsafe")
|
||||
}
|
||||
|
||||
logsState.add(
|
||||
webApp.initDataUnsafe.chat.toString()
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
when (isSafeState.value) {
|
||||
null -> "Checking safe state..."
|
||||
true -> "Data is safe"
|
||||
false -> "Data is unsafe"
|
||||
}
|
||||
)
|
||||
P()
|
||||
Text("Chat from WebAppInitData: ${webApp.initDataUnsafe.chat}")
|
||||
|
||||
val emojiStatusAccessState = remember { mutableStateOf(false) }
|
||||
webApp.onEmojiStatusAccessRequested {
|
||||
emojiStatusAccessState.value = it.isAllowed
|
||||
}
|
||||
Button({
|
||||
onClick {
|
||||
webApp.requestEmojiStatusAccess()
|
||||
}
|
||||
}) {
|
||||
Text("Request custom emoji status access")
|
||||
}
|
||||
if (emojiStatusAccessState.value) {
|
||||
Button({
|
||||
onClick {
|
||||
webApp.setEmojiStatus(CustomEmojiIdToSet/* android custom emoji id */)
|
||||
}
|
||||
}) {
|
||||
Text("Set custom emoji status")
|
||||
}
|
||||
val userId = webApp.initDataUnsafe.user ?.id
|
||||
userId ?.let { userId ->
|
||||
Button({
|
||||
onClick {
|
||||
scope.launchSafelyWithoutExceptions {
|
||||
client.post("$baseUrl/setCustomEmoji") {
|
||||
parameter(userIdField, userId.long)
|
||||
setBody(
|
||||
Json.encodeToString(
|
||||
WebAppDataWrapper.serializer(),
|
||||
WebAppDataWrapper(webApp.initData, webApp.initDataUnsafe.hash)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Text("Set custom emoji status via bot")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button({
|
||||
onClick {
|
||||
scope.launchSafelyWithoutExceptions {
|
||||
handleResult({ "Clicked" }) {
|
||||
client.post("${window.location.origin.removeSuffix("/")}/inline") {
|
||||
parameter(webAppQueryIdField, it)
|
||||
setBody(TextContent("Clicked", ContentType.Text.Plain))
|
||||
logsState.add(url.build().toString())
|
||||
}.coroutineContext.job.join()
|
||||
}
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Text("Answer in chat button")
|
||||
}
|
||||
|
||||
P()
|
||||
Text("Allow to write in private messages: ${webApp.initDataUnsafe.user ?.allowsWriteToPM ?: "User unavailable"}")
|
||||
|
||||
P()
|
||||
Text("Alerts:")
|
||||
Button({
|
||||
onClick {
|
||||
webApp.showPopup(
|
||||
PopupParams(
|
||||
"It is sample title of default button",
|
||||
"It is sample message of default button",
|
||||
DefaultPopupButton("default", "Default button"),
|
||||
OkPopupButton("ok"),
|
||||
DestructivePopupButton("destructive", "Destructive button")
|
||||
)
|
||||
) {
|
||||
logsState.add(
|
||||
when (it) {
|
||||
"default" -> "You have clicked default button in popup"
|
||||
"ok" -> "You have clicked ok button in popup"
|
||||
"destructive" -> "You have clicked destructive button in popup"
|
||||
else -> "I can't imagine where you take button with id $it"
|
||||
}
|
||||
)
|
||||
}
|
||||
val dataIsSafe = response.bodyAsText().toBoolean()
|
||||
|
||||
document.body ?.log(
|
||||
if (dataIsSafe) {
|
||||
"Data is safe"
|
||||
} else {
|
||||
"Data is unsafe"
|
||||
}
|
||||
)
|
||||
|
||||
document.body ?.log(
|
||||
webApp.initDataUnsafe.chat.toString()
|
||||
)
|
||||
}
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", {
|
||||
scope.launchSafelyWithoutExceptions {
|
||||
handleResult({ "Clicked" }) {
|
||||
client.post("${window.location.origin.removeSuffix("/")}/inline") {
|
||||
parameter(webAppQueryIdField, it)
|
||||
setBody(TextContent("Clicked", ContentType.Text.Plain))
|
||||
document.body ?.log(url.build().toString())
|
||||
}.coroutineContext.job.join()
|
||||
}
|
||||
}
|
||||
})
|
||||
appendText("Answer in chat button")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
document.body ?.appendText("Allow to write in private messages: ${webApp.initDataUnsafe.user ?.allowsWriteToPM ?: "User unavailable"}")
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
document.body ?.appendText("Alerts:")
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", {
|
||||
webApp.showPopup(
|
||||
PopupParams(
|
||||
"It is sample title of default button",
|
||||
"It is sample message of default button",
|
||||
DefaultPopupButton("default", "Default button"),
|
||||
OkPopupButton("ok"),
|
||||
DestructivePopupButton("destructive", "Destructive button")
|
||||
)
|
||||
) {
|
||||
document.body ?.log(
|
||||
when (it) {
|
||||
"default" -> "You have clicked default button in popup"
|
||||
"ok" -> "You have clicked ok button in popup"
|
||||
"destructive" -> "You have clicked destructive button in popup"
|
||||
else -> "I can't imagine where you take button with id $it"
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
appendText("Popup")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", {
|
||||
webApp.showAlert(
|
||||
"This is alert message"
|
||||
) {
|
||||
document.body ?.log(
|
||||
"You have closed alert"
|
||||
)
|
||||
}
|
||||
})
|
||||
appendText("Alert")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", { webApp.requestWriteAccess() })
|
||||
appendText("Request write access without callback")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", { webApp.requestWriteAccess { document.body ?.log("Write access request result: $it") } })
|
||||
appendText("Request write access with callback")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", { webApp.requestContact() })
|
||||
appendText("Request contact without callback")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", { webApp.requestContact { document.body ?.log("Contact request result: $it") } })
|
||||
appendText("Request contact with callback")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
addEventListener("click", {
|
||||
webApp.showConfirm(
|
||||
"This is confirm message"
|
||||
) {
|
||||
document.body ?.log(
|
||||
"You have pressed \"${if (it) "Ok" else "Cancel"}\" in confirm"
|
||||
)
|
||||
}
|
||||
})
|
||||
appendText("Confirm")
|
||||
} ?: window.alert("Unable to load body")
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
fun updateText() {
|
||||
textContent = if (webApp.isClosingConfirmationEnabled) {
|
||||
"Disable closing confirmation"
|
||||
} else {
|
||||
"Enable closing confirmation"
|
||||
}
|
||||
}) {
|
||||
Text("Popup")
|
||||
}
|
||||
Button({
|
||||
onClick {
|
||||
webApp.showAlert(
|
||||
"This is alert message"
|
||||
) {
|
||||
logsState.add(
|
||||
"You have closed alert"
|
||||
)
|
||||
}
|
||||
addEventListener("click", {
|
||||
webApp.toggleClosingConfirmation()
|
||||
updateText()
|
||||
})
|
||||
updateText()
|
||||
} ?: window.alert("Unable to load body")
|
||||
}
|
||||
}) {
|
||||
Text("Alert")
|
||||
}
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
|
||||
document.body ?.appendElement("button") {
|
||||
fun updateHeaderColor() {
|
||||
val (r, g, b) = Random.nextUBytes(3)
|
||||
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)"
|
||||
P()
|
||||
Button({
|
||||
onClick {
|
||||
webApp.requestWriteAccess()
|
||||
}
|
||||
}) {
|
||||
Text("Request write access without callback")
|
||||
}
|
||||
Button({
|
||||
onClick {
|
||||
webApp.requestWriteAccess {
|
||||
logsState.add("Write access request result: $it")
|
||||
}
|
||||
addEventListener("click", {
|
||||
updateHeaderColor()
|
||||
})
|
||||
}
|
||||
}) {
|
||||
Text("Request write access with callback")
|
||||
}
|
||||
|
||||
P()
|
||||
Button({
|
||||
onClick {
|
||||
webApp.requestContact()
|
||||
}
|
||||
}) {
|
||||
Text("Request contact without callback")
|
||||
}
|
||||
Button({
|
||||
onClick {
|
||||
webApp.requestContact { logsState.add("Contact request result: $it") }
|
||||
}
|
||||
}) {
|
||||
Text("Request contact with callback")
|
||||
}
|
||||
P()
|
||||
|
||||
Button({
|
||||
onClick {
|
||||
webApp.showConfirm(
|
||||
"This is confirm message"
|
||||
) {
|
||||
logsState.add(
|
||||
"You have pressed \"${if (it) "Ok" else "Cancel"}\" in confirm"
|
||||
)
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Text("Confirm")
|
||||
}
|
||||
|
||||
P()
|
||||
|
||||
val isClosingConfirmationEnabledState = remember { mutableStateOf(webApp.isClosingConfirmationEnabled) }
|
||||
Button({
|
||||
onClick {
|
||||
webApp.toggleClosingConfirmation()
|
||||
isClosingConfirmationEnabledState.value = webApp.isClosingConfirmationEnabled
|
||||
}
|
||||
}) {
|
||||
Text(
|
||||
if (isClosingConfirmationEnabledState.value) {
|
||||
"Disable closing confirmation"
|
||||
} else {
|
||||
"Enable closing confirmation"
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
P()
|
||||
|
||||
val headerColor = remember { mutableStateOf<Color.Hex>(Color.Hex("#000000")) }
|
||||
fun updateHeaderColor() {
|
||||
val (r, g, b) = Random.nextUBytes(3)
|
||||
headerColor.value = Color.Hex(r, g, b)
|
||||
webApp.setHeaderColor(headerColor.value)
|
||||
}
|
||||
DisposableEffect(0) {
|
||||
updateHeaderColor()
|
||||
onDispose { }
|
||||
}
|
||||
Button({
|
||||
style {
|
||||
backgroundColor(ComposeColor(headerColor.value.value))
|
||||
}
|
||||
onClick {
|
||||
updateHeaderColor()
|
||||
} ?: window.alert("Unable to load body")
|
||||
}
|
||||
}) {
|
||||
key(headerColor.value) {
|
||||
Text("Header color: ${webApp.headerColor ?.uppercase()} (click to change)")
|
||||
}
|
||||
}
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
P()
|
||||
|
||||
fun Element.updateCloudStorageContent() {
|
||||
clear()
|
||||
webApp.cloudStorage.getAll {
|
||||
it.onSuccess {
|
||||
document.body ?.log(it.toString())
|
||||
appendElement("label") { textContent = "Cloud storage" }
|
||||
val backgroundColor = remember { mutableStateOf<Color.Hex>(Color.Hex("#000000")) }
|
||||
fun updateBackgroundColor() {
|
||||
val (r, g, b) = Random.nextUBytes(3)
|
||||
backgroundColor.value = Color.Hex(r, g, b)
|
||||
webApp.setBackgroundColor(backgroundColor.value)
|
||||
}
|
||||
DisposableEffect(0) {
|
||||
updateBackgroundColor()
|
||||
onDispose { }
|
||||
}
|
||||
Button({
|
||||
style {
|
||||
backgroundColor(ComposeColor(backgroundColor.value.value))
|
||||
}
|
||||
onClick {
|
||||
updateBackgroundColor()
|
||||
}
|
||||
}) {
|
||||
key(backgroundColor.value) {
|
||||
Text("Background color: ${webApp.backgroundColor ?.uppercase()} (click to change)")
|
||||
}
|
||||
}
|
||||
|
||||
appendElement("p", {})
|
||||
P()
|
||||
|
||||
it.forEach { (k, v) ->
|
||||
appendElement("div") {
|
||||
val kInput = appendElement("input", {}) as HTMLInputElement
|
||||
val vInput = appendElement("input", {}) as HTMLInputElement
|
||||
val bottomBarColor = remember { mutableStateOf<Color.Hex>(Color.Hex("#000000")) }
|
||||
fun updateBottomBarColor() {
|
||||
val (r, g, b) = Random.nextUBytes(3)
|
||||
bottomBarColor.value = Color.Hex(r, g, b)
|
||||
webApp.setBottomBarColor(bottomBarColor.value)
|
||||
}
|
||||
DisposableEffect(0) {
|
||||
updateBottomBarColor()
|
||||
onDispose { }
|
||||
}
|
||||
Button({
|
||||
style {
|
||||
backgroundColor(ComposeColor(bottomBarColor.value.value))
|
||||
}
|
||||
onClick {
|
||||
updateBottomBarColor()
|
||||
}
|
||||
}) {
|
||||
key(bottomBarColor.value) {
|
||||
Text("Bottom bar color: ${webApp.bottomBarColor ?.uppercase()} (click to change)")
|
||||
}
|
||||
}
|
||||
|
||||
kInput.value = k.key
|
||||
vInput.value = v.value
|
||||
P()
|
||||
|
||||
appendElement("button") {
|
||||
addEventListener("click", {
|
||||
if (k.key == kInput.value) {
|
||||
webApp.cloudStorage.set(k.key, vInput.value) {
|
||||
document.body ?.log(it.toString())
|
||||
this@updateCloudStorageContent.updateCloudStorageContent()
|
||||
}
|
||||
} else {
|
||||
webApp.cloudStorage.remove(k.key) {
|
||||
it.onSuccess {
|
||||
webApp.cloudStorage.set(kInput.value, vInput.value) {
|
||||
document.body ?.log(it.toString())
|
||||
this@updateCloudStorageContent.updateCloudStorageContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
this.textContent = "Save"
|
||||
}
|
||||
}
|
||||
|
||||
appendElement("p", {})
|
||||
}
|
||||
appendElement("label") { textContent = "Cloud storage: add new" }
|
||||
|
||||
appendElement("p", {})
|
||||
|
||||
appendElement("div") {
|
||||
val kInput = appendElement("input", {}) as HTMLInputElement
|
||||
|
||||
appendElement("button") {
|
||||
textContent = "Add key"
|
||||
addEventListener("click", {
|
||||
webApp.cloudStorage.set(kInput.value, kInput.value) {
|
||||
document.body ?.log(it.toString())
|
||||
this@updateCloudStorageContent.updateCloudStorageContent()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
appendElement("p", {})
|
||||
}.onFailure {
|
||||
document.body ?.log(it.stackTraceToString())
|
||||
}
|
||||
val storageTrigger = remember { mutableStateOf<List<Pair<CloudStorageKey, CloudStorageValue>>>(emptyList()) }
|
||||
fun updateCloudStorage() {
|
||||
webApp.cloudStorage.getAll {
|
||||
it.onSuccess {
|
||||
storageTrigger.value = it.toList().sortedBy { it.first.key }
|
||||
}
|
||||
}
|
||||
val cloudStorageContentDiv = document.body ?.appendElement("div") {} as HTMLDivElement
|
||||
|
||||
document.body ?.appendElement("p", {})
|
||||
}
|
||||
key(storageTrigger.value) {
|
||||
storageTrigger.value.forEach { (key, value) ->
|
||||
val keyState = remember { mutableStateOf(key.key) }
|
||||
val valueState = remember { mutableStateOf(value.value) }
|
||||
Input(InputType.Text) {
|
||||
value(key.key)
|
||||
onInput { keyState.value = it.value }
|
||||
}
|
||||
Input(InputType.Text) {
|
||||
value(value.value)
|
||||
onInput { valueState.value = it.value }
|
||||
}
|
||||
Button({
|
||||
onClick {
|
||||
if (key.key != keyState.value) {
|
||||
webApp.cloudStorage.remove(key)
|
||||
}
|
||||
webApp.cloudStorage.set(keyState.value, valueState.value)
|
||||
updateCloudStorage()
|
||||
}
|
||||
}) {
|
||||
Text("Save")
|
||||
}
|
||||
}
|
||||
let { // new element adding
|
||||
val keyState = remember { mutableStateOf("") }
|
||||
val valueState = remember { mutableStateOf("") }
|
||||
Input(InputType.Text) {
|
||||
onInput { keyState.value = it.value }
|
||||
}
|
||||
Input(InputType.Text) {
|
||||
onInput { valueState.value = it.value }
|
||||
}
|
||||
Button({
|
||||
onClick {
|
||||
webApp.cloudStorage.set(keyState.value, valueState.value)
|
||||
updateCloudStorage()
|
||||
}
|
||||
}) {
|
||||
Text("Save")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
remember {
|
||||
webApp.apply {
|
||||
|
||||
onThemeChanged {
|
||||
document.body ?.log("Theme changed: ${webApp.themeParams}")
|
||||
logsState.add("Theme changed: ${webApp.themeParams}")
|
||||
}
|
||||
onViewportChanged {
|
||||
document.body ?.log("Viewport changed: ${it.isStateStable}")
|
||||
logsState.add("Viewport changed: ${it}")
|
||||
}
|
||||
backButton.apply {
|
||||
onClick {
|
||||
document.body ?.log("Back button clicked")
|
||||
logsState.add("Back button clicked")
|
||||
hapticFeedback.impactOccurred(
|
||||
HapticFeedbackStyle.Heavy
|
||||
)
|
||||
@@ -280,30 +404,249 @@ fun main() {
|
||||
mainButton.apply {
|
||||
setText("Main button")
|
||||
onClick {
|
||||
document.body ?.log("Main button clicked")
|
||||
logsState.add("Main button clicked")
|
||||
hapticFeedback.notificationOccurred(
|
||||
HapticFeedbackType.Success
|
||||
)
|
||||
}
|
||||
show()
|
||||
}
|
||||
secondaryButton.apply {
|
||||
setText("Secondary button")
|
||||
onClick {
|
||||
logsState.add("Secondary button clicked")
|
||||
hapticFeedback.notificationOccurred(
|
||||
HapticFeedbackType.Warning
|
||||
)
|
||||
}
|
||||
show()
|
||||
}
|
||||
onSettingsButtonClicked {
|
||||
document.body ?.log("Settings button clicked")
|
||||
logsState.add("Settings button clicked")
|
||||
}
|
||||
onWriteAccessRequested {
|
||||
document.body ?.log("Write access request result: $it")
|
||||
logsState.add("Write access request result: $it")
|
||||
}
|
||||
onContactRequested {
|
||||
document.body ?.log("Contact request result: $it")
|
||||
logsState.add("Contact request result: $it")
|
||||
}
|
||||
}
|
||||
webApp.ready()
|
||||
document.body ?.appendElement("input", {
|
||||
(this as HTMLInputElement).value = window.location.href
|
||||
})
|
||||
cloudStorageContentDiv.updateCloudStorageContent()
|
||||
}.onFailure {
|
||||
window.alert(it.stackTraceToString())
|
||||
}
|
||||
P()
|
||||
|
||||
let { // Accelerometer
|
||||
val enabledState = remember { mutableStateOf(webApp.accelerometer.isStarted) }
|
||||
webApp.onAccelerometerStarted { enabledState.value = true }
|
||||
webApp.onAccelerometerStopped { enabledState.value = false }
|
||||
Button({
|
||||
onClick {
|
||||
if (enabledState.value) {
|
||||
webApp.accelerometer.stop { }
|
||||
} else {
|
||||
webApp.accelerometer.start(AccelerometerStartParams(200))
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Text("${if (enabledState.value) "Stop" else "Start"} accelerometer")
|
||||
}
|
||||
val xState = remember { mutableStateOf(webApp.accelerometer.x) }
|
||||
val yState = remember { mutableStateOf(webApp.accelerometer.y) }
|
||||
val zState = remember { mutableStateOf(webApp.accelerometer.z) }
|
||||
fun updateValues() {
|
||||
xState.value = webApp.accelerometer.x
|
||||
yState.value = webApp.accelerometer.y
|
||||
zState.value = webApp.accelerometer.z
|
||||
}
|
||||
remember {
|
||||
updateValues()
|
||||
}
|
||||
|
||||
webApp.onAccelerometerChanged {
|
||||
updateValues()
|
||||
}
|
||||
if (enabledState.value) {
|
||||
P()
|
||||
Text("x: ${xState.value}")
|
||||
P()
|
||||
Text("y: ${yState.value}")
|
||||
P()
|
||||
Text("z: ${zState.value}")
|
||||
}
|
||||
}
|
||||
P()
|
||||
|
||||
let { // Gyroscope
|
||||
val enabledState = remember { mutableStateOf(webApp.gyroscope.isStarted) }
|
||||
webApp.onGyroscopeStarted { enabledState.value = true }
|
||||
webApp.onGyroscopeStopped { enabledState.value = false }
|
||||
Button({
|
||||
onClick {
|
||||
if (enabledState.value) {
|
||||
webApp.gyroscope.stop { }
|
||||
} else {
|
||||
webApp.gyroscope.start(GyroscopeStartParams(200))
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Text("${if (enabledState.value) "Stop" else "Start"} gyroscope")
|
||||
}
|
||||
val xState = remember { mutableStateOf(webApp.gyroscope.x) }
|
||||
val yState = remember { mutableStateOf(webApp.gyroscope.y) }
|
||||
val zState = remember { mutableStateOf(webApp.gyroscope.z) }
|
||||
fun updateValues() {
|
||||
xState.value = webApp.gyroscope.x
|
||||
yState.value = webApp.gyroscope.y
|
||||
zState.value = webApp.gyroscope.z
|
||||
}
|
||||
remember {
|
||||
updateValues()
|
||||
}
|
||||
|
||||
webApp.onGyroscopeChanged {
|
||||
updateValues()
|
||||
}
|
||||
if (enabledState.value) {
|
||||
P()
|
||||
Text("x: ${xState.value}")
|
||||
P()
|
||||
Text("y: ${yState.value}")
|
||||
P()
|
||||
Text("z: ${zState.value}")
|
||||
}
|
||||
}
|
||||
P()
|
||||
|
||||
let { // DeviceOrientation
|
||||
val enabledState = remember { mutableStateOf(webApp.deviceOrientation.isStarted) }
|
||||
webApp.onDeviceOrientationStarted { enabledState.value = true }
|
||||
webApp.onDeviceOrientationStopped { enabledState.value = false }
|
||||
Button({
|
||||
onClick {
|
||||
if (enabledState.value) {
|
||||
webApp.deviceOrientation.stop { }
|
||||
} else {
|
||||
webApp.deviceOrientation.start(DeviceOrientationStartParams(200))
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Text("${if (enabledState.value) "Stop" else "Start"} deviceOrientation")
|
||||
}
|
||||
val alphaState = remember { mutableStateOf(webApp.deviceOrientation.alpha) }
|
||||
val betaState = remember { mutableStateOf(webApp.deviceOrientation.beta) }
|
||||
val gammaState = remember { mutableStateOf(webApp.deviceOrientation.gamma) }
|
||||
fun updateValues() {
|
||||
alphaState.value = webApp.deviceOrientation.alpha
|
||||
betaState.value = webApp.deviceOrientation.beta
|
||||
gammaState.value = webApp.deviceOrientation.gamma
|
||||
}
|
||||
remember {
|
||||
updateValues()
|
||||
}
|
||||
|
||||
webApp.onDeviceOrientationChanged {
|
||||
updateValues()
|
||||
}
|
||||
if (enabledState.value) {
|
||||
P()
|
||||
Text("alpha: ${alphaState.value}")
|
||||
P()
|
||||
Text("beta: ${betaState.value}")
|
||||
P()
|
||||
Text("gamma: ${gammaState.value}")
|
||||
}
|
||||
}
|
||||
P()
|
||||
|
||||
EventType.values().forEach { eventType ->
|
||||
when (eventType) {
|
||||
EventType.AccelerometerChanged -> webApp.onAccelerometerChanged { /*logsState.add("AccelerometerChanged") /* see accelerometer block */ */ }
|
||||
EventType.AccelerometerFailed -> webApp.onAccelerometerFailed {
|
||||
logsState.add(it.error)
|
||||
}
|
||||
EventType.AccelerometerStarted -> webApp.onAccelerometerStarted { logsState.add("AccelerometerStarted") }
|
||||
EventType.AccelerometerStopped -> webApp.onAccelerometerStopped { logsState.add("AccelerometerStopped") }
|
||||
EventType.Activated -> webApp.onActivated { logsState.add("Activated") }
|
||||
EventType.BackButtonClicked -> webApp.onBackButtonClicked { logsState.add("BackButtonClicked") }
|
||||
EventType.BiometricAuthRequested -> webApp.onBiometricAuthRequested {
|
||||
logsState.add(it.isAuthenticated)
|
||||
}
|
||||
EventType.BiometricManagerUpdated -> webApp.onBiometricManagerUpdated { logsState.add("BiometricManagerUpdated") }
|
||||
EventType.BiometricTokenUpdated -> webApp.onBiometricTokenUpdated {
|
||||
logsState.add(it.isUpdated)
|
||||
}
|
||||
EventType.ClipboardTextReceived -> webApp.onClipboardTextReceived {
|
||||
logsState.add(it.data)
|
||||
}
|
||||
EventType.ContactRequested -> webApp.onContactRequested {
|
||||
logsState.add(it.status)
|
||||
}
|
||||
EventType.ContentSafeAreaChanged -> webApp.onContentSafeAreaChanged { logsState.add("ContentSafeAreaChanged") }
|
||||
EventType.Deactivated -> webApp.onDeactivated { logsState.add("Deactivated") }
|
||||
EventType.DeviceOrientationChanged -> webApp.onDeviceOrientationChanged { /*logsState.add("DeviceOrientationChanged")*//* see accelerometer block */ }
|
||||
EventType.DeviceOrientationFailed -> webApp.onDeviceOrientationFailed {
|
||||
logsState.add(it.error)
|
||||
}
|
||||
EventType.DeviceOrientationStarted -> webApp.onDeviceOrientationStarted { logsState.add("DeviceOrientationStarted") }
|
||||
EventType.DeviceOrientationStopped -> webApp.onDeviceOrientationStopped { logsState.add("DeviceOrientationStopped") }
|
||||
EventType.EmojiStatusAccessRequested -> webApp.onEmojiStatusAccessRequested {
|
||||
logsState.add(it.status)
|
||||
}
|
||||
EventType.EmojiStatusFailed -> webApp.onEmojiStatusFailed {
|
||||
logsState.add(it.error)
|
||||
}
|
||||
EventType.EmojiStatusSet -> webApp.onEmojiStatusSet { logsState.add("EmojiStatusSet") }
|
||||
EventType.FileDownloadRequested -> webApp.onFileDownloadRequested {
|
||||
logsState.add(it.status)
|
||||
}
|
||||
EventType.FullscreenChanged -> webApp.onFullscreenChanged { logsState.add("FullscreenChanged") }
|
||||
EventType.FullscreenFailed -> webApp.onFullscreenFailed {
|
||||
logsState.add(it.error)
|
||||
}
|
||||
EventType.GyroscopeChanged -> webApp.onGyroscopeChanged { /*logsState.add("GyroscopeChanged")*//* see gyroscope block */ }
|
||||
EventType.GyroscopeFailed -> webApp.onGyroscopeFailed {
|
||||
logsState.add(it.error)
|
||||
}
|
||||
EventType.GyroscopeStarted -> webApp.onGyroscopeStarted { logsState.add("GyroscopeStarted")/* see accelerometer block */ }
|
||||
EventType.GyroscopeStopped -> webApp.onGyroscopeStopped { logsState.add("GyroscopeStopped") }
|
||||
EventType.HomeScreenAdded -> webApp.onHomeScreenAdded { logsState.add("HomeScreenAdded") }
|
||||
EventType.HomeScreenChecked -> webApp.onHomeScreenChecked {
|
||||
logsState.add(it.status)
|
||||
}
|
||||
EventType.InvoiceClosed -> webApp.onInvoiceClosed { url, status ->
|
||||
logsState.add(url)
|
||||
logsState.add(status)
|
||||
}
|
||||
EventType.LocationManagerUpdated -> webApp.onLocationManagerUpdated { logsState.add("LocationManagerUpdated") }
|
||||
EventType.LocationRequested -> webApp.onLocationRequested {
|
||||
logsState.add(it.locationData)
|
||||
}
|
||||
EventType.MainButtonClicked -> webApp.onMainButtonClicked { logsState.add("MainButtonClicked") }
|
||||
EventType.PopupClosed -> webApp.onPopupClosed {
|
||||
logsState.add(it.buttonId)
|
||||
}
|
||||
EventType.QrTextReceived -> webApp.onQrTextReceived {
|
||||
logsState.add(it.data)
|
||||
}
|
||||
EventType.SafeAreaChanged -> webApp.onSafeAreaChanged { logsState.add("SafeAreaChanged") }
|
||||
EventType.ScanQrPopupClosed -> webApp.onScanQrPopupClosed { logsState.add("ScanQrPopupClosed") }
|
||||
EventType.SecondaryButtonClicked -> webApp.onSecondaryButtonClicked { logsState.add("SecondaryButtonClicked") }
|
||||
EventType.SettingsButtonClicked -> webApp.onSettingsButtonClicked { logsState.add("SettingsButtonClicked") }
|
||||
EventType.ShareMessageFailed -> webApp.onShareMessageFailed {
|
||||
logsState.add(it.error)
|
||||
}
|
||||
EventType.ShareMessageSent -> webApp.onShareMessageSent { logsState.add("ShareMessageSent") }
|
||||
EventType.ThemeChanged -> webApp.onThemeChanged { logsState.add("ThemeChanged") }
|
||||
EventType.ViewportChanged -> webApp.onViewportChanged {
|
||||
logsState.add(it)
|
||||
}
|
||||
EventType.WriteAccessRequested -> webApp.onWriteAccessRequested {
|
||||
logsState.add(it.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logsState.forEach {
|
||||
P { Text(it.toString()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<title>Web App Example</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="application/javascript" src="https://telegram.org/js/telegram-web-app.js"></script>
|
||||
<script type="application/javascript" src="WebApp.js"></script>
|
||||
</body>
|
||||
|
||||
@@ -6,6 +6,7 @@ import dev.inmo.tgbotapi.extensions.api.bot.getMe
|
||||
import dev.inmo.tgbotapi.extensions.api.bot.setMyCommands
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.send
|
||||
import dev.inmo.tgbotapi.extensions.api.set.setUserEmojiStatus
|
||||
import dev.inmo.tgbotapi.extensions.api.telegramBot
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.buildBehaviourWithLongPolling
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onBaseInlineQuery
|
||||
@@ -16,12 +17,9 @@ import dev.inmo.tgbotapi.extensions.utils.types.buttons.inlineKeyboard
|
||||
import dev.inmo.tgbotapi.extensions.utils.types.buttons.replyKeyboard
|
||||
import dev.inmo.tgbotapi.extensions.utils.types.buttons.webAppButton
|
||||
import dev.inmo.tgbotapi.requests.answers.InlineQueryResultsButton
|
||||
import dev.inmo.tgbotapi.types.BotCommand
|
||||
import dev.inmo.tgbotapi.types.*
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InlineQueryResult.InlineQueryResultArticle
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InputMessageContent.InputTextMessageContent
|
||||
import dev.inmo.tgbotapi.types.InlineQueryId
|
||||
import dev.inmo.tgbotapi.types.LinkPreviewOptions
|
||||
import dev.inmo.tgbotapi.types.webAppQueryIdField
|
||||
import dev.inmo.tgbotapi.types.webapps.WebAppInfo
|
||||
import dev.inmo.tgbotapi.utils.*
|
||||
import io.ktor.http.*
|
||||
@@ -30,7 +28,6 @@ import io.ktor.server.http.content.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.File
|
||||
|
||||
@@ -63,10 +60,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/")
|
||||
@@ -108,6 +102,26 @@ suspend fun main(vararg args: String) {
|
||||
|
||||
call.respond(HttpStatusCode.OK, isSafe.toString())
|
||||
}
|
||||
post("setCustomEmoji") {
|
||||
val requestBody = call.receiveText()
|
||||
val webAppCheckData = Json.decodeFromString(WebAppDataWrapper.serializer(), requestBody)
|
||||
|
||||
val isSafe = telegramBotAPIUrlsKeeper.checkWebAppData(webAppCheckData.data, webAppCheckData.hash)
|
||||
val rawUserId = call.parameters[userIdField] ?.toLongOrNull() ?.let(::RawChatId) ?: error("$userIdField should be presented as long value")
|
||||
|
||||
val set = if (isSafe) {
|
||||
runCatching {
|
||||
bot.setUserEmojiStatus(
|
||||
UserId(rawUserId),
|
||||
CustomEmojiIdToSet
|
||||
)
|
||||
}.getOrElse { false }
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
||||
call.respond(HttpStatusCode.OK, set.toString())
|
||||
}
|
||||
}
|
||||
}.start(false)
|
||||
|
||||
|
||||
28
WebHooks/README.md
Normal file
28
WebHooks/README.md
Normal 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
23
WebHooks/build.gradle
Normal 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"
|
||||
}
|
||||
87
WebHooks/src/main/kotlin/WebHooks.kt
Normal file
87
WebHooks/src/main/kotlin/WebHooks.kt
Normal 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)
|
||||
}
|
||||
@@ -29,3 +29,8 @@ allprojects {
|
||||
maven { url "https://nexus.inmo.dev/repository/maven-releases/" }
|
||||
}
|
||||
}
|
||||
|
||||
// Fix of https://youtrack.jetbrains.com/issue/KTOR-7912/Module-not-found-errors-when-executing-browserProductionWebpack-task-since-3.0.2
|
||||
rootProject.plugins.withType(org.jetbrains.kotlin.gradle.targets.js.yarn.YarnPlugin.class) {
|
||||
rootProject.kotlinYarn.resolution("ws", "8.18.0")
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
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=23.1.1
|
||||
micro_utils_version=0.24.4
|
||||
serialization_version=1.8.0
|
||||
ktor_version=3.0.3
|
||||
compose_version=1.7.3
|
||||
|
||||
2
gradle/wrapper/gradle-wrapper.properties
vendored
2
gradle/wrapper/gradle-wrapper.properties
vendored
@@ -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
|
||||
|
||||
@@ -52,4 +52,10 @@ include ":BusinessConnectionsBot"
|
||||
|
||||
include ":StarTransactionsBot"
|
||||
|
||||
include ":GiveawaysBot"
|
||||
|
||||
include ":CustomBot"
|
||||
|
||||
include ":MemberUpdatedWatcherBot"
|
||||
|
||||
include ":WebHooks"
|
||||
|
||||
Reference in New Issue
Block a user