### Kotlin Logging Examples
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
Demonstrates how to use the Kotlin Logging library for different log levels and exception logging within a bot application. This requires the Kotlin Logging library as a dependency.
```kotlin
import io.github.oshai.kotlinlogging.KotlinLogging
val logger = KotlinLogging.logger {}
// Different log levels in use
logger.debug { "WebSocket message received: $payload" }
logger.info { "Bot connected successfully" }
logger.warn { "Reconnecting in 5 seconds..." }
logger.error { "Failed to authenticate: ${e.message}" }
// Log with exception
try {
// Bot operations
} catch (e: Exception) {
logger.error(e) { "Critical error occurred: ${e.localizedMessage}" }
}
```
--------------------------------
### Run QQBot Application
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
This command executes a QQ Bot application packaged as a JAR file. Ensure the Java Runtime Environment is installed and accessible in your system's PATH.
```bash
java -jar your-qqbot-app.jar
```
--------------------------------
### Implement Custom API Endpoints (Kotlin)
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
This snippet shows how to extend the OpenApi base class to create custom API endpoints for interacting with QQ Bot services. It includes examples for GET, POST, PUT, and DELETE requests, handling both simple data and payloads. The implementation requires an AccessInfo object and relies on the sdk's exception handling.
```kotlin
import me.zhenxin.qqbot.api.OpenApi
import me.zhenxin.qqbot.entity.AccessInfo
import me.zhenxin.qqbot.entity.User
// Define response data class
data class MessageResponse(
val id: String,
val channelId: String,
val content: String
)
// Create custom API class extending OpenApi
class MessageApi(accessInfo: AccessInfo) : OpenApi(accessInfo) {
// GET request example
fun getMessage(channelId: String, messageId: String): MessageResponse {
return get("/channels/$channelId/messages/$messageId", MessageResponse::class.java)
}
// POST request example with payload
fun sendMessage(channelId: String, content: String): MessageResponse {
val data = mapOf(
"content" to content,
"msg_id" to System.currentTimeMillis().toString()
)
return post("/channels/$channelId/messages", data, MessageResponse::class.java)
}
// PUT request example
fun updateMessage(channelId: String, messageId: String, newContent: String): MessageResponse {
val data = mapOf("content" to newContent)
return put("/channels/$channelId/messages/$messageId", data, MessageResponse::class.java)
}
// DELETE request example
fun deleteMessage(channelId: String, messageId: String): MessageResponse {
return delete("/channels/$channelId/messages/$messageId", MessageResponse::class.java)
}
}
// Usage
val accessInfo = AccessInfo(
botAppId = 123456,
botSecret = "your-secret",
isSandbox = true
)
val messageApi = MessageApi(accessInfo)
// Send a message
try {
val response = messageApi.sendMessage("channel-id-123", "Hello, QQ!")
println("Message sent: ${response.id}")
} catch (e: me.zhenxin.qqbot.exception.ApiException) {
println("API Error: ${e.code} - ${e.detail} (Trace: ${e.traceId})")
}
```
--------------------------------
### Configure QQBot Logging Levels via Environment Variable
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
This example shows how to set the logging level for the QQBot SDK using an environment variable before running the bot. It specifies the available log levels: DEBUG, INFO, WARN, and ERROR, with DEBUG providing the most detailed output.
```bash
# Set log level before running your bot
export QQBOT_LOG_LEVEL=DEBUG
# Available log levels:
# DEBUG - Detailed debugging information including HTTP requests/responses
# INFO - General informational messages (default)
# WARN - Warning messages for potentially problematic situations
# ERROR - Error messages for serious issues
```
--------------------------------
### Initialize and Connect QQ Bot (Kotlin/Java)
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
Demonstrates how to initialize a QQ bot instance and connect to the QQ gateway by configuring access credentials and registering event intents. Supports both Kotlin and Java, requiring environment variables for bot credentials.
```kotlin
import me.zhenxin.qqbot.BotCore
import me.zhenxin.qqbot.entity.AccessInfo
import me.zhenxin.qqbot.enums.Intent
import me.zhenxin.qqbot.exception.ApiException
import io.github.oshai.kotlinlogging.KotlinLogging
val logger = KotlinLogging.logger {}
fun main() {
// Configure bot access credentials
val accessInfo = AccessInfo().apply {
botAppId = System.getenv("BOT_APP_ID")?.toInt() ?: 0
botToken = System.getenv("BOT_TOKEN") ?: ""
botSecret = System.getenv("BOT_SECRET") ?: ""
isSandbox = System.getenv("IS_SANDBOX")?.toBoolean() ?: true
}
try {
val bot = BotCore(accessInfo)
// Register event intents to subscribe to specific events
bot.registerIntents(
Intent.GUILDS, // Guild-related events
Intent.GUILD_MEMBERS, // Guild member events
Intent.GUILD_MESSAGE_REACTIONS, // Message reaction events
Intent.DIRECT_MESSAGE, // Private message events
Intent.OPEN_FORUMS_EVENTS, // Public forum events
Intent.AUDIO_OR_LIVE_CHANNEL_MEMBERS, // Voice/live channel events
Intent.INTERACTION, // Interaction events
Intent.MESSAGE_AUDIT, // Message audit events
Intent.PUBLIC_GUILD_MESSAGES // Public guild messages
)
// Connect to QQ gateway and start receiving events
bot.start()
} catch (e: ApiException) {
logger.error { "API Error: Code=${e.code}, Message=${e.message}, Detail=${e.detail}, TraceId=${e.traceId}" }
e.printStackTrace()
}
}
```
```java
import me.zhenxin.qqbot.BotCore;
import me.zhenxin.qqbot.entity.AccessInfo;
import me.zhenxin.qqbot.enums.Intent;
public class BotTest {
public static void main(String[] args) {
// Read credentials from environment variables
String botAppId = System.getenv("BOT_APP_ID");
String botToken = System.getenv("BOT_TOKEN");
String botSecret = System.getenv("BOT_SECRET");
// Create access info object
AccessInfo accessInfo = new AccessInfo();
accessInfo.setBotAppId(Integer.parseInt(botAppId));
accessInfo.setBotToken(botToken);
accessInfo.setBotSecret(botSecret);
accessInfo.setSandbox(true);
// Initialize bot with credentials
BotCore bot = new BotCore(accessInfo);
// Subscribe to events by registering intents
bot.registerIntents(
Intent.GUILDS,
Intent.GUILD_MEMBERS,
Intent.GUILD_MESSAGE_REACTIONS,
Intent.DIRECT_MESSAGE,
Intent.OPEN_FORUMS_EVENTS,
Intent.AUDIO_OR_LIVE_CHANNEL_MEMBERS,
Intent.INTERACTION,
Intent.MESSAGE_AUDIT,
Intent.PUBLIC_GUILD_MESSAGES
);
// Start bot and establish WebSocket connection
bot.start();
}
}
```
--------------------------------
### Add QQBot SDK Dependency
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
Instructions for adding the QQBot SDK to your project using Gradle (Kotlin and Groovy DSL) and Maven build tools. Ensure you have a compatible Java/Kotlin environment.
```kotlin
// Kotlin DSL (build.gradle.kts)
implementation("me.zhenxin:qqbot-sdk:2.0.0-dev")
```
```groovy
// Groovy DSL (build.gradle)
implementation 'me.zhenxin:qqbot-sdk:2.0.0-dev'
```
```xml
me.zhenxin
qqbot-sdk
2.0.0-dev
```
--------------------------------
### Retrieve Gateway API Information (Kotlin)
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
This snippet demonstrates how to retrieve gateway connection information, including standard and bot-specific gateway URLs, shard recommendations, and session limits. It utilizes the BotCore and ApiManager from the qqbot-sdk. No external dependencies are required beyond the sdk itself.
```kotlin
import me.zhenxin.qqbot.BotCore
import me.zhenxin.qqbot.entity.AccessInfo
import me.zhenxin.qqbot.api.ApiManager
val accessInfo = AccessInfo(
botAppId = 123456,
botToken = "your-bot-token",
botSecret = "your-bot-secret",
isSandbox = true
)
val bot = BotCore(accessInfo)
// Get API manager to access various API endpoints
val apiManager = bot.getApiManager()
// Get gateway API interface
val gatewayApi = apiManager.getGatewayApi()
// Retrieve standard gateway URL
val gateway = gatewayApi.getGateway()
println("Gateway URL: ${gateway.url}")
// Retrieve bot-specific gateway with shard information
val botGateway = gatewayApi.getBotGateway()
println("Bot Gateway URL: ${botGateway.url}")
println("Recommended Shards: ${botGateway.shards}")
println("Session Limit - Total: ${botGateway.sessionStartLimit.total}")
println("Session Limit - Remaining: ${botGateway.sessionStartLimit.remaining}")
println("Session Limit - Reset After: ${botGateway.sessionStartLimit.resetAfter}")
println("Max Concurrency: ${botGateway.sessionStartLimit.maxConcurrency}")
```
--------------------------------
### Implement WebSocket Event Handling in Kotlin
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
This snippet demonstrates how to create a custom event handler for various bot events such as 'READY', 'GUILD_CREATE', and 'MESSAGE_CREATE'. It parses incoming WebSocket payloads and reacts accordingly. Dependencies include the QQBot SDK and fastjson2 for JSON parsing.
```kotlin
import me.zhenxin.qqbot.BotCore
import me.zhenxin.qqbot.entity.AccessInfo
import me.zhenxin.qqbot.websocket.WebSocketClient
import me.zhenxin.qqbot.entity.Payload
import me.zhenxin.qqbot.entity.Guild
import me.zhenxin.qqbot.entity.Channel
import me.zhenxin.qqbot.entity.Member
import com.alibaba.fastjson2.parseObject
import com.alibaba.fastjson2.toJSONString
class CustomEventHandler(private val client: WebSocketClient) {
fun handleEvent(payload: Payload) {
when (payload.type) {
"READY" -> onReady(payload)
"GUILD_CREATE" -> onGuildJoin(payload)
"GUILD_MEMBER_ADD" -> onMemberJoin(payload)
"CHANNEL_CREATE" -> onChannelCreate(payload)
"MESSAGE_CREATE" -> onMessageReceive(payload)
else -> println("Unknown event: ${payload.type}")
}
}
private fun onReady(payload: Payload) {
val ready = payload.data.toJSONString().parseObject()
println("Bot ${ready.user.username} is now online!")
println("Session ID: ${ready.sessionId}")
client.sessionId = ready.sessionId
}
private fun onGuildJoin(payload: Payload) {
val guild = payload.data.toJSONString().parseObject()
println("Joined guild: ${guild.name} (ID: ${guild.id})")
println("Members: ${guild.memberCount}/${guild.maxMembers}")
println("Owner ID: ${guild.ownerId}")
}
private fun onMemberJoin(payload: Payload) {
val member = payload.data.toJSONString().parseObject()
println("New member: ${member.user.username} (ID: ${member.user.id})")
// Send welcome message or perform other actions
}
private fun onChannelCreate(payload: Payload) {
val channel = payload.data.toJSONString().parseObject()
println("New channel created: ${channel.name}")
println("Type: ${channel.type}, Position: ${channel.position}")
}
private fun onMessageReceive(payload: Payload) {
val data = payload.data.toJSONString().parseObject()
val content = data.getString("content")
val author = data.getJSONObject("author")
val username = author.getString("username")
println("Message from $username: $content")
// Respond to commands
if (content.startsWith("/ping")) {
// Send response using API
}
}
}
```
--------------------------------
### Kotlin Intent System Configuration
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
Illustrates how to configure event intents for a QQ Bot using the `me.zhenxin.qqbot.enums.Intent` enum. Different intents grant access to various event types, with varying permissions. This requires the QQBot SDK's intent enumeration.
```kotlin
import me.zhenxin.qqbot.enums.Intent
/*
* Intent Values and Permissions:
* Each intent subscribes to specific event types
*/
// Guild and channel events (public access)
val guildIntents = listOf(
Intent.GUILDS,
Intent.GUILD_MEMBERS,
Intent.GUILD_MESSAGE_REACTIONS
)
// Message events (different access levels)
val messageIntents = listOf(
Intent.GUILD_MESSAGES,
Intent.PUBLIC_GUILD_MESSAGES,
Intent.DIRECT_MESSAGE
)
// Forum events (public and private)
val forumIntents = listOf(
Intent.OPEN_FORUMS_EVENTS,
Intent.FORUM_EVENT
)
// Audio and interaction events
val specialIntents = listOf(
Intent.AUDIO_OR_LIVE_CHANNEL_MEMBERS,
Intent.INTERACTION,
Intent.MESSAGE_AUDIT,
Intent.AUDIO_ACTION
)
// Minimal bot example with only essential intents
val minimalBot = BotCore(accessInfo).apply {
registerIntents(
Intent.GUILDS,
Intent.PUBLIC_GUILD_MESSAGES
)
start()
}
// Full-featured bot with all intents (requires permissions)
val fullBot = BotCore(accessInfo).apply {
registerIntents(*Intent.values())
start()
}
```
--------------------------------
### Handle API Errors with ApiException in Kotlin
Source: https://context7.com/armoe-project/qqbot-sdk/llms.txt
This Kotlin snippet shows how to implement robust error handling for QQBot API calls using the ApiException. It catches specific error codes like authentication failures, permission issues, rate limiting, and server errors, providing detailed debugging information. It requires ApiManager and AccessInfo from the QQBot SDK.
```kotlin
import me.zhenxin.qqbot.exception.ApiException
import me.zhenxin.qqbot.api.ApiManager
import me.zhenxin.qqbot.entity.AccessInfo
val accessInfo = AccessInfo(
botAppId = 123456,
botSecret = "your-secret",
isSandbox = false
)
val apiManager = ApiManager(accessInfo)
try {
val gatewayApi = apiManager.getGatewayApi()
val gateway = gatewayApi.getBotGateway()
println("Connected to: ${gateway.url}")
} catch (e: ApiException) {
// Handle specific error codes
when (e.code) {
401 -> {
println("Authentication failed: ${e.detail}")
println("Check your botAppId and botSecret")
}
403 -> {
println("Permission denied: ${e.detail}")
println("Bot may lack required permissions")
}
429 -> {
println("Rate limited: ${e.detail}")
println("Too many requests, please wait")
}
500, 502, 503 -> {
println("Server error: ${e.detail}")
println("QQ API is experiencing issues")
}
else -> {
println("API Error occurred:")
println(" Code: ${e.code}")
println(" Message: ${e.message}")
println(" Detail: ${e.detail}")
println(" Trace ID: ${e.traceId}")
}
}
// Log trace ID for support requests
println("Report this trace ID if contacting support: ${e.traceId}")
} catch (e: Exception) {
println("Unexpected error: ${e.message}")
e.printStackTrace()
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.