This repository has been archived by the owner on Apr 12, 2021. It is now read-only.
forked from nickoala/telepot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguessa.py
75 lines (59 loc) · 2.09 KB
/
guessa.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import sys
import asyncio
import random
import telepot
from telepot.delegate import per_chat_id
from telepot.async.delegate import create_open
"""
$ python3.4 guessa.py <token>
Guess a number:
1. Send the bot anything to start a game.
2. The bot randomly picks an integer between 0-99.
3. You make a guess.
4. The bot tells you to go higher or lower.
5. Repeat step 3 and 4, until guess is correct.
"""
class Player(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(Player, self).__init__(seed_tuple, timeout)
self._answer = random.randint(0,99)
def _hint(self, answer, guess):
if answer > guess:
return 'larger'
else:
return 'smaller'
@asyncio.coroutine
def open(self, initial_msg, seed):
yield from self.sender.sendMessage('Guess my number')
return True # prevent on_message() from being called on the initial message
@asyncio.coroutine
def on_message(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type != 'text':
yield from self.sender.sendMessage('Give me a number, please.')
return
try:
guess = int(msg['text'])
except ValueError:
yield from self.sender.sendMessage('Give me a number, please.')
return
# check the guess against the answer ...
if guess != self._answer:
# give a descriptive hint
hint = self._hint(self._answer, guess)
yield from self.sender.sendMessage(hint)
else:
yield from self.sender.sendMessage('Correct!')
self.close()
@asyncio.coroutine
def on_close(self, exception):
if isinstance(exception, telepot.helper.WaitTooLong):
yield from self.sender.sendMessage('Game expired. The answer is %d' % self._answer)
TOKEN = sys.argv[1]
bot = telepot.async.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(Player, timeout=10)),
])
loop = asyncio.get_event_loop()
loop.create_task(bot.messageLoop())
print('Listening ...')
loop.run_forever()