def next_recipe(bot, update): user = update.message.from_user reply_keyboard = [['Yes', 'One more !']] if update.message.text == 'Yes': reply_markup = ReplyKeyboardHide() bot.sendMessage(update.message.chat_id, text=conversations['enjoy'][randint(0, 2)] % user.first_name, reply_markup=reply_markup) bot.sendMessage( update.message.chat_id, text='To start the conversation again, simply click on /start.') log_to_csv(update.message.chat_id, user, sent_recipes[0], preferences) gif = str(conversations['gifs'][(randint(0, 2))]) bot.sendDocument(chat_id=update.message.chat_id, document=gif) return ConversationHandler.END if len(sent_recipes) > limit_of_recipes - 1: reply_markup = ReplyKeyboardHide() bot.sendMessage(update.message.chat_id, conversations['notMore'][(randint(0, 2))], reply_markup=reply_markup) del sent_recipes[:] return ConversationHandler.END # Code duplication here, change this! try: recipe = get_recipe(preferences) except Exception, e: bot.sendMessage(update.message.chat_id, text=conversations['problem'][randint(0, 2)]) return ConversationHandler.END
def set_only_mention(self, message, user_id, chat_id, user): """ Manages the set only mention requests :param message: Str with the message (Yes or No) :param user_id: User id :param chat_id: Chat ud :param user: Dict with user configuration :return: None """ onlymentions = message == 'Yes' if self.get_group(): user.set_field(chat_id, 'onlymentions', onlymentions, group=self.get_group()) user.set_field(chat_id, 'mode', 'normal', group=self.get_group()) else: user.set_field(user_id, 'onlymentions', onlymentions, group=self.get_group()) user.set_field(user_id, 'mode', 'normal', group=self.get_group()) if not onlymentions: text = self._get_template('only_mention.md').render() self.telegram_api.sendMessage( chat_id, text, 'Markdown', reply_markup=ReplyKeyboardHide()) else: template = self._get_template('answer_always.md') text = template.render(is_rtl=self.get_is_rtl()) self.telegram_api.sendMessage( chat_id, text, 'Markdown', reply_markup=ReplyKeyboardHide())
def process_vote_response(bot: telegram.Bot, update: telegram.Update): # Message text comes from a reply keyboard. # The keyboard options look like: "abcdefgh: Title of Poll", # where "abcdefgh" is the poll tag. t = update.message.text uid = update.message.from_user.id # Check if user has typed something into the text reply, instead of # clicking a reply keyboard button like they should have. if not re.match("^[a-z]{8}:", t): bot.sendMessage(update.message.chat_id, text_vote_not_understood, reply_markup=ReplyKeyboardHide()) return ConversationHandler.END # Check if the given poll tag 1) exists, 2) is active, # and 3) if the user is allowed to vote in that poll. poll_tag = t[0:8] q = Query() poll = polls_db.get(q.tag == poll_tag) if (poll is None) or (poll['active'] != True) or (not user_is_in_chat( uid, poll['target_chat'], bot)): bot.sendMessage(update.message.chat_id, text_no_such_vote, reply_markup=ReplyKeyboardHide()) return ConversationHandler.END # Check if user was already given a token for this poll. q2 = Query() existing_token = tokens_db.get(q2.user_id == uid and q2.poll_tag == poll_tag) if existing_token is None: # Give new token token = make_token(uid, poll_tag) msg = text_new_token.format(title=poll['title'], url=poll['url'], token=token) bot.sendMessage(update.message.chat_id, msg, reply_markup=ReplyKeyboardHide()) return ConversationHandler.END else: # Give existing token again token = existing_token['token'] msg = text_existing_token.format(title=poll['title'], url=poll['url'], token=token) bot.sendMessage(update.message.chat_id, msg, reply_markup=ReplyKeyboardHide()) return ConversationHandler.END assert False # Should never reach here
def get_reply_markup(self, user): action = "show" ply = persistence_controller.get_ply(user) if user and str(user.id): if ply.event: if str(user.id) in ply.event.custom_keyboard_status.keys(): if ply.event.custom_keyboard_status[str( user.id )] == "close" or ply.event.custom_keyboard_status[str( user.id)] == "never show": action = "close" else: if str(user.id) in DungeonBot.custom_keyboard_status.keys(): if DungeonBot.custom_keyboard_status[str( user.id )] == "close" or DungeonBot.custom_keyboard_status[str( user.id)] == "never show": action = "close" markup = None keyboard = None if action == "show": if ply.event: keyboard = ply.event.get_keyboard(user) else: keyboard = self.get_keyboard(user) if keyboard: markup = ReplyKeyboardMarkup(keyboard) else: markup = ReplyKeyboardHide(True) return markup
def subscribe(bot, update): ''' Provides user subscription. ''' chat = Chat.get_or_create(id=update.message.chat_id) show_title = update.message.text[11:].strip().lower() if show_title: try: show = Show.nodes.get(title_lower=show_title) if chat in show.subscribers.all(): response = _('You are already subscribed to this series.') else: show.subscribers.connect(chat) response = _('You have subscribed to the show.') except DoesNotExist: response = _('Specified series is not on my list, ' 'but we will try to find this series.') ShowFinder(bot=bot, chat_id=update.message.chat_id, show_title=show_title).start() chat.referer = '' else: response = _('Which series would you like to subscribe?') chat.referer = update.message.text bot.sendMessage(chat_id=update.message.chat_id, text=response, reply_markup=ReplyKeyboardHide()) chat.save()
def rate(bot, update): ''' Provides the ability to rate videos. ''' chat = Chat.get_or_create(id=update.message.chat_id) video = Video.nodes.get(url=' '.join(update.message.text[6:].split()[:-1])) chat.rated_videos.disconnect(video) ref, chat.referer = chat.referer, '' chat.save() if update.message.text.split()[-1] == unicode(Emoji.THUMBS_UP_SIGN, 'utf-8'): chat.rated_videos.connect(video, {'value': 1}) bot.sendMessage(chat_id=update.message.chat_id, text=_('Thanks for the feedback!'), reply_markup=ReplyKeyboardHide()) elif update.message.text.split()[-1] == unicode(Emoji.THUMBS_DOWN_SIGN, 'utf-8'): chat.rated_videos.connect(video, {'value': -1}) update.message.text = ' '.join(['/watch', video.episode.get().id]) watch(bot, update) else: chat.referer = ref chat.save() bot.sendMessage(chat_id=update.message.chat_id, text=_('Please rate the video.'), reply_markup=ReplyKeyboardMarkup( [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]]))
def setlanguage(bot, update): ''' Provides the setting of language preferences. ''' chat = Chat.get_or_create(id=update.message.chat_id) language = update.message.text[13:].strip().lower() reply_markup = ReplyKeyboardHide() if language: if language in shared.translations: if chat.language != language: chat.language = language chat.save() response = _('The language has changed!') else: response = _('You are already using this language!') else: response = _('Unknown language!') chat.referer = '' else: response = _('Which language do you prefer?') reply_markup = ReplyKeyboardMarkup( [shared.config['telegram']['locales']]) chat.referer = update.message.text bot.sendMessage(chat_id=update.message.chat_id, text=response, reply_markup=reply_markup) chat.save()
def unsubscribe(bot, update): ''' Provides user unsubscription. ''' chat = Chat.get_or_create(id=update.message.chat_id) show_title = update.message.text[13:].strip().lower() if show_title: try: show = Show.nodes.get(title_lower=show_title) if chat in show.subscribers.all(): show.subscribers.disconnect(chat) response = _('You have unsubscribed from the show.') else: response = _('You are not subscribed to the show.') except DoesNotExist: response = _('Specified series is not on my list.') chat.referer = '' else: response = _('Which series would you like to unsubscribe?') chat.referer = update.message.text bot.sendMessage(chat_id=update.message.chat_id, text=response, reply_markup=ReplyKeyboardHide()) chat.save()
def reto_enviar(self, bot, update, user_data): chat_id = str(update.message.chat_id) problema = update.message.text logging.info('STATS [%s] [reto-enviar] %s' % (chat_id, problema)) problemas = configparser.ConfigParser() problemas.read_file( codecs.open(self.tr_bot.file_reto_problemas, "r", "utf-8")) propuestos = list() t_now = datetime.datetime.now() for prob in problemas.sections(): t_ini = parser.parse(problemas.get(prob, 'fecha_inicio')) t_fin = parser.parse(problemas.get(prob, 'fecha_fin')) if (t_now > t_ini) & (t_now < t_fin): propuestos.append(prob) if problema not in propuestos: # Quiere mandar solución a problema ya resuelto return self.reto_error(bot, update, user_data) if self.tr_bot.users.has_option(chat_id, problema): txt = ('Para el problema ' + problema + ' ya tenías la solución ' + self.tr_bot.users.get(chat_id, problema) + '. ' + 'Escribe tu solución o "Zzz" para cancelar: ') else: txt = ('Escribe tu solución para el problema ' + problema + ': ' + 'o "Zzz" para cancelar: ') user_data['solucion'] = 0 user_data['prob'] = problema update.message.reply_text(txt, reply_markup=ReplyKeyboardHide()) return self.RETO_RECIBIDA
def opinar_votar_texto(self, bot, update, user_data): user_data['textolibre'] = True # chat_id = str(update.message.chat_id) # logging.info('STATS [%s] [opinar-clase-t]' % chat_id) update.message.reply_text('Texto libre sobre la última clase:', reply_markup=ReplyKeyboardHide()) return self.OPINAR_VOTADO
def endpoll(bot, update): """Ends poll and show results. Delete all data of poll""" chat_id = update.message.chat_id if chat_id in config.act: if config.act[chat_id]['act']: sortres = [(v, k) for k, v in config.act[chat_id]['resp'].iteritems()] sortres.sort(reverse=True) ftext = config.act[chat_id]['quo'] + "\n" for val, key in sortres: ftext += ("\n%s: %d" % (key, val)) reply_markup = ReplyKeyboardHide() bot.sendMessage( chat_id=chat_id, # text=Emoji.BAR_CHART + " " + ftext, text=Emoji.BAR_CHART + ftext.encode('utf-8').strip(), reply_markup=reply_markup) config.act.pop(chat_id, None) else: bot.sendMessage(chat_id=chat_id, text="No hay ninguna votación en curso.") else: bot.sendMessage(chat_id=chat_id, text="No hay ninguna votación en curso.")
def run(self): chat = Chat.get_or_create(self.chat_id) videos = set(self.episode.videos) # select chat rated videos chat_rated_videos = set([v for v in videos if chat in v.critics]) # if rating is positive, return this video, otherwise return the best video if any([v.critics.relationship(chat).value > 0 for v in chat_rated_videos]): videos = [v for v in chat_rated_videos if v.critics.relationship(chat).value > 0] else: videos = sorted(videos-chat_rated_videos, key=lambda x: -x.score) reply_markup = ReplyKeyboardMarkup([[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]]) if videos: response = videos[0].link chat.referer = '/rate ' + response elif update_episode_urls(self.episode): response = self.episode.videos.all()[0].link chat.referer = '/rate ' + response else: response = _('We could not found any video of the episode.') reply_markup = ReplyKeyboardHide() chat.referer = '' self.bot.sendMessage(chat_id=self.chat_id, text=response, reply_markup=reply_markup) chat.save()
def build_keyboard(self, keyboard): if keyboard: keyboard = ast.literal_eval(keyboard) keyboard = ReplyKeyboardMarkup(keyboard, resize_keyboard=True) else: keyboard = ReplyKeyboardHide() return keyboard
def get_location(self, bot, update): latitude = update.message.location.latitude longitude = update.message.location.longitude chat_id = update.message.chat_id telegram_id = update.message.from_user.id telegram_user = EdxTelegramUser.objects.get(telegram_id=telegram_id) bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) UserLocation.objects.create(telegram_user=telegram_user, longitude=longitude, latitude=latitude) message = "There is no edX users nearby" your_location = (latitude, longitude) last_users_location = [ UserLocation.objects.filter(telegram_user=each).last() for each in EdxTelegramUser.objects.all().exclude( id=telegram_user.id) ] distance_to_users = [(each.telegram_user, vincenty(your_location, (each.latitude, each.longitude)).meters) for each in last_users_location if each] distance_to_users.sort(key=lambda x: x[1]) if distance_to_users: message = "The closest edX user is just %.2f meters from you, their name are @%s, chat to them if you want ;)" %\ (distance_to_users[0][1], distance_to_users[0][0].telegram_nick) bot.sendMessage(chat_id=chat_id, text=message, reply_markup=ReplyKeyboardHide())
def get_course_description(self, bot, chat_id, course_name=None, course_key=None, enroll=None, enroll_keyboard=False): """ Get description of particular courses by Title or by course_id """ bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) if enroll: result = CourseEnrollment.objects.get(id=enroll) results = [modulestore().get_course(result.course_id)] course_name = results[0].display_name_with_default elif course_key: results = [modulestore().get_course(course_key)] course_name = modulestore().get_course( course_key).display_name_with_default else: results = modulestore().get_courses() results = [ course for course in results if course.scope_ids.block_type == 'course' ] for each in results: if each.display_name_with_default == course_name: message = truncate_course_info( CourseDetails.fetch_about_attribute(each.id, 'overview')) if message == 'null': bot.sendMessage( chat_id=chat_id, text="I'm sorry, but this course has no description") else: bot.sendMessage(chat_id=chat_id, text="*Short course description*", parse_mode=telegram.ParseMode.MARKDOWN) course_key = each.id current_site = Site.objects.get_current() course_title = modulestore().get_course( course_key).display_name_with_default course_url = '[%s](%scourses/%s/)' % ( course_title, current_site, each.id) bot.sendMessage(chat_id=chat_id, text=course_url, parse_mode=telegram.ParseMode.MARKDOWN) if enroll_keyboard: reply_markup = InlineKeyboardMarkup([[ InlineKeyboardButton( text='I like it and I want to enroll', callback_data=json.dumps( {'key': str(course_key)})) ]]) bot.sendMessage(chat_id=chat_id, text=message, reply_markup=reply_markup) else: bot.sendMessage(chat_id=chat_id, text=message) break bot.sendMessage(chat_id=chat_id, reply_markup=ReplyKeyboardHide())
def finger_in_command(bot, update, args, is_reply=False): chat_id = update.message.chat_id logger.info("Finger on %s" % chat_id) if not Pineapple.is_open(chat_id): logger.info("Pineapple not open") send_message(bot, chat_id, MESSAGE.NOT_YET_OPEN) return user_name = get_full_name(update.message.from_user) pineapple = Pineapple.get(chat_id) if len(args) == 2 and "".join(args) == "domeio": # Easter Egg pineapple.middle_finger(user_name) message = pineapple.get_short_fingers_list_message() else: try: pineapple.finger_in(user_name) Pineapple.update(chat_id, pineapple) message = pineapple.get_short_fingers_list_message() except Finger.FingersLimitReached: message = MESSAGE.NO_MORE_FINGERS_IN_HAND if is_reply: message_id = update.message.message_id else: message_id = None send_message(bot, chat_id, message, reply_to_message_id=message_id, reply_markup=ReplyKeyboardHide(selective=True))
def message_location(self, bot, update): user_id = str(update.message.from_user.id) text = str(update.message.location.latitude) + "|" + str( update.message.location.longitude) draft = self.store.get_draft(user_id) if draft: event = draft['event'] current_field = draft['current_field'] field = FIELDS[current_field] if field['name'] == 'place' or field['name'] == 'parking': event[field['name']] = parse_fields(field['name'], text) current_field += 1 self.update_draft(bot, event, user_id, update, current_field) else: bot.sendMessage( update.message.chat_id, text= "\u26A0\uFE0F En aquest pas no pots enviar una ubicació. Torna a provar-ho seguint els passos que s'indiquen." ) current_field += 0 self.update_draft(bot, event, user_id, update, current_field) else: bot.sendMessage( update.message.chat_id, text= "\U0001F914 No sé a on para això, ni per què m'ho has enviat. Si vols fer alguna cosa útil:\n\n1. /start per a començar a crear una excursió nova\n2. /help per a saber un poc més sobre mi.", reply_markup=ReplyKeyboardHide())
def set_language_command(self, message, user_id, chat_id, u): """ Answers the language command :param message: Message :param user_id: User identifier :param chat_id: Chat identifier :param u: User object :return: None """ if message in self.get_languages(): if self.get_group(): u.set_field(chat_id, 'lang', self.get_languages()[message], group=self.get_group()) u.set_field(chat_id, 'mode', 'normal', group=self.get_group()) else: u.set_field(user_id, 'lang', self.get_languages()[message], group=self.get_group()) u.set_field(user_id, 'mode', 'normal', group=self.get_group()) self.load_language(self.get_languages()[message]) template = self._get_template('new_language.md') text = template.render(is_rtl=self.get_is_rtl()) k = ReplyKeyboardHide() self.telegram_api.sendMessage( chat_id, text, 'Markdown', reply_markup=k) else: if self.get_group(): u.set_field(chat_id, 'mode', 'normal', group=True) else: u.set_field(user_id, 'mode', 'normal') temp = self._get_template('cant_talk_message.md') text = temp.render() self.telegram_api.sendMessage(chat_id, text, 'Markdown')
def cancel(bot, update): user = update.message.from_user logger.info("User %s canceled the conversation." % user.first_name) update.message.reply_text('Bye! I hope we can talk again some day.', reply_markup=ReplyKeyboardHide()) return ConversationHandler.END
def handler(bot, update): chat_id = update.message.chat.id text = update.message.text.encode('utf-8') chat_state = state.get(chat_id, NEW_USER) chat_context = context.get(chat_id, None) if chat_state == NEW_USER and text[0] == '/' or text == '/start': state[chat_id] = NEW_USER # set the state # context[chat_id] = user_id # save the user id to context bot.sendMessage( chat_id, text= "Stranger, please enter your group number and I can tell your schedule for week!", ) elif chat_state == NEW_USER and text in GROUPS: state[chat_id] = REGISTERED_USER context[chat_id] = text bot.sendMessage(chat_id=chat_id, text="Dedication passed! Choose day, student", reply_markup=reply_markup) elif chat_state == NEW_USER and text not in GROUPS: bot.sendMessage( chat_id=chat_id, text= " Hey, if you do not tell me your group number, how do I know your schedule? " "Please, tell me your group number...", reply_markup=ReplyKeyboardHide()) elif chat_state == REGISTERED_USER: if text in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ] and chat_context in GROUPS: bot.sendMessage(chat_id=chat_id, text=constract_pretty_shedule_response( chat_context, text), reply_markup=reply_markup) elif text == "LOL": bot.sendMessage(chat_id=chat_id, text=get_random_joke(), reply_markup=reply_markup) else: state[chat_id] = NEW_USER context[chat_id] = None bot.sendMessage( chat_id, text= "Something went wrong , please use /start command to restart our communication", reply_markup=ReplyKeyboardHide())
def cancel_command(self, bot, update): user_id = update.message.from_user.id draft = self.store.get_draft(user_id) if draft: self.store.remove_draft(update.message.from_user.id) bot.sendMessage( update.message.chat_id, text="\U0001F5D1 S'ha cancel·lat la creació de l'excursió.", reply_markup=ReplyKeyboardHide() ) else: bot.sendMessage( update.message.chat_id, text="\u26A0\uFE0F No hi ha res a cancel·lar.\nAquesta comanda només funciona quan s'ha iniciat la creació d'una excursió.", reply_markup=ReplyKeyboardHide() )
def cancel(bot, update): try: del state[update.message.chat_id] finally: bot.sendMessage(update.message.chat_id, text="Current operation canceled", reply_markup=ReplyKeyboardHide(), reply_to_message_id=update.message.message_id)
def settings_error(self, bot, update): chat_id = str(update.message.chat_id) text = update.message.text logging.info('STATS [%s] [settings-error] %s' % (chat_id, text)) txt = ('Parece que hubo un error, usa /help para ver la ayuda ' 'e intenta emplear únicamente los comandos propuestos. ') update.message.reply_text(txt, reply_markup=ReplyKeyboardHide()) return ConversationHandler.END
def nokeyboard(bot, update): db.update_user(update.message.from_user) text = "Keyboard is down." reply_markup = ReplyKeyboardHide() update.message.reply_text(reply_markup=reply_markup, text=text, parse_mode=ParseMode.HTML, disable_web_page_preview=True)
def film_type(bot, update): user = update.message.from_user message = update.message.text if message == 'سریال': update.message.reply_text(''' دایی کدوم سریالو می خوای ؟ ''', reply_markup=ReplyKeyboardHide()) return SERIES elif message == 'فیلم': update.message.reply_text(''' دایی کدوم فیلمو می خوای ''', reply_markup=ReplyKeyboardHide()) return MOVIENAME
def gender(bot, update): user = update.message.from_user logger.info("Gender of %s: %s" % (user.first_name, update.message.text)) update.message.reply_text( 'I see! Please send me a photo of yourself, ' 'so I know what you look like, or send /skip if you don\'t want to.', reply_markup=ReplyKeyboardHide()) return PHOTO
def build_keyboard(self, keyboard): built_keyboard = [] if keyboard: built_keyboard = InlineKeyboardMarkup( [[self._create_keyboard_button(element)] for element in traverse(ast.literal_eval(keyboard))]) else: built_keyboard = ReplyKeyboardHide() return built_keyboard
def reset_chat(bot, update, chat_data, msg_text): '''Сброс режима.''' print('reset_chat msg_text',msg_text) chat_data['cmd'] = '' chat_data['expression'] = '' chat_data['cities'] = {} hide_keyboard = ReplyKeyboardHide() print(hide_keyboard) bot.sendMessage(update.message.chat_id, text=msg_text, reply_markup=hide_keyboard)
def register(bot, update): pytrtbot.writedb(update.message.to_dict()) db = pickledb.load('db/users.db', False) db.set(update.message.from_user.id, REG) db.dump() reply_markup = ReplyKeyboardHide() bot.sendMessage(update.message.chat_id, text='Send your public API Key and API ' + 'secret, with a space between them.', reply_markup=reply_markup)
def start(self, bot, update): chat_id = update.message.chat_id auth_url = self.vk.get_auth_url() # Send first info messages bot.sendMessage(chat_id=chat_id, text=message.WELCOME(auth_url), reply_markup=ReplyKeyboardHide()) bot.sendMessage(chat_id=chat_id, text=message.COPY_TOKEN) # Create new client client = Client(next_action=action.ACCESS_TOKEN, chat_id=chat_id) self.clients[chat_id] = client client.persist()