-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
209 lines (151 loc) · 5.65 KB
/
bot.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.
import os
import logging
from typing import Dict
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
TOKEN = os.getenv("TOKEN")
#Start change
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)
reply_keyboard = [
['Monte Carlo', 'Favourite colour'],
['Number of siblings', 'Something else...'],
['Done'],
]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
reply_keyboard2 = [
['Yes', 'No'],
]
markup2 = ReplyKeyboardMarkup(reply_keyboard2, one_time_keyboard=True)
reply_keyboard3 = [
["P1:apple", "P2:banana", "P3:cherry"],
['Finish'],
]
markup3 = ReplyKeyboardMarkup(reply_keyboard3, one_time_keyboard=True)
thislist = ["P1:apple", "P2:banana", "P3:cherry"]
# Function facts_to_str to convert dict to string
def facts_to_str(user_data: Dict[str, str]) -> str:
facts = list()
for key, value in user_data.items():
facts.append(f'{key} - {value}')
return "\n".join(facts).join(['\n', '\n'])
# Initiate conversation
def start(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
"Hi! My name is Doctor Botter"
"Why don't you tell me something about yourself?"
"Choose a simulation that u would like to run",
reply_markup=markup,
)
return CHOOSING
def regular_choice(update: Update, context: CallbackContext) -> int:
text = update.message.text
context.user_data['choice'] = text
update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!', reply_markup=markup3,)
return TYPING_REPLY
def params_choice(update: Update, context: CallbackContext) -> int:
text = update.message.text
context.user_data['choice'] = text
update.message.reply_text(f'Please enter {text.lower()}? no. of trials',reply_markup=markup2,)
return TYPING_CHOICE
def custom_choice(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
'Alright, please send me the category first, ' 'for example "Most impressive skill"', reply_markup=markup3
)
return TYPING_CHOICE
def received_information(update: Update, context: CallbackContext) -> int:
user_data = context.user_data
text = update.message.text
category = user_data['choice']
user_data[category] = text
del user_data['choice']
update.message.reply_text(
"Neat! Just so you know, this is what you already told me:"
f"{facts_to_str(user_data)} You can tell me more, or change your opinion"
" on something.",
reply_markup=markup,
)
return CHOOSING
# Only way to end conversation is by pressing 'done'
# Function 'done' to do that
def done(update: Update, context: CallbackContext) -> int:
user_data = context.user_data
user = update.message.from_user
if 'choice' in user_data:
del user_data['choice']
print(user_data)
print(type(user_data))
update.message.reply_text(
f"Hey {user.first_name}, I learned these facts about you: {facts_to_str(user_data)} \nThe next time U wish to talk to me, just send\n /start to me 😊"
)
user_data.clear()
return ConversationHandler.END
#End change
def run(updater):
PORT = int(os.environ.get("PORT", "8443"))
HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME")
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, TOKEN))
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main() -> None:
# Create the Updater and pass it your bot's token.
updater = Updater(TOKEN)
#Start change
dispatcher = updater.dispatcher
# Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
# Choosing
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
CHOOSING: [
MessageHandler(
Filters.regex('^(Favourite colour|Number of siblings)$'), regular_choice
),
MessageHandler(
Filters.text('^Something else...$'), custom_choice
),
MessageHandler(
Filters.regex('^Monte Carlo$'), params_choice
),
MessageHandler(
Filters.text(thislist) | Filters.regex('^Yes$'), regular_choice
),
],
TYPING_CHOICE: [
MessageHandler(
Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice
),
],
TYPING_REPLY: [
MessageHandler(
Filters.text & ~(Filters.command | Filters.regex('^Done$')),
received_information,
)],
},
fallbacks=[MessageHandler(Filters.regex('^Done$'), done)],
)
dispatcher.add_handler(conv_handler)
#End change
dispatcher.add_error_handler(error)
run(updater)
if __name__ == '__main__':
main()