ctucx.git: ctucxbot

[nimlang] A telegram bot

commit 285c0c98719d6d9a005ba4ef711df1908e577289
parent 7a2396292ef87bf5f8ad2d3d25c6f85f0a89b12d
Author: ctucx <c@ctu.cx>
Date: Fri, 17 Jan 2020 11:18:58 +0100

use envVar 'API_KEY' instead of secret.key file, handle ctrl+c correctly
1 file changed, 26 insertions(+), 18 deletions(-)
M
src/ctucxbot.nim
|
44
++++++++++++++++++++++++++------------------
diff --git a/src/ctucxbot.nim b/src/ctucxbot.nim
@@ -1,7 +1,8 @@
 import asyncdispatch, telebot, options, strutils, random, os, re, unicode
 include cmd/[animalpics, daysuntilcongress, help, stats, unixtime, utc, uptime, yesorno, whoami]
 
-const API_KEY = slurp("secret.key")
+proc ctrlcHandler() {.noconv.} =
+  quit()
 
 proc updateHandler(bot: Telebot, update: Update) {.async.} =
   if not update.message.isNone:

@@ -52,21 +53,28 @@ proc updateHandler(bot: Telebot, update: Update) {.async.} =
         response.replyToMessageId = message.messageId
         discard await bot.send(response)
 
-let bot = newTeleBot(API_KEY)
 
-bot.onUpdate(updateHandler)
-bot.onCommand("daysuntilcongress", daysUntilCongressCommand)
-bot.onCommand("fox", animalCommand(fox, false))
-#bot.onCommand("penguin", animalCommand(penguin, false))  # pingudor.de is offline
-bot.onCommand("dog", animalCommand(dog, false))
-bot.onCommand("doggo", animalCommand(dog, false))
-bot.onCommand("cat", animalCommand(cat, false))
-bot.onCommand("catgif", animalCommand(cat, true))
-bot.onCommand("help", helpCommand)
-bot.onCommand("stats", statsCommand)
-bot.onCommand("unixtime", unixtimeCommand)
-bot.onCommand("utc", utcCommand)
-bot.onCommand("uptime", uptimeCommand)
-bot.onCommand("yesorno", yesornoCommand)
-bot.onCommand("whoami", whoamiCommand)
-bot.poll(timeout=300)
+setControlCHook(ctrlcHandler)
+
+if getEnv("API_KEY") != "":
+  let bot = newTeleBot(getEnv("API_KEY"))
+
+  bot.onUpdate(updateHandler)
+  bot.onCommand("daysuntilcongress", daysUntilCongressCommand)
+  bot.onCommand("fox", animalCommand(fox, false))
+  #bot.onCommand("penguin", animalCommand(penguin, false))  # pingudor.de is offline
+  bot.onCommand("dog", animalCommand(dog, false))
+  bot.onCommand("doggo", animalCommand(dog, false))
+  bot.onCommand("cat", animalCommand(cat, false))
+  bot.onCommand("catgif", animalCommand(cat, true))
+  bot.onCommand("help", helpCommand)
+  bot.onCommand("stats", statsCommand)
+  bot.onCommand("unixtime", unixtimeCommand)
+  bot.onCommand("utc", utcCommand)
+  bot.onCommand("uptime", uptimeCommand)
+  bot.onCommand("yesorno", yesornoCommand)
+  bot.onCommand("whoami", whoamiCommand)
+  bot.poll(timeout=300)
+
+else:
+  echo "No API_KEY given!"