-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
166 lines (138 loc) · 5.6 KB
/
main.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""Matrix Bot to play some Wordle in chat"""
import os
import string
import simplematrixbotlib as botlib
import wordle as w
import state as s
if __name__ == '__main__':
creds = botlib.Creds(
homeserver=os.environ.get('HOMESERVER'),
username=os.environ.get('USERNAME'),
password=os.environ.get('PASSWORD'),
access_token=os.environ.get('ACCESS_TOKEN')
)
bot = botlib.Bot(creds)
prefix = os.environ.get('PREFIX', 'w!')
wordle = w.Wordle()
try:
s.load_state()
except FileNotFoundError:
s.save_state({})
def bot_msg_match(room, message):
"""Wrapper function to reduce repetition"""
return botlib.MessageMatch(room, message, bot, prefix)
@bot.listener.on_message_event
async def help_message(room, message):
"""Display help message to user"""
match = bot_msg_match(room, message)
if not valid_command("help", match):
return
response = ("## matrix-wordle\n"
"An implementation of the popular Wordle game for the Matrix Protocol.\n"
"Commands:\n"
"help, h - Display help message\n"
"start, s - Start a new Wordle\n"
"answer, a - Reveal the answer")
await bot.api.send_markdown_message(room.room_id, response)
@bot.listener.on_message_event
@s.ensure_state
async def start_game(room, message, state):
"""Initialize the state and game for requesting user"""
match = bot_msg_match(room, message)
if not valid_command("start", match):
return
user = message.sender
state[user] = {
"guesses": 0,
"guessed_letters": [],
"letters_remaining": list(string.ascii_uppercase)
}
response = ("Starting new Wordle game!\n"\
f"Guess a 5 letter word with \"{prefix}guess\"\n"\
"6 guesses remaining."
)
wordle.get_daily()
await bot.api.send_markdown_message(room.room_id, response)
s.save_state(state)
@bot.listener.on_message_event
@s.ensure_state
async def guess_word(room, message, state):
"""Check the word guessed by user"""
match = bot_msg_match(room, message)
if not valid_command("guess", match):
return
user = message.sender
# Game not started yet
if user not in state.keys():
response = f"Please start a new Wordle game with \"{prefix}start\" before guessing!"
await bot.api.send_text_message(room.room_id, response)
return
# Invalid guess
if len(match.args()) != 1 or len(match.args()[0]) != 5:
response = ("Invalid guess, please provide a valid 5 letter word: "
f"\"{prefix}guess <word>\"."
)
await bot.api.send_text_message(room.room_id, response)
return
# Build bot's response
result = wordle.check_guess(match.args()[0])
response = (f"{' '.join(x for x in match.args()[0])}\n"
f"{''.join(x for x in result['space'])}"
)
# Unknown word
if not wordle.known(match.args()[0]):
response = f"Unknown word: \"{match.args()[0]}\"; please try again."
await bot.api.send_text_message(room.room_id, response)
return
# Out of guesses
if state[user]['guesses'] > 5:
response = f"Out of guesses!\n The answer may be revealed with \"{prefix}answer\"."
await bot.api.send_markdown_message(room.room_id, response)
state.pop(user)
s.save_state(state)
return
# Answer guessed correctly
if result['space'] == list(wordle.GREEN*5):
response = (f"{response}\n"
f"The answer was {wordle.get_daily()}. "
f"You Won in {state[user]['guesses']+1} guesses!"
)
await bot.api.send_text_message(room.room_id, response)
state.pop(user)
s.save_state(state)
return
# Mid-game
state[user]['guesses'] += 1
for letter in result['valid']:
if letter not in state[user]['guessed_letters']:
state[user]['guessed_letters'].append(letter)
state[user]['guessed_letters'] = sorted(state[user]['guessed_letters'])
if letter in state[user]['letters_remaining']:
state[user]['letters_remaining'].remove(letter)
for letter in result['invalid']:
if letter in state[user]['letters_remaining']:
state[user]['letters_remaining'].remove(letter)
s.save_state(state)
response = (f"{response}\n"
f"{6 - state[user]['guesses']} guesses remaining.\n"
f"discovered: {''.join(state[user]['guessed_letters'])}\n"
f"remaining: {''.join(state[user]['letters_remaining'])}"
)
await bot.api.send_text_message(room.room_id, response)
@bot.listener.on_message_event
async def reveal_answer(room, message):
"""Reveal the answer to today's puzzle"""
match = bot_msg_match(room, message)
if not valid_command("answer", match):
return
response = f"The answer is {wordle.get_daily()}."
await bot.api.send_text_message(room.room_id, response)
def valid_command(cmd, match) -> bool:
"""Check if the bot command is expected"""
if not match.prefix():
return False
cmd_start = cmd[0]
if match.command(cmd) or match.command(cmd_start):
return True
return False
bot.run()