mirror of
https://github.com/InsanusMokrassar/TelegramBotAPI-examples.git
synced 2026-11-27 13:52:58 +00:00
update examples for ktgbotapi 38.0.0
This commit is contained in:
1 parent
d0da6c851b
commit
97b4391495
86 files changed
+888
-370
No files matched your search
@@ -0,0 +1,27 @@
|
||||
# WidgetsBot
|
||||
|
||||
WidgetsBot sends an interactive die inside a Telegram message. Tap **Roll a die** to get a private answer with your result. The bot also saves the number in the widget so anyone viewing that message can see the last roll.
|
||||
|
||||
## Run
|
||||
|
||||
Create a bot with BotFather and open its private chat in a Telegram client that supports widgets. From the repository root, run the long-polling bot with its token. [BotFather](https://t.me/BotFather)
|
||||
|
||||
```bash
|
||||
./gradlew :WidgetsBot:run --args="<BOT_TOKEN>"
|
||||
```
|
||||
|
||||
The optional `debug` argument enables diagnostic logging. Telegram currently supports widgets in private chats with the bot in production. To try groups, forwards, or inline results, use a bot token and account created in Telegram's test environment and add `testServer` after the token. [Test account setup](https://core.telegram.org/bots/features#creating-a-bot-in-the-test-environment) · [Widget availability](https://core.telegram.org/bots/widgets#availability)
|
||||
|
||||
## Try the widgets
|
||||
|
||||
| Command | What to try |
|
||||
| --- | --- |
|
||||
| `/start` | Show the two widget commands. |
|
||||
| `/widget` | Send a die and tap it. Send a second one to see that each message keeps its own last roll in `chatData`. |
|
||||
| `/sharedwidget` | Send two messages showing the same die. Tap either one and watch both last-roll values change to match. On the test server, forward one and roll it from the forward. |
|
||||
|
||||
`sendWidget` creates the shared die with `isShared = true` and `allowQueries = true`. The bot reads `widget.id` from the returned message and passes it to `sendSharedWidget` for the second message.
|
||||
|
||||
To try inline mode, send `/setinline` to BotFather on the test server, select the bot, and enter a placeholder. In a private chat or group, type `@your_bot_username` followed by a space and select **Roll a die**. Each selected `InputWidgetMessageContent` starts a new die. [Telegram inline setup](https://core.telegram.org/bots/inline) · [Inline widgets](https://core.telegram.org/bots/widgets#inline-mode-widgets)
|
||||
|
||||
A tap in a bot-sent or inline message reaches `onWidgetQuery`. A tap in a forward of the shared die reaches `onSharedWidgetQuery`. The bot calls `answerWidgetQuery` for the tapping viewer, then writes the roll with `editMessageWidgetData` using either the chat and message IDs or the inline message ID. For a shared die it calls `editSharedWidgetData` with the widget ID. Open copies call `watchPublicData()` to refresh on Telegram's polling interval. The example requests a five-second interval when saving a shared roll. [Telegram widget guide](https://core.telegram.org/bots/widgets#requests-to-the-bot)
|
||||
@@ -0,0 +1,19 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'kotlin'
|
||||
apply plugin: 'application'
|
||||
|
||||
application.mainClass = "WidgetsBotKt"
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||
implementation "dev.inmo:tgbotapi:$telegram_bot_api_version"
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
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.tgbotapi.bot.TelegramBot
|
||||
import dev.inmo.tgbotapi.bot.exceptions.MessageIsNotModifiedException
|
||||
import dev.inmo.tgbotapi.extensions.api.answers.answerInlineQuery
|
||||
import dev.inmo.tgbotapi.extensions.api.answers.answerWidgetQuery
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.widgets.editMessageWidgetData
|
||||
import dev.inmo.tgbotapi.extensions.api.edit.widgets.editSharedWidgetData
|
||||
import dev.inmo.tgbotapi.extensions.api.send.reply
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendSharedWidget
|
||||
import dev.inmo.tgbotapi.extensions.api.send.sendWidget
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.telegramBotWithBehaviourAndLongPolling
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onAnyInlineQuery
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onSharedWidgetQuery
|
||||
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onWidgetQuery
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InlineQueryResult.InlineQueryResultArticle
|
||||
import dev.inmo.tgbotapi.types.InlineQueries.InputMessageContent.InputWidgetMessageContent
|
||||
import dev.inmo.tgbotapi.types.InlineQueryId
|
||||
import dev.inmo.tgbotapi.types.chat.ChatType
|
||||
import dev.inmo.tgbotapi.types.widgets.WidgetQuery
|
||||
import dev.inmo.tgbotapi.types.widgets.WidgetQuerySource
|
||||
import dev.inmo.tgbotapi.types.widgets.WidgetQueryType
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlin.random.Random
|
||||
|
||||
private suspend fun TelegramBot.rollDie(query: WidgetQuerySource) {
|
||||
if (query.type !is WidgetQueryType.Data || query.data != "roll") {
|
||||
answerWidgetQuery(query, "Unknown die action.")
|
||||
return
|
||||
}
|
||||
|
||||
val roll = Random.nextInt(1, 7).toString()
|
||||
answerWidgetQuery(query, "You rolled $roll.")
|
||||
|
||||
val widgetId = query.widgetId
|
||||
val original = query as? WidgetQuery
|
||||
val inlineMessageId = original?.inlineMessageId
|
||||
val chat = original?.chat
|
||||
val messageId = original?.messageId
|
||||
try {
|
||||
when {
|
||||
widgetId != null -> editSharedWidgetData(widgetId, publicData = roll, cacheTime = 5)
|
||||
inlineMessageId != null -> editMessageWidgetData(inlineMessageId, chatData = roll)
|
||||
chat != null && messageId != null -> editMessageWidgetData(chat, messageId, chatData = roll)
|
||||
}
|
||||
} catch (_: MessageIsNotModifiedException) {
|
||||
// Two consecutive rolls can have the same value. The widget already shows it.
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun main(vararg args: String) {
|
||||
val botToken = requireNotNull(args.firstOrNull()) { "Pass the bot token as the first argument." }
|
||||
val isTestServer = "testServer" in args
|
||||
if ("debug" in args) {
|
||||
setDefaultKSLog(
|
||||
KSLog { level: LogLevel, tag: String?, message: Any, throwable: Throwable? ->
|
||||
println(defaultMessageFormatter(level, tag, message, throwable))
|
||||
}
|
||||
)
|
||||
}
|
||||
val dieHtml = checkNotNull(Thread.currentThread().contextClassLoader.getResource("die.html")).readText()
|
||||
val messageDie = InputWidgetMessageContent(
|
||||
html = dieHtml,
|
||||
chatData = "No rolls yet",
|
||||
allowQueries = true,
|
||||
text = "Roll this die to update its last roll in this message."
|
||||
)
|
||||
val inlineDie = InlineQueryResultArticle(
|
||||
id = InlineQueryId("die"),
|
||||
title = "Roll a die",
|
||||
inputMessageContent = messageDie
|
||||
)
|
||||
|
||||
telegramBotWithBehaviourAndLongPolling(
|
||||
botToken,
|
||||
CoroutineScope(Dispatchers.IO),
|
||||
testServer = isTestServer
|
||||
) {
|
||||
onCommand("start") {
|
||||
reply(it, "Use /widget for a die in one message or /sharedwidget to roll the same die in two messages.")
|
||||
}
|
||||
onCommand("widget") { message ->
|
||||
sendWidget(message.chat, messageDie)
|
||||
}
|
||||
onCommand("sharedwidget") { message ->
|
||||
val first = sendWidget(
|
||||
message.chat,
|
||||
html = dieHtml,
|
||||
publicData = "No rolls yet",
|
||||
allowQueries = true,
|
||||
isShared = true,
|
||||
text = "This die shares its last roll with every copy."
|
||||
)
|
||||
val widgetId = checkNotNull(first.content.widget.id) { "Telegram did not return a shared widget ID." }
|
||||
sendSharedWidget(message.chat, widgetId, text = "Roll here and watch the other message update.")
|
||||
}
|
||||
onAnyInlineQuery { query ->
|
||||
val results = if (isTestServer && query.chatType != ChatType.Channel) {
|
||||
listOf(inlineDie)
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
answerInlineQuery(query, results, cachedTime = 0)
|
||||
}
|
||||
|
||||
onWidgetQuery { rollDie(it) }
|
||||
onSharedWidgetQuery { rollDie(it) }
|
||||
}.second.join()
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<body>
|
||||
<h3>Last roll</h3>
|
||||
<p id="last-roll">No rolls yet</p>
|
||||
<button id="roll" disabled>Roll a die</button>
|
||||
<p id="answer"></p>
|
||||
<script>
|
||||
const widget = window.TelegramWidget;
|
||||
if (widget) {
|
||||
const lastRoll = document.getElementById('last-roll');
|
||||
const button = document.getElementById('roll');
|
||||
const answer = document.getElementById('answer');
|
||||
|
||||
function render() {
|
||||
lastRoll.textContent = widget.chatData || widget.publicData || 'No rolls yet';
|
||||
}
|
||||
|
||||
widget.onEvent('chatDataChanged', render);
|
||||
widget.onEvent('publicDataChanged', render);
|
||||
widget.watchPublicData();
|
||||
render();
|
||||
|
||||
button.disabled = !widget.viewer;
|
||||
button.addEventListener('click', () => {
|
||||
button.disabled = true;
|
||||
widget.request('roll').then(
|
||||
response => { answer.textContent = response.result; },
|
||||
error => { answer.textContent = 'Roll failed (' + error.code + ').'; }
|
||||
).finally(() => { button.disabled = false; });
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user