-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
159 lines (130 loc) · 7.32 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
# -*- coding: utf-8 -*-
import os
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
# app specific imports
import pandas as pd
import random
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# Get environment variables
telegram_token = str(os.environ.get('TELEGRAM_TOKEN'))
# defining Handlers
def start(bot, update):
""" When /start is pressed - prompts user with brief introduction and ask to press GO! button """
go_button = telegram.KeyboardButton(text="GO!")
custom_keyboard = [[go_button]]
chat_reply = "Hello hello! Want me to suggest food places for you? Press GO!"
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True)
bot.send_message(chat_id=update.message.chat_id, text=chat_reply, reply_markup=reply_markup)
def respond(bot, update):
""" When user sends any text response """
def error_msg():
location_button = telegram.KeyboardButton(text="Suggest a location")
all_location_button = telegram.KeyboardButton(text="See all locations")
custom_keyboard = [[location_button], [all_location_button]]
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True)
bot.send_message(chat_id=update.message.chat_id, text="Aiyo paiseh got error LOL try again can?", reply_markup=reply_markup)
def suggest_location():
locations = pd.read_csv('locations.csv', index_col=0)
suggestion = random.choice(list(locations['name']))
bot.send_message(chat_id=update.message.chat_id, text=f"We should go to... {suggestion}!!")
return suggestion
def next_step_prompt(suggestion):
location_restaurant_button = telegram.KeyboardButton(text=f"Suggest a restaurant in {suggestion}")
location_button = telegram.KeyboardButton(text="Suggest another location")
all_location_button = telegram.KeyboardButton(text="See all locations")
custom_keyboard = [[location_restaurant_button], [location_button], [all_location_button]]
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True)
bot.send_message(chat_id=update.message.chat_id, text="Do you want me to suggest a restaurant in this location? Suggest another location? You can also choose to see all locations!", reply_markup=reply_markup)
def see_all_locations():
ccp_button = telegram.KeyboardButton(text="Changi City Point")
uebiz_button = telegram.KeyboardButton(text="UE BizHub")
plaza8_button = telegram.KeyboardButton(text="Plaza 8")
ibm_button = telegram.KeyboardButton(text="IBM")
sig_button = telegram.KeyboardButton(text="The Signature")
airt3_button = telegram.KeyboardButton(text="Airport T3")
custom_keyboard = [[ccp_button], [uebiz_button], [plaza8_button], [ibm_button], [sig_button], [airt3_button]]
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True)
bot.send_message(chat_id=update.message.chat_id, text="Click the below if you want me to suggest a restaurant in the location, or any other locations!", reply_markup=reply_markup)
class Location(object):
def __init__(self, location_name, location_csv):
self.location_name = location_name
self.location_csv = location_csv
def suggest_restaurants(self):
restaurant_database = pd.read_csv(self.location_csv, index_col=0)
suggestion = random.choice(list(restaurant_database['name']))
bot.send_message(chat_id=update.message.chat_id, text=f"We should eat at... {suggestion}!!")
another_restaurant_button = telegram.KeyboardButton(text=f"Suggest another restaurant in {self.location_name}")
location_button = telegram.KeyboardButton(text="Suggest another location")
all_location_button = telegram.KeyboardButton(text="See all locations")
custom_keyboard = [[another_restaurant_button], [location_button], [all_location_button]]
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True)
bot.send_message(chat_id=update.message.chat_id, text="Let me know if you want another restaurant recommendation... or another location recommendation!", reply_markup=reply_markup)
ccp = Location('Changi City Point', 'locations/ccp.csv')
ue = Location('UE BizHub', 'locations/uebizhub.csv')
plaza8 = Location('Plaza 8', 'locations/plaza8.csv')
signature = Location('The Signature', 'locations/signature.csv')
airport_t3 = Location('Airport T3', 'locations/airportt3.csv')
ibm = Location('IBM', 'locations/ibm.csv')
if update.message.text == 'GO!':
suggestion = suggest_location()
next_step_prompt(suggestion)
elif update.message.text in ['Suggest a location', 'Suggest another location']:
try:
suggestion = suggest_location()
next_step_prompt(suggestion)
except:
error_msg()
elif update.message.text == 'See all locations':
try:
see_all_locations()
except:
error_msg()
else:
location_dict = {'Changi City Point': ccp, 'UE BizHub': ue, 'Plaza 8': plaza8, 'Signature': signature,
'Airport T3': airport_t3, 'IBM': ibm}
try:
for key in location_dict.keys():
if key in update.message.text:
database = location_dict[key]
database.suggest_restaurants()
except:
error_msg()
def helper_help(bot, update):
""" If user sends /help command """
bot.send_message(chat_id=update.message.chat_id, text="Type /start to start LOL")
def helper_unknown(bot, update):
""" If user sends unknown command """
bot.send_message(chat_id=update.message.chat_id, text="Sorry leh, I don't know that command. If you don't know got what command, just type / then everything will come out")
def helper_error(bot, update, error, logger):
""" Log Errors """
logger.warning('Update "%s" caused error "%s"' % (update, error))
# define main function
def main():
""" This is where the bot starts from! """
updater = Updater(token=telegram_token)
# Get the dispatcher to register handlers
dispatch = updater.dispatcher
# define which handler to use on different commands to answer in Telegram
start_handler = CommandHandler('start', start)
dispatch.add_handler(start_handler)
respond_handler = MessageHandler(Filters.text, respond)
dispatch.add_handler(respond_handler)
help_handler = CommandHandler('help', helper_help)
dispatch.add_handler(help_handler)
unknown_handler = MessageHandler(Filters.command, helper_unknown)
dispatch.add_handler(unknown_handler)
# log all errors
dispatch.add_error_handler(helper_error)
#PROD
port_number = int(os.environ.get('PORT', '5000'))
updater.start_webhook(listen="0.0.0.0",
port=port_number,
url_path=telegram_token)
updater.bot.setWebhook("https://foodsuggestsg.herokuapp.com/" + telegram_token)
updater.idle()
if __name__ == '__main__':
main()