Skip to content
This repository has been archived by the owner on Oct 20, 2023. It is now read-only.

Commit

Permalink
[U] Updated to 0.3.6-rc2
Browse files Browse the repository at this point in the history
* 修复推送推文时使用了错误的发送目标
* 修复命令执行器可能导致的数组越界问题
* 修正了 B 站用户信息文本缺少换行的问题
* 优化了复读功能, 现在更不容易复读了
* 支持查看距离推送的推文发送时间
  • Loading branch information
StarWishsama committed May 31, 2020
1 parent 3d5f76e commit ee51ebe
Show file tree
Hide file tree
Showing 17 changed files with 195 additions and 122 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jar {
}

group 'io.github.starwishsama.nbot'
version '0.3.6-rc1-200530'
version '0.3.6-rc2-200531'

repositories {
maven { url 'https://jitpack.io' }
Expand Down
2 changes: 2 additions & 0 deletions src/main/kotlin/io/github/starwishsama/nbot/BotConstants.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import io.github.starwishsama.nbot.objects.RandomResult
import io.github.starwishsama.nbot.objects.draw.ArkNightOperator
import io.github.starwishsama.nbot.objects.draw.PCRCharacter
import io.github.starwishsama.nbot.objects.group.Shop
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import java.util.*

Expand All @@ -34,4 +35,5 @@ object BotConstants {

var gson: Gson = GsonBuilder().serializeNulls().setPrettyPrinting().create()
val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm")
val twitterTimeFormat: SimpleDateFormat = SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH)
}
126 changes: 68 additions & 58 deletions src/main/kotlin/io/github/starwishsama/nbot/BotMain.kt
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
package io.github.starwishsama.nbot

import com.hiczp.bilibili.api.BilibiliClient
import io.github.starwishsama.nbot.BotMain.bot
import io.github.starwishsama.nbot.api.bilibili.DynamicApi
import io.github.starwishsama.nbot.api.twitter.TwitterApi
import io.github.starwishsama.nbot.commands.CommandExecutor
import io.github.starwishsama.nbot.commands.subcommands.*
import io.github.starwishsama.nbot.enums.UserLevel
import io.github.starwishsama.nbot.file.*
import io.github.starwishsama.nbot.listeners.*
import io.github.starwishsama.nbot.file.BackupHelper
import io.github.starwishsama.nbot.file.DataSetup
import io.github.starwishsama.nbot.listeners.FuckLightAppListener
import io.github.starwishsama.nbot.listeners.GroupChatListener
import io.github.starwishsama.nbot.listeners.RepeatListener
import io.github.starwishsama.nbot.listeners.SessionListener
import io.github.starwishsama.nbot.managers.TaskManager
import io.github.starwishsama.nbot.objects.BotUser
import io.github.starwishsama.nbot.tasks.CheckLiveStatus
import io.github.starwishsama.nbot.api.twitter.TwitterApi
import io.github.starwishsama.nbot.tasks.LatestTweetChecker
import io.github.starwishsama.nbot.util.getContext
import io.github.starwishsama.nbot.util.writeString
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import net.kronos.rkon.core.Rcon
Expand All @@ -23,7 +29,9 @@ import net.mamoe.mirai.alsoLogin
import net.mamoe.mirai.event.subscribeMessages
import net.mamoe.mirai.join
import net.mamoe.mirai.message.data.EmptyMessageChain
import net.mamoe.mirai.utils.*
import net.mamoe.mirai.utils.BotConfiguration
import net.mamoe.mirai.utils.MiraiLogger
import net.mamoe.mirai.utils.PlatformLogger
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.concurrent.BasicThreadFactory
import java.io.File
Expand All @@ -37,7 +45,7 @@ import kotlin.system.exitProcess

