fix: fix weather null pointer tip

This commit is contained in:
2024-09-06 15:28:48 +08:00
parent cbca4323b4
commit 010f9fa466
1 file changed
+27 -19
@@ -28,24 +28,32 @@ class WeatherCommand : BaseCommand() {
listener.sendGroupMessage(message.groupId, msg) listener.sendGroupMessage(message.groupId, msg)
return return
} }
try {
val locationName = args.first() val locationName = args.first()
val lookupLocationId = Http.get<Geo>( val lookupLocation = Http.get<Geo>(
"https://geoapi.qweather.com/v2/city/lookup", "https://geoapi.qweather.com/v2/city/lookup",
mapOf("location" to locationName, "key" to configManager.qweatherKey) mapOf("location" to locationName, "key" to configManager.qweatherKey)
).location.first().id ).location.first()
val weather = Http.get<Weather>( val weather = Http.get<Weather>(
"https://devapi.qweather.com/v7/weather/now", "https://devapi.qweather.com/v7/weather/now",
mapOf("location" to lookupLocationId, "key" to configManager.qweatherKey) mapOf("location" to lookupLocation.id, "key" to configManager.qweatherKey)
) )
val msg = MessageChain.Builder() val msg = MessageChain.Builder()
.addAt(message.sender.userId) .addAt(message.sender.userId)
.addNewLine() .addNewLine()
.addText("城市: $locationName, 温度: ${weather.now.temp}") .addText("城市: ${lookupLocation.name}, 温度: ${weather.now.temp}")
.addNewLine() .addNewLine()
.addText("${weather.now.text}/${weather.now.windDir}") .addText("${weather.now.text}/${weather.now.windDir}")
.addNewLine() .addNewLine()
.addText("数据来源: ${weather.refer.sources.joinToString(",")}") .addText("数据来源: ${weather.refer.sources.joinToString(",")}")
.build() .build()
listener.sendGroupMessage(message.groupId, msg) listener.sendGroupMessage(message.groupId, msg)
} catch (_: NullPointerException) {
val msg = MessageChain.Builder()
.addAt(message.sender.userId)
.addText("没有查询到该城市的天气信息哦~")
.build()
listener.sendGroupMessage(message.groupId, msg)
}
} }
} }