Commit c63f54bc authored by Him188's avatar Him188

Fix bugs

parent 4e27ad32
...@@ -54,7 +54,10 @@ suspend fun InputStream.sendAsImageTo(contact: Contact) = withContext(Dispatcher ...@@ -54,7 +54,10 @@ suspend fun InputStream.sendAsImageTo(contact: Contact) = withContext(Dispatcher
* @throws OverFileSizeMaxException * @throws OverFileSizeMaxException
*/ */
@Throws(OverFileSizeMaxException::class) @Throws(OverFileSizeMaxException::class)
suspend fun File.sendAsImageTo(contact: Contact) = withContext(Dispatchers.IO) { toExternalImage() }.sendTo(contact) suspend fun File.sendAsImageTo(contact: Contact) {
require(this.exists() && this.canRead())
withContext(Dispatchers.IO) { toExternalImage() }.sendTo(contact)
}
// endregion // endregion
...@@ -93,7 +96,10 @@ suspend fun InputStream.upload(contact: Contact): Image = withContext(Dispatcher ...@@ -93,7 +96,10 @@ suspend fun InputStream.upload(contact: Contact): Image = withContext(Dispatcher
* @throws OverFileSizeMaxException * @throws OverFileSizeMaxException
*/ */
@Throws(OverFileSizeMaxException::class) @Throws(OverFileSizeMaxException::class)
suspend fun File.upload(contact: Contact): Image = withContext(Dispatchers.IO) { toExternalImage() }.upload(contact) suspend fun File.upload(contact: Contact): Image {
require(this.exists() && this.canRead())
return withContext(Dispatchers.IO) { toExternalImage() }.upload(contact)
}
// endregion // endregion
......
...@@ -49,8 +49,10 @@ fun BufferedImage.toExternalImage(formatName: String = "gif"): ExternalImage { ...@@ -49,8 +49,10 @@ fun BufferedImage.toExternalImage(formatName: String = "gif"): ExternalImage {
*/ */
@Throws(IOException::class) @Throws(IOException::class)
fun File.toExternalImage(): ExternalImage { fun File.toExternalImage(): ExternalImage {
println(this.path)
val input = ImageIO.createImageInputStream(this) val input = ImageIO.createImageInputStream(this)
val image = ImageIO.getImageReaders(input).asSequence().firstOrNull() ?: error("Unable to read file(${this.path}), no ImageReader found") checkNotNull(input) { "Unable to read file(path=${this.path}), no ImageInputStream found" }
val image = ImageIO.getImageReaders(input).asSequence().firstOrNull() ?: error("Unable to read file(path=${this.path}), no ImageReader found")
image.input = input image.input = input
return ExternalImage( return ExternalImage(
...@@ -80,6 +82,7 @@ fun URL.toExternalImage(): ExternalImage { ...@@ -80,6 +82,7 @@ fun URL.toExternalImage(): ExternalImage {
fun InputStream.toExternalImage(): ExternalImage { fun InputStream.toExternalImage(): ExternalImage {
val file = createTempFile().apply { deleteOnExit() } val file = createTempFile().apply { deleteOnExit() }
this.transferTo(FileOutputStream(file)) this.transferTo(FileOutputStream(file))
this.close()
return file.toExternalImage() return file.toExternalImage()
} }
......
...@@ -9,7 +9,6 @@ import io.ktor.http.ContentType ...@@ -9,7 +9,6 @@ import io.ktor.http.ContentType
import io.ktor.http.content.OutgoingContent import io.ktor.http.content.OutgoingContent
import kotlinx.coroutines.io.ByteWriteChannel import kotlinx.coroutines.io.ByteWriteChannel
import kotlinx.io.core.Input import kotlinx.io.core.Input
import kotlinx.io.core.readFully
import java.io.DataInput import java.io.DataInput
import java.io.EOFException import java.io.EOFException
import java.io.InputStream import java.io.InputStream
...@@ -70,7 +69,7 @@ actual suspend fun httpPostFriendImageOld( ...@@ -70,7 +69,7 @@ actual suspend fun httpPostFriendImageOld(
"?htcmd=0x6ff0070" + "?htcmd=0x6ff0070" +
"&ver=5603" + "&ver=5603" +
"&ukey=$uKeyHex" + "&ukey=$uKeyHex" +
"&filezise=${imageData.remaining}" + "&filesize=${imageData.remaining}" +
"&range=0" + "&range=0" +
"&uin=$botNumber" "&uin=$botNumber"
) )
...@@ -101,7 +100,6 @@ internal actual fun HttpRequestBuilder.configureBody( ...@@ -101,7 +100,6 @@ internal actual fun HttpRequestBuilder.configureBody(
) { ) {
//body = ByteArrayContent(input.readBytes(), ContentType.Image.PNG) //body = ByteArrayContent(input.readBytes(), ContentType.Image.PNG)
body = object : OutgoingContent.WriteChannelContent() { body = object : OutgoingContent.WriteChannelContent() {
override val contentType: ContentType = ContentType.Image.PNG override val contentType: ContentType = ContentType.Image.PNG
override val contentLength: Long = inputSize override val contentLength: Long = inputSize
...@@ -109,9 +107,10 @@ internal actual fun HttpRequestBuilder.configureBody( ...@@ -109,9 +107,10 @@ internal actual fun HttpRequestBuilder.configureBody(
override suspend fun writeTo(channel: ByteWriteChannel) {//不知道为什么这个 channel 在 common 找不到... override suspend fun writeTo(channel: ByteWriteChannel) {//不知道为什么这个 channel 在 common 找不到...
val buffer = byteArrayOf(1) val buffer = byteArrayOf(1)
repeat(contentLength.toInt()) { repeat(contentLength.toInt()) {
input.readFully(buffer) input.readFully(buffer, 0, 1)
channel.writeFully(buffer, 0, buffer.size) channel.writeFully(buffer, 0, 1)
} }
println("已经发送$contentLength")
} }
} }
} }
\ No newline at end of file
...@@ -61,7 +61,7 @@ suspend fun Bot.messageDSL() { ...@@ -61,7 +61,7 @@ suspend fun Bot.messageDSL() {
this.group.sendMessage("你在一个群里") this.group.sendMessage("你在一个群里")
} }
reply("你发送了一个图片, ID为 ${message[Image].id}, 我要复读了") reply("图片, ID= ${message[Image].id}")
reply(message) reply(message)
} }
...@@ -70,7 +70,7 @@ suspend fun Bot.messageDSL() { ...@@ -70,7 +70,7 @@ suspend fun Bot.messageDSL() {
"我的qq" reply { sender.id.toString() } "我的qq" reply { sender.id.toString() }
sentBy(1040400290) { sentBy(1040400290) {
reply("是你!") //reply("是你!")
} }
contains("复读") { contains("复读") {
......
package demo.gentleman
import kotlinx.coroutines.*
import net.mamoe.mirai.contact.Contact
import net.mamoe.mirai.message.Image
import net.mamoe.mirai.message.upload
import net.mamoe.mirai.utils.MiraiLogger
import org.jsoup.Jsoup
class GentleImage {
lateinit var tags: String
lateinit var sample_url: String
lateinit var author: String
lateinit var file_url: String
var score: Int = 0
var width: Int = 0
var height: Int = 0
//val summary by lazy { "Avatar by ${author}; Origin size ($width*$height);" + "HD URL: $file_url" }
val name: String by lazy {
var name: String
val tags = tags.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (tags.isEmpty()) {
return@lazy "OneTapper"
}
name = tags[(Math.random() * tags.size).toInt()]
name = name.substring(0, 1).toUpperCase() + name.substring(1)
name = name.split("\\(".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
name = name.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
name
}
lateinit var contact: Contact
val image: Deferred<Image> by lazy {
GlobalScope.async {
// runBlocking {
// CompletableDeferred(suspend {
delay((Math.random() * 5000L).toLong())
MiraiLogger.logPurple("Downloading image: $name")
withContext(Dispatchers.IO) {
Jsoup.connect(sample_url)
.userAgent(UserAgent.randomUserAgent)
.timeout(20_0000)
.ignoreContentType(true)
.maxBodySize(Int.MAX_VALUE)
.execute()
.bodyStream()
}.upload(contact).also {
MiraiLogger.logPurple("Downloaded image: $name")
}
// }())
// }
}
}
}
package demo.gentleman
import com.alibaba.fastjson.JSONArray
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import net.mamoe.mirai.contact.Contact
import org.jsoup.Connection
import org.jsoup.Jsoup
/**
* 最少缓存的图片数量
*/
private const val IMAGE_BUFFER_CAPACITY: Int = 5
/**
* 每次补充的数量
*/
private const val FILL_COUNT: Int = IMAGE_BUFFER_CAPACITY
@ExperimentalUnsignedTypes
@ExperimentalCoroutinesApi
object Gentlemen : MutableMap<UInt, Gentleman> by mutableMapOf() {
fun getOrPut(key: Contact): Gentleman = this.getOrPut(key.id) { Gentleman(key) }
}
@ExperimentalCoroutinesApi
class Gentleman(private val contact: Contact) : Channel<GentleImage> by Channel(IMAGE_BUFFER_CAPACITY) {
init {
GlobalScope.launch {
while (!isClosedForSend) {
val response = withContext(Dispatchers.IO) {
tryNTimes(2) {
Jsoup.connect("https://yande.re/post.json?")
.userAgent(UserAgent.randomUserAgent)
.data("limit", "20")
.data("page", (Math.random() * 4000).toString())
.ignoreContentType(true)
.timeout(20_000)
.method(Connection.Method.GET)
.execute()
}
}
check(response.statusCode() == 200) { "failed to get resources" }
JSONArray.parseArray(response.body(), GentleImage::class.java)
.filterNot { it.tags in ForbiddenKeyWords }
.sortedBy { it.score }
.let {
if (it.size <= FILL_COUNT) {
it
} else it.slice(0..FILL_COUNT)
}
.forEach {
it.contact = contact
it.image//start downloading
send(it)
}
}
}
}
}
object ForbiddenKeyWords : List<String> by listOf(
"miku",
"vocaloid",
"kuriyama",
"mirai"
) {
override fun contains(element: String): Boolean {
return this.stream().anyMatch { element.contains(it, ignoreCase = true) }
}
}
\ No newline at end of file
...@@ -6,6 +6,9 @@ import net.mamoe.mirai.Bot ...@@ -6,6 +6,9 @@ import net.mamoe.mirai.Bot
import net.mamoe.mirai.BotAccount import net.mamoe.mirai.BotAccount
import net.mamoe.mirai.event.subscribeMessages import net.mamoe.mirai.event.subscribeMessages
import net.mamoe.mirai.login import net.mamoe.mirai.login
import net.mamoe.mirai.message.Image
import net.mamoe.mirai.message.ImageId
import net.mamoe.mirai.message.sendAsImageTo
import net.mamoe.mirai.network.protocol.tim.packet.login.requireSuccess import net.mamoe.mirai.network.protocol.tim.packet.login.requireSuccess
import java.io.File import java.io.File
...@@ -18,7 +21,7 @@ private fun readTestAccount(): BotAccount? { ...@@ -18,7 +21,7 @@ private fun readTestAccount(): BotAccount? {
val lines = file.readLines() val lines = file.readLines()
return try { return try {
BotAccount(lines[0].toUInt(), lines[1]) BotAccount(lines[0].toUInt(), lines[1])
} catch (e: IndexOutOfBoundsException) { } catch (e: Exception) {
null null
} }
} }
...@@ -26,19 +29,35 @@ private fun readTestAccount(): BotAccount? { ...@@ -26,19 +29,35 @@ private fun readTestAccount(): BotAccount? {
@Suppress("UNUSED_VARIABLE") @Suppress("UNUSED_VARIABLE")
suspend fun main() { suspend fun main() {
val bot = Bot( val bot = Bot(
//readTestAccount() ?: BotAccount( readTestAccount() ?: BotAccount(
qq = 1994701121u, id = 1994701121u,
password = "123456" password = "123456"
// ) )
) ).apply { login().requireSuccess() }
val bot2 = Bot(1994701121u, "").apply { login().requireSuccess() } bot.subscribeMessages {
"你好" reply "你好!"
bot.login().requireSuccess() startsWith("发送图片", removePrefix = true) {
reply(Image(ImageId(it)))
}
bot.subscribeMessages { startsWith("上传图片", removePrefix = true) {
contains("") { File("C:/Users/Him18/Desktop/$it").sendAsImageTo(subject)
}
case("随机色图") {
reply("Downloading started")
val received = Gentlemen.getOrPut(subject).receive()
reply("Received Image")
received.image.await().send()
reply("Thanks for using")
}
"色图" caseReply {
""
} }
} }
......
package demo.gentleman
import kotlin.reflect.KClass
@Throws(TryFailedException::class)
inline fun <T> tryNTimes(
tryTimes: Int,
vararg expectingExceptions: KClass<out Exception> = Array<KClass<out Exception>>(1) { Exception::class },
expectingHandler: (Exception) -> Unit = { },
unexpectingHandler: (Exception) -> Unit = { throw it },
block: () -> T
): T {
require(tryTimes > 0) { "tryTimes must be greater than 0" }
var lastE: java.lang.Exception? = null
repeat(tryTimes) {
try {
return block()
} catch (e: Exception) {
if (lastE != null && lastE !== e) {
e.addSuppressed(lastE)
}
lastE = e
if (expectingExceptions.any { it.isInstance(e) }) {
expectingHandler(e)
} else {
unexpectingHandler(e)
}
}
}
if (lastE != null) {
throw TryFailedException(lastE!!)
}
throw TryFailedException()
}
class TryFailedException : RuntimeException {
constructor() : super()
constructor(e: Exception) : super(e)
}
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment