aboutsummaryrefslogtreecommitdiff
path: root/example/guess.scm
diff options
context:
space:
mode:
authorAdrian Kummerlaender2016-03-15 19:10:06 +0100
committerAdrian Kummerlaender2016-03-15 19:10:06 +0100
commita6dbf20faf95ae892a805b8e83c131a4733f564f (patch)
tree94f2e6c16b4ea6d6a98a725a4a30b1226849d277 /example/guess.scm
parent040875369c2ef0d10a8a0d68852ebea1b146ac85 (diff)
downloadTelebot-a6dbf20faf95ae892a805b8e83c131a4733f564f.tar
Telebot-a6dbf20faf95ae892a805b8e83c131a4733f564f.tar.gz
Telebot-a6dbf20faf95ae892a805b8e83c131a4733f564f.tar.bz2
Telebot-a6dbf20faf95ae892a805b8e83c131a4733f564f.tar.lz
Telebot-a6dbf20faf95ae892a805b8e83c131a4733f564f.tar.xz
Telebot-a6dbf20faf95ae892a805b8e83c131a4733f564f.tar.zst
Telebot-a6dbf20faf95ae892a805b8e83c131a4733f564f.zip
Implement simple number guessing game example
Diffstat (limited to 'example/guess.scm')
-rw-r--r--example/guess.scm59
1 files changed, 59 insertions, 0 deletions
diff --git a/example/guess.scm b/example/guess.scm
new file mode 100644
index 0000000..c3267ff
--- /dev/null
+++ b/example/guess.scm
@@ -0,0 +1,59 @@
+(require-extension telebot
+ (prefix telebot telebot:))
+
+(use srfi-69)
+(use extras)
+(use data-structures)
+
+(define (resolve-query query tree)
+ (fold (lambda (x y) (alist-ref x y))
+ tree
+ query))
+
+(define token (car (command-line-arguments)))
+(define conversations (make-hash-table))
+
+(define (send chat_id text)
+ (telebot:sendMessage token
+ chat_id: chat_id
+ text: text))
+
+(define (print-failed-guess chat_id answer guess)
+ (print "User " chat_id " guessed " guess " instead of " answer))
+
+(define (make-conversation chat_id)
+ (let ((chat_id chat_id)
+ (answer (random 100)))
+ (lambda (text)
+ (let ((guess (string->number text)))
+ (if (equal? #f guess)
+ (send chat_id
+ "This is not a number - please provide your guess in base 10.")
+ (cond ((= guess answer)
+ (begin (send chat_id
+ "Correct! Feel free to guess the next number.")
+ (print "User " chat_id " correctly guessed " answer)
+ (set! answer (random 100))))
+ ((< guess answer)
+ (begin (send chat_id
+ "Too small. Try again.")
+ (print-failed-guess chat_id answer guess)))
+ ((> guess answer)
+ (begin (send chat_id
+ "Too large. Try again.")
+ (print-failed-guess chat_id answer guess)))))))))
+
+(define (handle-message m)
+ (let ((chat_id (resolve-query '(message from id) m))
+ (text (resolve-query '(message text) m)))
+ (if (hash-table-exists? conversations chat_id)
+ ((hash-table-ref conversations chat_id) text)
+ (begin (hash-table-set! conversations chat_id (make-conversation chat_id))
+ (print "Started talking to user " chat_id)
+ (send chat_id
+ "Hi there! I just generated a random number for you to guess!")))))
+
+(randomize)
+(telebot:pollUpdates token
+ (lambda (u) (if (telebot:is-message? u)
+ (handle-message u))))