object BotMain {
val filePath: File = File(getPath())
const val version = "0.3.6-rc1-200524"
const val version = "0.3.6-rc2-200531"
var qqId = 0L
lateinit var password: String
lateinit var bot: Bot
Expand All @@ -57,7 +65,7 @@ object BotMain {
"stop" -> exitProcess(0)
"upgrade" -> {
val cmd = command.split(" ")
if (cmd.isNotEmpty() && StringUtils.isNumeric(cmd[1])) {
if (cmd.size > 1 && StringUtils.isNumeric(cmd[1])) {
val user = BotUser.getUser(cmd[1].toLong())
if (user != null) {
logger.info("[CONSOLE] 已升级权限组至 ${UserLevel.upgrade(user)}")
Expand Down Expand Up @@ -109,9 +117,10 @@ object BotMain {
}
}

@ObsoleteCoroutinesApi
suspend fun main() {
BotMain.initLog()
BotMain.startTime = System.currentTimeMillis()
BotMain.initLog()
DataSetup.initData()
BotMain.qqId = BotConstants.cfg.botId
BotMain.password = BotConstants.cfg.botPassword
Expand All @@ -135,30 +144,30 @@ suspend fun main() {
}
config.heartbeatPeriodMillis = BotConstants.cfg.heartBeatPeriod * 60 * 1000
config.fileBasedDeviceInfo()
BotMain.bot = Bot(qq = BotMain.qqId, password = BotMain.password, configuration = config)
BotMain.bot.alsoLogin()
BotMain.logger = BotMain.bot.logger
bot = Bot(qq = BotMain.qqId, password = BotMain.password, configuration = config)
bot.alsoLogin()
BotMain.logger = bot.logger
CommandExecutor.setupCommand(
arrayOf(
AdminCommand(),
BiliBiliCommand(),
CheckInCommand(),
ClockInCommand(),
DebugCommand(),
DivineCommand(),
GachaCommand(),
GuessNumberCommand(),
FlowerCommand(),
HelpCommand(),
InfoCommand(),
MusicCommand(),
MuteCommand(),
PictureSearch(),
R6SCommand(),
RConCommand(),
TwitterCommand(),
VersionCommand()
)
arrayOf(
AdminCommand(),
BiliBiliCommand(),
CheckInCommand(),
ClockInCommand(),
DebugCommand(),
DivineCommand(),
GachaCommand(),
GuessNumberCommand(),
FlowerCommand(),
HelpCommand(),
InfoCommand(),
MusicCommand(),
MuteCommand(),
PictureSearch(),
R6SCommand(),
RConCommand(),
TwitterCommand(),
VersionCommand()
)
)

val listeners = arrayOf(FuckLightAppListener, GroupChatListener, RepeatListener, SessionListener)
Expand All @@ -168,33 +177,34 @@ suspend fun main() {

BotMain.setupRCon()

BotMain.service = Executors.newSingleThreadScheduledExecutor(
BasicThreadFactory.Builder().namingPattern("bot-service-%d").daemon(true).build()
BotMain.service = Executors.newScheduledThreadPool(
4,
BasicThreadFactory.Builder().namingPattern("bot-service-%d").daemon(true).build()
)

/** 服务 */
/** 定时任务 */
BackupHelper.scheduleBackup()
TaskManager.runScheduleTaskAsync(
{ BotConstants.users.forEach { it.addTime(100) } },
5,
5,
TimeUnit.HOURS)
{ BotConstants.users.forEach { it.addTime(100) } },
5,
5,
TimeUnit.HOURS)
TaskManager.runScheduleTaskAsyncIf(
CheckLiveStatus::run,
BotConstants.cfg.checkDelay,
BotConstants.cfg.checkDelay,
TimeUnit.MINUTES,
BotConstants.cfg.subList.isNotEmpty()
CheckLiveStatus::run,
BotConstants.cfg.checkDelay,
BotConstants.cfg.checkDelay,
TimeUnit.MINUTES,
BotConstants.cfg.subList.isNotEmpty()
)
TaskManager.runAsync({
BotMain.client.runCatching {
val pwd = BotConstants.cfg.biliPassword
val uname = BotConstants.cfg.biliUserName
val username = BotConstants.cfg.biliUserName

if (pwd != null && uname != null) {
if (pwd != null && username != null) {
runBlocking {
withContext(Dispatchers.IO) {
login(username = uname, password = pwd)
login(username = username, password = pwd)
}
}
}
Expand All @@ -203,26 +213,26 @@ suspend fun main() {
}, 5)
TaskManager.runScheduleTaskAsync({ apis.forEach { it.resetTime() } }, 25, 25, TimeUnit.MINUTES)
TaskManager.runScheduleTaskAsyncIf(
LatestTweetChecker::run,
1,
15,
TimeUnit.MINUTES,
(BotConstants.cfg.twitterSubs.isNotEmpty() && BotConstants.cfg.tweetPushGroups.isNotEmpty())
LatestTweetChecker::run,
1,
8,
TimeUnit.MINUTES,
(BotConstants.cfg.twitterSubs.isNotEmpty() && BotConstants.cfg.tweetPushGroups.isNotEmpty())
)

/** 监听器 */
listeners.forEach {
it.register(BotMain.bot)
it.register(bot)
BotMain.logger.info("[监听器] 已注册 ${it.getName()} 监听器")
}

val time = System.currentTimeMillis() - BotMain.startTime
val startUsedTime =
if (time > 1000) {
String.format("%.2f", (time.toDouble() / 1000)) + "s"
} else {
(time.toString() + "ms")
}
if (time > 1000) {
String.format("%.2f", (time.toDouble() / 1000)) + "s"
} else {
(time.toString() + "ms")
}

BotMain.logger.info("无名 Bot 启动成功, 耗时 $startUsedTime")

Expand All @@ -233,7 +243,7 @@ suspend fun main() {
BotMain.rCon?.disconnect()
})

BotMain.bot.subscribeMessages {
bot.subscribeMessages {
always {
if (sender.id != 80000000L) {
val result = CommandExecutor.execute(this)
Expand All @@ -246,7 +256,7 @@ suspend fun main() {

BotMain.executeCommand()

BotMain.bot.join() // 等待 Bot 离线, 避免主线程退出
bot.join() // 等待 Bot 离线, 避免主线程退出
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import io.github.starwishsama.nbot.exceptions.RateLimitException
import io.github.starwishsama.nbot.objects.WrappedMessage
import io.github.starwishsama.nbot.objects.pojo.bilibili.dynamic.DynamicTypeSelector
import io.github.starwishsama.nbot.objects.pojo.bilibili.dynamic.dynamicdata.UnknownType
import java.time.LocalDateTime

/**
* BiliBili 动态 API
*
* 获取用户的最新动态
* 支持多种格式
* @author Nameless
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import io.github.starwishsama.nbot.BotMain
import io.github.starwishsama.nbot.api.ApiExecutor
import io.github.starwishsama.nbot.exceptions.EmptyTweetException
import io.github.starwishsama.nbot.exceptions.RateLimitException
import io.github.starwishsama.nbot.exceptions.TwitterApiException
import io.github.starwishsama.nbot.objects.pojo.twitter.Tweet
import io.github.starwishsama.nbot.objects.pojo.twitter.TwitterErrorInfo
import io.github.starwishsama.nbot.objects.pojo.twitter.TwitterUser
Expand All @@ -24,6 +25,7 @@ import java.time.LocalDateTime

/**
* Twitter API
*
* 支持获取蓝鸟用户信息 & 最新推文
* @author Nameless
*/
Expand All @@ -35,7 +37,7 @@ object TwitterApi : ApiExecutor {
private const val tokenGetApi = "https://api.twitter.com/oauth2/token"

// Bearer Token
var token: String = BotConstants.cache["token"].asString
var token: String? = BotConstants.cache["token"].asString

// Token 获取时间, 时间过长需要重新获取, Token 可能会到期
var tokenGetTime = BotConstants.cache["get_time"].asLong
Expand Down Expand Up @@ -67,7 +69,7 @@ object TwitterApi : ApiExecutor {
}
}

@Throws(RateLimitException::class)
@Throws(RateLimitException::class, TwitterApiException::class)
fun getUserInfo(username: String): TwitterUser? {
if (isReachLimit()) {
throw RateLimitException()
Expand All @@ -81,22 +83,39 @@ object TwitterApi : ApiExecutor {
.timeout(12_000)

if (BotConstants.cfg.proxyUrl != null && BotConstants.cfg.proxyPort != 0) {
conn.setProxy(Proxy(Proxy.Type.HTTP, Socket(BotConstants.cfg.proxyUrl, BotConstants.cfg.proxyPort).remoteSocketAddress))
conn.setProxy(
Proxy(
Proxy.Type.HTTP,
Socket(BotConstants.cfg.proxyUrl, BotConstants.cfg.proxyPort).remoteSocketAddress
)
)
}

var result : HttpResponse? = null
var result: HttpResponse? = null
try {
result = conn.executeAsync()
} catch (e: HttpException) {
BotMain.logger.error("[蓝鸟] 在获取用户最新推文时出现了问题", e)
}

val entity = gson.fromJson(result?.body(), TwitterUser::class.java)
var entity: TwitterUser? = null

try {
entity = gson.fromJson(result?.body(), TwitterUser::class.java)
} catch (e: JsonSyntaxException) {
try {
val errorInfo = gson.fromJson(result?.body(), TwitterErrorInfo::class.java)
BotMain.logger.error("[蓝鸟] 调用 API 时出现了问题\n${errorInfo.getReason()}")
throw TwitterApiException(errorInfo.errors[0].code, errorInfo.errors[0].reason)
} catch (e: JsonSyntaxException) {
BotMain.logger.error("[蓝鸟] 解析推文 JSON 时出现问题: 不支持的类型", e)
}
}
BotMain.logger.debug("[蓝鸟] 查询用户信息耗时 ${Duration.between(startTime, LocalDateTime.now()).toMillis()}ms")
return entity
}

@Throws(RateLimitException::class, EmptyTweetException::class)
@Throws(RateLimitException::class, EmptyTweetException::class, TwitterApiException::class)
fun getLatestTweet(username: String): Tweet? {
if (isReachLimit()) {
throw RateLimitException("已达到API调用上限")
Expand Down Expand Up @@ -135,6 +154,7 @@ object TwitterApi : ApiExecutor {
try {
val errorInfo = gson.fromJson(result.body(), TwitterErrorInfo::class.java)
BotMain.logger.error("[蓝鸟] 调用 API 时出现了问题\n${errorInfo.getReason()}")
throw TwitterApiException(errorInfo.errors[0].code, errorInfo.errors[0].reason)
} catch (e: JsonSyntaxException) {
BotMain.logger.error("[蓝鸟] 解析推文 JSON 时出现问题: 不支持的类型", e)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import net.mamoe.mirai.message.data.*
import java.util.*

/**
* Mirai 命令处理器
* 无名 Bot 命令处理器
* 处理群聊/私聊聊天信息中存在的命令
* @author Nameless
*/
Expand Down Expand Up @@ -88,9 +88,7 @@ object CommandExecutor {
}

private fun isCommandPrefix(message: String): Boolean {
return BotConstants.cfg.commandPrefix.contains(
message.substring(0, 1)
) && message.isNotEmpty()
return message.isNotEmpty() && BotConstants.cfg.commandPrefix.contains(message.substring(0, 1))
}

private fun commandEquals(cmd: UniversalCommand, cmdName: String): Boolean {
Expand Down
Loading

0 comments on commit ee51ebe

Please sign in to comment.