Kaynağa Gözat

added single city command to bot

Vadik Sirekanyan 5 yıl önce
ebeveyn
işleme
13fc61a3e1

+ 18 - 1
src/main/kotlin/com/sirekanyan/andersrobot/AndersRobot.kt

@@ -4,6 +4,8 @@ import com.sirekanyan.andersrobot.api.WeatherApi
 import com.sirekanyan.andersrobot.config.Config
 import com.sirekanyan.andersrobot.config.ConfigKey.BOT_TOKEN
 import com.sirekanyan.andersrobot.config.ConfigKey.BOT_USERNAME
+import com.sirekanyan.andersrobot.extensions.getCityCommand
+import com.sirekanyan.andersrobot.extensions.isCelsiusCommand
 import com.sirekanyan.andersrobot.extensions.isWeatherCommand
 import com.sirekanyan.andersrobot.extensions.sendText
 import org.telegram.telegrambots.bots.DefaultAbsSender
@@ -25,9 +27,24 @@ class AndersRobot : DefaultAbsSender(DefaultBotOptions()), LongPollingBot {
     override fun onUpdateReceived(update: Update) {
         val message = update.message
         val chatId = message.chatId
+        println("${message.from?.id} => ${message.text}")
+        val isBetterAccuracy = message.chatId == 314085103L || message.chatId == 106547051L
+        val accuracy = if (isBetterAccuracy) 1 else 0
+        val cityCommand = getCityCommand(message.text)
         when {
+            !cityCommand.isNullOrEmpty() -> {
+                val temperature = weather.getTemperature(cityCommand, accuracy)
+                if (temperature == null) {
+                    sendText(chatId, "Не знаю такого города")
+                } else {
+                    sendText(chatId, listOf(temperature).joinToString("\n"))
+                }
+            }
+            isCelsiusCommand(message.text) -> {
+                sendText(chatId, "Можешь звать меня просто Андерс")
+            }
             isWeatherCommand(message.text) -> {
-                val temperatures = weather.getTemperatures()
+                val temperatures = weather.getTemperatures(accuracy)
                 if (temperatures.isNotEmpty()) {
                     sendText(chatId, temperatures.joinToString("\n"))
                 }

+ 11 - 1
src/main/kotlin/com/sirekanyan/andersrobot/extensions/String.kt

@@ -4,6 +4,16 @@ import com.sirekanyan.andersrobot.botName
 import kotlin.text.RegexOption.IGNORE_CASE
 
 private val REGEX = Regex("\\b(андерс|anders|погод[аеуы])\\b", IGNORE_CASE)
+private val DEGREE_REGEX = Regex("\\bградус", IGNORE_CASE)
+private val CELSIUS_REGEX = Regex("\\b(Celsi|Цельси)", IGNORE_CASE)
+private val CITY_REGEX = Regex("(/temp|погода) +(.+)", IGNORE_CASE)
 
 fun isWeatherCommand(text: String?): Boolean =
-    text?.contains(REGEX) == true || text == "/temp" || text == "/temp@$botName"
+    text?.contains(REGEX) == true || text?.contains(DEGREE_REGEX) == true ||
+            text == "/temp" || text == "/temp@$botName"
+
+fun isCelsiusCommand(text: String?): Boolean =
+    text?.contains(CELSIUS_REGEX) == true
+
+fun getCityCommand(text: String?): String? =
+    CITY_REGEX.matchEntire(text.orEmpty())?.groupValues?.get(2)