Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions src/main/kotlin/org/hydev/back/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.github.kotlintelegrambot.bot
import com.github.kotlintelegrambot.dispatch
import com.github.kotlintelegrambot.dispatcher.Dispatcher
import com.github.kotlintelegrambot.dispatcher.callbackQuery
import com.github.kotlintelegrambot.entities.BotCommand
import com.github.kotlintelegrambot.entities.ChatId
import com.github.kotlintelegrambot.logging.LogLevel
import kotlinx.coroutines.DelicateCoroutinesApi
Expand All @@ -24,6 +25,31 @@ val secrets = getSecrets()
lateinit var bot: Bot
private val COMMENT_ID_REGEX = Regex("^#(\\d+)\\b")

private data class CommandSpec(
val name: String,
val menuDescription: String,
val usage: String,
val detail: String
)

private val COMMAND_SPECS = listOf(
CommandSpec("start", "Check if bot is alive", "/start", "检查机器人在线状态"),
CommandSpec("help", "Show admin commands", "/help", "显示完整命令帮助"),
CommandSpec("ban", "Ban an IP address", "/ban <ip> [reason]", "封禁 IP,可附带原因"),
CommandSpec("unban", "Unban an IP address", "/unban <ip>", "解除 IP 封禁"),
CommandSpec("listban", "List all banned IPs", "/listban", "列出当前所有封禁 IP"),
CommandSpec("note", "Add note to a pending comment", "/note <note>", "回复待审评论消息后添加备注(内容为 clear 可清空)")
)

private val TELEGRAM_COMMANDS = COMMAND_SPECS.map { BotCommand(it.name, it.menuDescription) }

private val HELP_TEXT = buildString {
appendLine("可用命令:")
COMMAND_SPECS.forEach { spec ->
appendLine("${spec.usage} - ${spec.detail}")
}
}

/**
* Command that can only be used in the telegram chats specified in the secrets
*/
Expand Down Expand Up @@ -56,12 +82,7 @@ class PostConstruct(
token = secrets.telegramBotToken
dispatch {
cmd("start") { "🐈 Running!" }
secureCmd("help") { """
/ban <ip> [reason]
/unban <ip>
/listban
/note <note>""".trimIndent()
}
secureCmd("help") { HELP_TEXT }
secureCmd("ban") {
val args = (message.text ?: "").split(" ").slice(1)
if (args.isEmpty()) return@secureCmd "Usage: /ban <ip> [reason]"
Expand Down Expand Up @@ -99,6 +120,10 @@ class PostConstruct(
}
}
bot.sendMessage(ChatId.fromId(secrets.telegramChatID), getMorningMsg() + "\n\n(服务器已起床)")
bot.setMyCommands(TELEGRAM_COMMANDS).fold(
{ println("[Telegram] Command list synced (${TELEGRAM_COMMANDS.size} commands)") },
{ println("[Telegram] Failed to sync command list: $it") }
)
GlobalScope.launch {
println(geoIP.info("127.0.0.1"))
}
Expand Down
48 changes: 41 additions & 7 deletions src/main/kotlin/org/hydev/back/controller/EditController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,29 @@ import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.github.kotlintelegrambot.entities.ChatId
import org.hydev.back.*
import org.hydev.back.ai.HarmLevel
import org.hydev.back.ai.IHarmClassifier
import org.hydev.back.db.BanRepo
import org.hydev.back.geoip.AcceptLanguage
import org.hydev.back.geoip.GeoIP
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest


@RestController
@RequestMapping("/edit")
@CrossOrigin(origins = ["*"])
class EditController
class EditController(
private val banRepo: BanRepo,
private val geoIP: GeoIP,
private val harmClassifier: IHarmClassifier
)
{
@PostMapping("/info")
fun get(@P id: str, @P content: str, @P captcha: str, @P name: str, @P email: str,
suspend fun get(@P id: str, @P content: str, @P captcha: str, @P name: str, @P email: str,
request: HttpServletRequest): Any
{
val ip = request.getIP()
Expand All @@ -29,6 +39,8 @@ class EditController
> Name: $name
> Email: $email
> Content: $content
> Accept-Language: ${request.getHeader("accept-language")}
> User-Agent: ${request.getHeader("user-agent")}
<< EOF >>""")

// Verify captcha
Expand All @@ -47,18 +59,40 @@ class EditController
val obj = ObjectMapper().readTree(content)
val yml = ObjectMapper(YAMLFactory()).writeValueAsString(obj)

val notif = """
var notif = """
$id 收到了信息编辑请求:

$yml

- IP: $ip
- 姓名: $name
- 邮箱: $email"""
- IP: $ip"""

if (name != "Anonymous")
notif += "\n- 姓名: $name"
if (email != "anonymous@example.com")
notif += "\n- 邮箱: $email"
geoIP.info(ip)?.let { notif += "\n$it" }

// Check if ip is banned. If it is, send it to the blocked chat instead.
val ban = banRepo.queryByIp(ip)
val chatId = if (ban != null) {
notif += "\n- ❌ IP 已被封禁!"
secrets.telegramBlockedChatID
}
else {
// Check if AI think it's inappropriate
val clas = harmClassifier.classify(content)
clas?.msg?.let { notif += "\n- $it" }

if (clas == HarmLevel.HARMFUL) secrets.telegramBlockedChatID
else secrets.telegramChatID
}
Comment thread
Misaka13514 marked this conversation as resolved.

request.getHeader("accept-language")?.let { notif += "\n- 请求语言: ${AcceptLanguage.parse(it)}" }
request.getHeader("user-agent")?.let { notif += "\n- 浏览器: $it" }
Comment thread
Misaka13514 marked this conversation as resolved.

return try
{
bot.sendMessage(ChatId.fromId(secrets.telegramChatID), notif, disableWebPagePreview = true)
bot.sendMessage(ChatId.fromId(chatId), notif, disableWebPagePreview = true)

// This fails for some reason:
// createPullRequest(name, email,
Expand Down
Loading