def nearest_stations(bot, update, count=5):
with open('allstations.csv', newline='', encoding='utf-8') as infile:
csv_reader = csv.reader(infile, delimiter=';')
stations = [(int(row[0]), float(row[1]), float(row[2]), row[3]) for row in csv_reader]
# distance sorting based on http://stackoverflow.com/a/28368926 by Sergey Ivanov
coord = (float(update.message.location.latitude), float(update.message.location.longitude))
pts = [geopy.Point(p[1], p[2], p[0]) for p in stations]
sts = [p[3] for p in stations]
onept = geopy.Point(coord[0], coord[1])
alldist = [(p, geopy.distance.distance(p, onept).m) for p in pts]
nearest = sorted(alldist, key=lambda x: (x[1]))[:count]
nearest_points = [n[0] for n in nearest]
nearest_distances = [n[1] for n in nearest]
nearest_sts = [sts[int(n.altitude)] for n in nearest_points]
msg = 'Nächstgelegene Stationen:'
for s, d, p in zip(nearest_sts, nearest_distances, nearest_points):
msg += '\n{} (<a href="https://www.google.de/maps?q={},{}">{:.0f}m</a>)'.format(s, p.latitude,
p.longitude, d)
reply_keyboard = [[telegram.KeyboardButton(text='/Abfahrten {}'.format(n))] for n in nearest_sts]
bot.sendMessage(chat_id=update.message.chat_id, text=msg, parse_mode='HTML',
reply_markup=telegram.ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
python类ReplyKeyboardMarkup()的实例源码
def recover(bot, update, db, users_state):
user_id = update.message.from_user.id
users_state[user_id] = dict()
users_state[user_id]['channels'] = dict()
keyboard = []
keyboard_row = []
for channel in db.query(DisabledChannel).filter(DisabledChannel.owner_id == str(user_id)).order_by(DisabledChannel.created_at.desc()):
title = '{} ({})'.format(channel.vk_group_id, channel.channel_id)
users_state[user_id]['channels'][title] = channel.channel_id
keyboard_row.append(title)
if len(keyboard_row) == 2:
keyboard.append(keyboard_row)
keyboard_row = []
if len(keyboard_row) != 0:
keyboard.append(keyboard_row)
if len(keyboard) == 0:
update.message.reply_text('??? ???????, ??????? ????? ????????????')
del_state(update, users_state)
return ConversationHandler.END
else:
update.message.reply_text('???????? ?????', reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True))
return ASKED_CHANNEL_ID_IN_RECOVER
def show_settings(bot, update):
chat = update.message.chat
if update.message.chat.type != 'private':
send_async(bot, chat.id,
text=_("Please edit your settings in a private chat with "
"the bot."))
return
us = UserSetting.get(id=update.message.from_user.id)
if not us:
us = UserSetting(id=update.message.from_user.id)
if not us.stats:
stats = '??' + ' ' + _("Enable statistics")
else:
stats = '?' + ' ' + _("Delete all statistics")
kb = [[stats], ['??' + ' ' + _("Language")]]
send_async(bot, chat.id, text='??' + ' ' + _("Settings"),
reply_markup=ReplyKeyboardMarkup(keyboard=kb,
one_time_keyboard=True))
def kb_select(bot, update, groups):
chat = update.message.chat
user = update.message.from_user
option = groups[0]
if option == '??':
us = UserSetting.get(id=user.id)
us.stats = True
send_async(bot, chat.id, text=_("Enabled statistics!"))
elif option == '??':
kb = [[locale + ' - ' + descr]
for locale, descr
in sorted(available_locales.items())]
send_async(bot, chat.id, text=_("Select locale"),
reply_markup=ReplyKeyboardMarkup(keyboard=kb,
one_time_keyboard=True))
elif option == '?':
us = UserSetting.get(id=user.id)
us.stats = False
us.first_places = 0
us.games_played = 0
us.cards_played = 0
send_async(bot, chat.id, text=_("Deleted and disabled statistics!"))
def cmd_vote(bot: telegram.Bot, update: telegram.Update):
cid = update.message.chat_id
uid = update.message.from_user.id
polls = get_polls(uid, bot)
if update.message.chat.type != "private":
bot.sendMessage(cid, text_private_chat_only)
return ConversationHandler.END
if len(polls) == 0:
bot.sendMessage(cid, "You aren't eligible to vote in any polls.")
else:
keyboard_choices = [p["tag"] + ": " + p["title"] for p in polls]
# keyboard array is a list of lists
# because each list represents a new row
# and we want each button on a separate row
keyboard_array = [[k, ] for k in keyboard_choices]
keyboard = ReplyKeyboardMarkup(keyboard_array,
one_time_keyboard=True)
bot.sendMessage(cid,
"Click the button for the poll you would like to vote in.",
reply_markup=keyboard)
return state_vote_1
def execute(self, chat_id, bot: Bot, update: Update):
handled = False
if update.message.text in self._buildings_dict:
handled = True
building_identifier = self._buildings_dict[update.message.text]
classrooms = self.get_classroom_source().get_classrooms_in_building(building_identifier)
keyboard_button = []
counter = 0
row = -1
for classroom in classrooms:
if counter == 0:
keyboard_button.append([])
row += 1
keyboard_button[row].append(KeyboardButton("/"+classroom.get_name().lower()))
counter += 1
if counter == 3:
counter = 0
keyboard_button.append(["/buildings"])
reply_keyboard = ReplyKeyboardMarkup(keyboard_button)
bot.send_message(chat_id=chat_id, text="Available classrooms", reply_markup=reply_keyboard)
return handled
def services(bot, update):
reply_keyboard = [["Agregar Saldo"], ["Ver saldo"], ["Retirar"], ["Mis retiros"], ["Transferir"], ["Mis transferencias"], ["Recargar"],["Mis recargas"],
["Menu Principal"]]
response = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=False)
update.message.reply_text("¿Que quieres hacer?", reply_markup=response)
if response == "Ver saldo":
return GET_BALANCE
elif response == "Retirar":
return WITHDRAW
elif response == "Cuenta":
return ACCOUNT_INFO
elif response == "Transferir":
return TRANSFERIR
elif response == "Mis transferencias":
return SHOW_TRANSFERS
elif response == "Mis retiros":
return SHOW_WITHDRAWS
elif response == "Recargar":
return RECARGAR
elif response == "Mis recargas":
return SHOW_RECHARGES
elif response == "Menu Principal":
return RETURN
return ADD_BALANCE
def trade_cmd(bot, update):
reply_msg = "Buy or sell?"
buttons = [
KeyboardButton(KeyboardEnum.BUY.clean()),
KeyboardButton(KeyboardEnum.SELL.clean())
]
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_BUY_SELL
# Save if BUY or SELL order and choose the currency to trade
def trade_buy_sell(bot, update, chat_data):
chat_data["buysell"] = update.message.text
reply_msg = "Choose currency"
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
# If SELL chosen, then include button 'ALL' to sell everything
if chat_data["buysell"].upper() == KeyboardEnum.SELL.clean():
cancel_btn.insert(0, KeyboardButton(KeyboardEnum.ALL.clean()))
reply_mrk = ReplyKeyboardMarkup(build_menu(coin_buttons(), n_cols=3, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_CURRENCY
# Show confirmation to sell all assets
def trade_price(bot, update, chat_data):
chat_data["price"] = update.message.text
reply_msg = "How to enter the volume?"
buttons = [
KeyboardButton(config["trade_to_currency"].upper()),
KeyboardButton(KeyboardEnum.VOLUME.clean())
]
cancel_btn = [
KeyboardButton(KeyboardEnum.ALL.clean()),
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_VOL_TYPE
# Save volume type decision and enter volume
def orders_choose_order(bot, update):
buttons = list()
# Go through all open orders and create a button
if orders:
for order in orders:
order_id = next(iter(order), None)
buttons.append(KeyboardButton(order_id))
else:
update.message.reply_text("No open orders")
return ConversationHandler.END
msg = "Which order to close?"
close_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=1, footer_buttons=close_btn))
update.message.reply_text(msg, reply_markup=reply_mrk)
return WorkflowEnum.ORDERS_CLOSE_ORDER
# Close all open orders
def bot_cmd(bot, update):
reply_msg = "What do you want to do?"
buttons = [
KeyboardButton(KeyboardEnum.UPDATE_CHECK.clean()),
KeyboardButton(KeyboardEnum.UPDATE.clean()),
KeyboardButton(KeyboardEnum.RESTART.clean()),
KeyboardButton(KeyboardEnum.SHUTDOWN.clean()),
KeyboardButton(KeyboardEnum.SETTINGS.clean()),
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.BOT_SUB_CMD
# Execute chosen sub-cmd of 'bot' cmd
def chart_cmd(bot, update):
reply_msg = "Choose currency"
buttons = list()
for coin, url in config["coin_charts"].items():
buttons.append(KeyboardButton(coin))
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=3, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.CHART_CURRENCY
# Get chart URL for every coin in config
def settings_cmd(bot, update):
settings = str()
buttons = list()
# Go through all settings in config file
for key, value in config.items():
settings += key + " = " + str(value) + "\n\n"
buttons.append(KeyboardButton(key.upper()))
# Send message with all current settings (key & value)
update.message.reply_text(settings)
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
msg = "Choose key to change value"
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn))
update.message.reply_text(msg, reply_markup=reply_mrk)
return WorkflowEnum.SETTINGS_CHANGE
# Change setting
def keyboard_cmds():
command_buttons = [
KeyboardButton("/trade"),
KeyboardButton("/orders"),
KeyboardButton("/balance"),
KeyboardButton("/price"),
KeyboardButton("/value"),
KeyboardButton("/chart"),
KeyboardButton("/history"),
KeyboardButton("/funding"),
KeyboardButton("/bot")
]
return ReplyKeyboardMarkup(build_menu(command_buttons, n_cols=3))
# Generic custom keyboard that shows YES and NO
def eventSelectEditing(self, bot, update, user_data):
user_data[user_data['editing_choice']] = update.message.text
reply_text = ""
if user_data['editing_choice'] == 'Time' and not isTimeString(update.message.text):
reply_text = "Your time string is not formatted correctly, please try again.\n\n"
user_data['Time'] = None
elif user_data['editing_choice'] == 'Date' and not isDateString(update.message.text):
reply_text = 'You Date string is not formatted correctly (m/d/20xx), please try again.\n\n'
user_data['Date'] = None
reply_keyboard = [['Name', 'Time', 'Date'],
['Group','Place'],
['Description']]
if all (key in user_data for key in ['Name','Time','Date','Description','Place','Group']):
reply_keyboard.append(['Cancel','Done'])
else:
reply_keyboard.append(['Cancel'])
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
reply_text += "Please select which you would like to edit, once you've entered something for all of these, you will be able to create the event."
update.message.reply_text(reply_text, reply_markup=markup)
return EVENTSELECT
def start(bot, update):
"""
Shows an welcome message and help info about the available commands.
"""
me = bot.get_me()
# Welcome message
msg = _("Hello!\n")
msg += _("I'm {0} and I came here to help you.\n").format(me.first_name)
msg += _("What would you like to do?\n\n")
msg += _("/support - Opens a new support ticket\n")
msg += _("/settings - Settings of your account\n\n")
# Commands menu
main_menu_keyboard = [[telegram.KeyboardButton('/support')],
[telegram.KeyboardButton('/settings')]]
reply_kb_markup = telegram.ReplyKeyboardMarkup(main_menu_keyboard,
resize_keyboard=True,
one_time_keyboard=True)
# Send the message with menu
bot.send_message(chat_id=update.message.chat_id,
text=msg,
reply_markup=reply_kb_markup)
def settings(bot, update):
"""
Configure the messages language using a custom keyboard.
"""
# Languages message
msg = _("Please, choose a language:\n")
msg += "en_US - English (US)\n"
msg += "pt_BR - Português (Brasil)\n"
# Languages menu
languages_keyboard = [
[telegram.KeyboardButton('en_US - English (US)')],
[telegram.KeyboardButton('pt_BR - Português (Brasil)')]
]
reply_kb_markup = telegram.ReplyKeyboardMarkup(languages_keyboard,
resize_keyboard=True,
one_time_keyboard=True)
# Sends message with languages menu
bot.send_message(chat_id=update.message.chat_id,
text=msg,
reply_markup=reply_kb_markup)
def traffic(bot, update, args):
""" Get Traffic Updates """
if len(args) == 0:
final_string = 'Please enter either traffic Woodlands or traffic Tuas'
custom_keyboard = [['/traffic Tuas', '/traffic Woodlands']]
reply_markup = ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, selective=True)
bot.sendMessage(update.message.chat_id, final_string, reply_markup=reply_markup)
else:
bot.sendMessage(update.message.chat_id, text='I go turn on my spycam, please wait',
parse_mode='HTML')
bot.sendChatAction(update.message.chat_id, action=ChatAction.TYPING)
final_string = gov.traffic_get(args[0])
bot.sendMessage(update.message.chat_id, text=final_string, parse_mode='HTML')
botan_track(update.message.from_user.id, update.message, update.message.text)
def __init__(self, token, host, port, cert, cert_key, working_dir):
self.token = token
self.host = host
self.port = port
self.cert = cert
self.cert_key = cert_key
self.bot = telegram.Bot(self.token)
self.app = Flask(__name__)
self.context = (self.cert, self.cert_key)
self.working_dir = working_dir
self.kb = [[telegram.KeyboardButton('Offer me a coffee'), telegram.KeyboardButton('Source Code'), telegram.KeyboardButton('Vote Me')]]
self.kb_markup = telegram.ReplyKeyboardMarkup(self.kb, resize_keyboard=True)
def custom_keyboard(bot, chat_id, buttons, text):
reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard = True)
try:
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except BadRequest:
bot.sendMessage(chat_id=chat_id,
text=replace_unsafe(text),
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except RetryAfter:
sleep(240)
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except TimedOut:
sleep(10)
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except:
sleep(1)
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
def reply_to_start_command(bot, update):
reply_keyboard = [['???????? ??????', '?????? ??????', '????????? ??????']]
update.message.reply_text(
"??????! ? ???, ??????? ??????? ????????? ??????? ??????.",
reply_markup=ReplyKeyboardMarkup(reply_keyboard)
)
def reply_to_start_command(bot, update):
reply_keyboard = [['???????? ??????', '?????? ??????', '????????? ??????']]
update.message.reply_text(
"??????! ? ???, ??????? ??????? ????????? ??????? ??????.",
reply_markup=ReplyKeyboardMarkup(reply_keyboard)
)
def get_name(bot, update, user_data):
user_name = update.message.text
if len(user_name.split(" ")) < 2:
update.message.reply_text("??????????, ???????? ??? ? ???????")
return "name"
else:
user_data["name"] = user_name
reply_keyboard = [["1", "2", "3", "4", "5"]]
update.message.reply_text(
"?????????? ?? ??? ????? ??????? ?? ????? ?? 1 ?? 5",
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
)
return "attitude"
def attitude(bot, update, user_data):
user_data["attitude"] = update.message.text
reply_keyboard = [["1", "2", "3", "4", "5"]]
update.message.reply_text(
"??? ?? ???? ???????? ??????? ?? ????? ?? 1 ?? 5",
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
)
return "understanding"
def comment(bot, update, user_data):
user_data["comment"] = update.message.text
reply_keyboard = [['???????? ??????', '?????? ??????']]
update.message.reply_text("??????? ?? ??? ???????????!", reply_markup=ReplyKeyboardMarkup(reply_keyboard))
return ConversationHandler.END
def reply_to_start_command(bot, update, user_data):
first_name = update.effective_user.first_name
last_name = update.effective_user.last_name
avatar = get_avatar(user_data)
text = "??????, {} {}! ? ???, ??????? ???????? ??????? /start".format(first_name, avatar)
logging.info("???????????? {} {} ????? {}".format(first_name, last_name, "/start"))
update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))
def change_avatar_step1(bot, update, user_data):
reply_keyboard = []
for index, ava in enumerate(avatars):
button = "/avatar {} {}".format(index, ava)
button = emojize(button, use_aliases=True)
reply_keyboard.append(button)
text = '?????? ???????? {}'.format(get_avatar(user_data))
update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup([reply_keyboard], resize_keyboard=True))
def change_avatar_step2(bot, update, args, user_data):
try:
ava = avatars[int(args[0])]
user_data['avatar'] = emojize(ava, use_aliases=True)
update.message.reply_text('???????? ????????', reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))
except(IndexError, ValueError):
update.message.reply_text('?????????? ??? ???')
def reply_to_start_command(bot, update, user_data):
user = get_user(update.effective_user, user_data)
text = "??????, {} {}! ? ???, ??????? ???????? ??????? /start".format(user.first_name, user.avatar)
logging.info("???????????? {} {} ????? {}".format(user.first_name, user.last_name, "/start"))
update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))