def set_user(bot, update, args, job_queue: JobQueue): if update.message.from_user.id not in [ p.t_id for p in Permission.select(Permission.t_id) ]: update.message.reply_text( "You don't have permission to get issues from this jira-service") return user, _ = User.get_or_create(name=args[0]) user.last_updated = datetime.now() user.save() t_id = update.message.chat_id try: chat = Chat.get(t_id=t_id) except DoesNotExist: chat = Chat.create(t_id=t_id) chat.user = user chat.save() add_job(job_queue, chat) update.message.reply_text('You will get issues notifications from user: ' + user.name)
def test_get_or_create(self): ''' Tests the creation of the object, if necessary. ''' configure_for_unittest() from model import Chat Chat(id=1).save() chat1 = Chat.get_or_create(id=1) chat2 = Chat.get_or_create(id=2)
def test_multiple_returned(self): ''' Tests raise exception with trying to access multiple returned objects with .get(). ''' configure_for_unittest() from model import Chat from neomodel import MultipleNodesReturned Chat(id=1).save() Chat(id=2).save() with self.assertRaises(MultipleNodesReturned): Chat.nodes.get(id__lt=10)
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 default(bot, update): ''' Handles messages that are not commands. ''' chat = Chat.get_or_create(id=update.message.chat_id) if chat.referer.startswith('/subscribe'): update.message.text = ' '.join([chat.referer, update.message.text]) subscribe(bot, update) elif chat.referer.startswith('/unsubscribe'): update.message.text = ' '.join([chat.referer, update.message.text]) unsubscribe(bot, update) elif chat.referer.startswith('/setlanguage'): update.message.text = ' '.join([chat.referer, update.message.text]) setlanguage(bot, update) elif chat.referer.startswith('/rate'): update.message.text = ' '.join([chat.referer, update.message.text]) rate(bot, update) elif chat.referer.startswith('/watch'): pairs = re.findall(r'([a-z]+)([0-9]+)', chat.referer) update.message.text = ( ' %s' % ('' if chat.referer == '/watch' else 'e' if pairs else 's')).join( [chat.referer, update.message.text]) watch(bot, update) else: start(bot, update)
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 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 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 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 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 on_new_chat_member(bot, update, job_queue): chat_id = update.message.chat_id with session_scope() as sess: chat = sess.query(Chat).filter(Chat.id == chat_id).first() if chat is None: chat = Chat(id=chat_id) sess.add(chat) sess.commit() message = chat.on_new_chat_member_message timeout = chat.kick_timeout if timeout != 0: job = job_queue.run_once(on_timeout, timeout * 60, context={ "chat_id": chat_id, "user_id": update.message.new_chat_members[-1].id }) update.message.reply_text(message)
def default(bot, update): ''' Handles messages that are not commands. ''' chat = Chat.get_or_create(id=update.message.chat_id) if chat.referer.startswith('/subscribe'): update.message.text = ' '.join([chat.referer, update.message.text]) subscribe(bot, update) elif chat.referer.startswith('/unsubscribe'): update.message.text = ' '.join([chat.referer, update.message.text]) unsubscribe(bot, update) elif chat.referer.startswith('/setlanguage'): update.message.text = ' '.join([chat.referer, update.message.text]) setlanguage(bot, update) elif chat.referer.startswith('/rate'): update.message.text = ' '.join([chat.referer, update.message.text]) rate(bot, update) elif chat.referer.startswith('/watch'): pairs = re.findall(r'([a-z]+)([0-9]+)', chat.referer) update.message.text = (' %s' % ( '' if chat.referer == '/watch' else 'e' if pairs else 's')).join([ chat.referer, update.message.text]) watch(bot, update) else: start(bot, update)
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 on_new_chat_member(bot, update, job_queue): chat_id = update.message.chat_id user_id = update.message.new_chat_members[-1].id for job in job_queue.jobs(): if job.context['user_id'] == user_id and job.context[ 'chat_id'] == chat_id and job.enabled == True: job.enabled = False job.schedule_removal() with session_scope() as sess: user = sess.query(User).filter(User.chat_id == chat_id, User.user_id == user_id).first() chat = sess.query(Chat).filter(Chat.id == chat_id).first() if chat is None: chat = Chat(id=chat_id) sess.add(chat) sess.commit() if user is not None: update.message.reply_text(chat.on_known_new_chat_member_message) return message = chat.on_new_chat_member_message timeout = chat.kick_timeout if message == constants.skip_on_new_chat_member_message: return message_markdown = mention_markdown(bot, chat_id, user_id, message) msg = update.message.reply_text(message_markdown, parse_mode=telegram.ParseMode.MARKDOWN) if timeout != 0: if timeout >= 10: job = job_queue.run_once(on_notify_timeout, (timeout - constants.notify_delta) * 60, context={ "chat_id": chat_id, "user_id": user_id, "job_queue": job_queue }) job = job_queue.run_once(on_kick_timeout, timeout * 60, context={ "chat_id": chat_id, "user_id": user_id, "message_id": msg.message_id })
def chat(message): if session.get('auth') is not None: chat = Chat(user_id=session['auth']['id'], name=session['auth']['name'], datetime=datetime.now(), content=message['data']) db.session.add(chat) db.session.commit() __emit('show message', { 'name': chat.name, 'data': chat.content }, broadcast=True)
def showlist(bot, update): ''' Returns list of available TV shows. ''' chat = Chat.get_or_create(id=update.message.chat_id) chat.referer = '' chat.save() response_lines = [ unicode(_('List of available TV shows:') + '\n', 'utf-8') ] + [' '.join([unicode(Emoji.BLACK_SMALL_SQUARE if chat in s.subscribers.all() else Emoji.WHITE_SMALL_SQUARE, 'utf-8'), s.title]) for s in sorted(Show.nodes.all(), key=lambda x: x.title)] bot.sendMessage(chat_id=update.message.chat_id, text='\n'.join(response_lines), reply_markup=ReplyKeyboardHide())
def on_hashtag_message(bot, update, user_data, job_queue): if not update.message: update.message = update.edited_message chat_id = update.message.chat_id if "#whois" in update.message.parse_entities(types=['hashtag']).values() \ and len(update.message.text) >= constants.min_whois_length \ and chat_id < 0: user_id = update.message.from_user.id with session_scope() as sess: chat = sess.query(Chat).filter(Chat.id == chat_id).first() if chat is None: chat = Chat(id=chat_id) sess.add(chat) sess.commit() message = chat.on_introduce_message with session_scope() as sess: user = User(chat_id=chat_id, user_id=user_id, whois=update.message.text) sess.merge(user) removed = False for job in job_queue.jobs(): if job.context['user_id'] == user_id and job.context['chat_id'] == chat_id and job.enabled == True: try: bot.delete_message( job.context['chat_id'], job.context['message_id']) except: pass job.enabled = False job.schedule_removal() removed = True if removed: message_markdown = mention_markdown(bot, chat_id, user_id, message) update.message.reply_text( message_markdown, parse_mode=telegram.ParseMode.MARKDOWN) else: on_message(bot, update, user_data=user_data, job_queue=job_queue)
def on_set_introduce_message(bot, update, args): chat_id = update.message.chat_id message = " ".join(args) if not authorize_user(bot, update): # update.message.reply_text(default_messages.on_failed_auth_response) return if message == '': update.message.reply_text(default_messages.on_empty_message) return with session_scope() as sess: chat = Chat(id=chat_id, on_introduce_message=message) sess.merge(chat) update.message.reply_text( default_messages.on_set_introduce_message_response)
def start(bot, update): ''' Returns the standard greeting with a list of commands. ''' chat = Chat.get_or_create(id=update.message.chat_id) chat.referer = '' chat.save() response = (_('You can control me by sending these commands:') + '\n', '/showlist - %s' % _('show list of available TV shows'), '/subscriptions - %s' % _('show active subscriptions'), '/subscribe - %s' % _('subscribe to a TV show'), '/unsubscribe - %s' % _('unsubscribe from a TV show'), '/setlanguage - %s' % _('change language'), '/watch - %s' % _('find any available episode')) bot.sendMessage(chat_id=update.message.chat_id, text='\n'.join(response), reply_markup=ReplyKeyboardHide())
def on_successful_introduce(bot, update, job_queue): if "#whois" in update.message.parse_entities(types=['hashtag']).values(): chat_id = update.message.chat_id user_id = update.message.from_user.id with session_scope() as sess: chat = sess.query(Chat).filter(Chat.id == chat_id).first() if chat is None: chat = Chat(id=chat_id) sess.add(chat) sess.commit() message = chat.on_introduce_message for job in job_queue.jobs(): if job.context['user_id'] == user_id: job.schedule_removal() update.message.reply_text(message)
def showlist(bot, update): ''' Returns list of available TV shows. ''' chat = Chat.get_or_create(id=update.message.chat_id) chat.referer = '' chat.save() response_lines = [ unicode(_('List of available TV shows:') + '\n', 'utf-8') ] + [ ' '.join([ unicode( Emoji.BLACK_SMALL_SQUARE if chat in s.subscribers.all() else Emoji.WHITE_SMALL_SQUARE, 'utf-8'), s.title ]) for s in sorted(Show.nodes.all(), key=lambda x: x.title) ] bot.sendMessage(chat_id=update.message.chat_id, text='\n'.join(response_lines), reply_markup=ReplyKeyboardHide())
def start(bot, update): ''' Returns the standard greeting with a list of commands. ''' chat = Chat.get_or_create(id=update.message.chat_id) chat.referer = '' chat.save() response = ( _('You can control me by sending these commands:') + '\n', '/showlist - %s' % _('show list of available TV shows'), '/subscriptions - %s' % _('show active subscriptions'), '/subscribe - %s' % _('subscribe to a TV show'), '/unsubscribe - %s' % _('unsubscribe from a TV show'), '/setlanguage - %s' % _('change language'), '/watch - %s' % _('find any available episode') ) bot.sendMessage(chat_id=update.message.chat_id, text='\n'.join(response), reply_markup=ReplyKeyboardHide())
def subscriptions(bot, update): ''' Returns active subscriptions of the chat. ''' chat = Chat.get_or_create(id=update.message.chat_id) chat.referer = '' chat.save() if chat.subscriptions.all(): response_lines = [ unicode(_('Active subscriptions:') + '\n', 'utf-8') ] + [' '.join([unicode(Emoji.BLACK_SMALL_SQUARE, 'utf-8'), s.title]) for s in sorted(chat.subscriptions.all(), key=lambda x: x.title)] response = '\n'.join(response_lines) else: response = _('You are not subscribed to any of the series.') bot.sendMessage(chat_id=update.message.chat_id, text=response, reply_markup=ReplyKeyboardHide())
def on_set_kick_timeout(bot, update, args): chat_id = update.message.chat_id if not authorize_user(bot, update): # update.message.reply_text(default_messages.on_failed_auth_response) return try: timeout = int(args[0]) assert timeout >= 0 except: update.message.reply_text( default_messages.on_failed_set_kick_timeout_response) return with session_scope() as sess: chat = Chat(id=chat_id, kick_timeout=timeout) sess.merge(chat) update.message.reply_text( default_messages.on_success_set_kick_timeout_response)
def subscriptions(bot, update): ''' Returns active subscriptions of the chat. ''' chat = Chat.get_or_create(id=update.message.chat_id) chat.referer = '' chat.save() if chat.subscriptions.all(): response_lines = [ unicode(_('Active subscriptions:') + '\n', 'utf-8') ] + [ ' '.join([unicode(Emoji.BLACK_SMALL_SQUARE, 'utf-8'), s.title]) for s in sorted(chat.subscriptions.all(), key=lambda x: x.title) ] response = '\n'.join(response_lines) else: response = _('You are not subscribed to any of the series.') bot.sendMessage(chat_id=update.message.chat_id, text=response, reply_markup=ReplyKeyboardHide())
def on_successful_introduce(bot, update, job_queue): if not update.message: update.message = update.edited_message if "#whois" in update.message.parse_entities(types=['hashtag']).values(): chat_id = update.message.chat_id user_id = update.message.from_user.id with session_scope() as sess: chat = sess.query(Chat).filter(Chat.id == chat_id).first() if chat is None: chat = Chat(id=chat_id) sess.add(chat) sess.commit() message = chat.on_introduce_message with session_scope() as sess: user = User(chat_id=chat_id, user_id=user_id, whois=update.message.text) sess.merge(user) removed = False for job in job_queue.jobs(): if job.context['user_id'] == user_id and job.context[ 'chat_id'] == chat_id and job.enabled == True: try: bot.delete_message(job.context['chat_id'], job.context['message_id']) except: pass job.enabled = False job.schedule_removal() removed = True if removed: update.message.reply_text(message)
def watch(bot, update): ''' Returns a link to the video of episode. ''' def parse(text): matches = [re.search(r'/watch (.+) s(\d+) e(\d+)', text), re.search(r'/watch (.+) s(\d+)', text), re.search(r'/watch (.+)', text)] if not matches[0] is None: show_title, season_number, episode_number = matches[0].group(1,2,3) elif not matches[1] is None: show_title, season_number, episode_number = matches[1].group(1,2) + (None,) elif not matches[2] is None: show_title, season_number, episode_number = (matches[2].group(1), None, None) else: show_title, season_number, episode_number = ('', None, None) return show_title.strip().lower(), season_number, episode_number chat = Chat.get_or_create(id=update.message.chat_id) response, reply_markup = None, ReplyKeyboardHide() if not chat.referer: show_title, season_number, episode_number = parse(update.message.text) else: show_title, season_number, episode_number = parse(chat.referer) if not show_title: show_title = update.message.text[7:].strip().lower() elif not season_number: try: season_number = int(update.message.text.split(chat.referer + ' s')[1]) except ValueError: response = _('Invalide season number.') else: try: episode_number = int(update.message.text.split(chat.referer + ' e')[1]) except ValueError: response = _('Invalid episode number.') if not response: if show_title: try: show = Show.nodes.get(title_lower=show_title) if show.is_available: if season_number: try: season = show.seasons.get(number=season_number) if season.is_available: if episode_number: try: episode = season.episodes.get(number=episode_number) if episode.is_available: response = _('We will send you video soon.') chat.referer = update.message.text VideoFinder(bot=bot, chat_id=update.message.chat_id, episode=episode).start() else: raise DoesNotExist({'episode_number': episode_number}) except DoesNotExist: response = _('This episode is not available.') chat.referer = '' else: response = _('Which episode would you like to see?') chat.referer, l = update.message.text, sorted( [str(ep.number) for ep in season.available_episodes], key=lambda x: int(x)) reply_markup = ReplyKeyboardMarkup( [l[i:i+3] for i in range(0,len(l),3)]) else: raise DoesNotExist({'season_number': season_number}) except DoesNotExist: response = _('This season is not available.') chat.referer = '' else: response = _('Which season would you like to see?') chat.referer, l = update.message.text, sorted( [str(s.number) for s in show.available_seasons], key=lambda x: int(x)) reply_markup = ReplyKeyboardMarkup( [l[i:i+3] for i in range(0,len(l),3)]) else: raise DoesNotExist({'show_title': show_title}) 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() else: response = _('Which TV show would you like to see?') chat.referer = update.message.text bot.sendMessage(chat_id=update.message.chat_id, text=response, reply_markup=reply_markup) chat.save()
def on_message(bot, update, user_data, job_queue): chat_id = update.message.chat_id if chat_id < 0: user_id = update.message.from_user.id if update.message.forward_from: on_forward(bot, update, job_queue) return if not authorize_user(bot, chat_id, user_id) and filter_message( chat_id, update.message.text): bot.delete_message(chat_id, update.message.message_id) message_markdown = mention_markdown(bot, chat_id, user_id, constants.on_filtered_message) for job in job_queue.jobs(): if job.context['user_id'] == user_id and job.context[ 'chat_id'] == chat_id and job.enabled == True: try: bot.delete_message(job.context['chat_id'], job.context['message_id']) except: pass job.enabled = False job.schedule_removal() message = bot.send_message(chat_id, text=message_markdown, parse_mode=telegram.ParseMode.MARKDOWN) bot.kick_chat_member(chat_id, user_id, until_date=datetime.now() + timedelta(seconds=60)) user_id = chat_id action = user_data.get('action') if action is None: return chat_id = user_data["chat_id"] if action == Actions.set_kick_timeout: message = update.message.text try: timeout = int(message) assert timeout >= 0 except: update.message.reply_text( constants.on_failed_set_kick_timeout_response) return with session_scope() as sess: chat = Chat(id=chat_id, kick_timeout=timeout) sess.merge(chat) user_data['action'] = None keyboard = [ [ InlineKeyboardButton('К настройке чата', callback_data=json.dumps({ 'chat_id': chat_id, 'action': Actions.select_chat })), InlineKeyboardButton('К списку чатов', callback_data=json.dumps( {'action': Actions.start_select_chat})) ], ] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text( constants.on_success_set_kick_timeout_response, reply_markup=reply_markup) elif action in [ Actions.set_on_new_chat_member_message_response, Actions.set_notify_message, Actions.set_on_known_new_chat_member_message_response, Actions.set_on_successful_introducion_response, Actions.set_on_kick_message, Actions.set_regex_filter ]: message = update.message.text_markdown with session_scope() as sess: if action == Actions.set_on_new_chat_member_message_response: chat = Chat(id=chat_id, on_new_chat_member_message=message) if action == Actions.set_on_known_new_chat_member_message_response: chat = Chat(id=chat_id, on_known_new_chat_member_message=message) if action == Actions.set_on_successful_introducion_response: chat = Chat(id=chat_id, on_introduce_message=message) if action == Actions.set_notify_message: chat = Chat(id=chat_id, notify_message=message) if action == Actions.set_on_kick_message: chat = Chat(id=chat_id, on_kick_message=message) if action == Actions.set_regex_filter: if message == "%TURN_OFF%": chat = Chat(id=chat_id, regex_filter=None) else: message = update.message.text chat = Chat(id=chat_id, regex_filter=message) sess.merge(chat) user_data['action'] = None keyboard = [ [ InlineKeyboardButton('К настройке чата', callback_data=json.dumps({ 'chat_id': chat_id, 'action': Actions.select_chat })), InlineKeyboardButton('К списку чатов', callback_data=json.dumps( {'action': Actions.start_select_chat})) ], ] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text(constants.on_set_new_message, reply_markup=reply_markup)
def init_bot(job_queue: JobQueue): for chat in Chat.select(Chat): add_job(job_queue, chat)
def on_message(bot, update, user_data): user_id = update.message.chat_id if user_id < 0: return action = user_data.get('action') if action is None: return chat_id = user_data["chat_id"] if action == Actions.set_kick_timeout: message = update.message.text try: timeout = int(message) assert timeout >= 0 except: update.message.reply_text( constants.on_failed_set_kick_timeout_response) return with session_scope() as sess: chat = Chat(id=chat_id, kick_timeout=timeout) sess.merge(chat) user_data['action'] = None keyboard = [ [ InlineKeyboardButton('К настройке чата', callback_data=json.dumps({ 'chat_id': chat_id, 'action': Actions.select_chat })), InlineKeyboardButton('К списку чатов', callback_data=json.dumps( {'action': Actions.start_select_chat})) ], ] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text( constants.on_success_set_kick_timeout_response, reply_markup=reply_markup) elif action in [ Actions.set_on_new_chat_member_message_response, Actions.set_notify_message, Actions.set_on_known_new_chat_member_message_response, Actions.set_on_successful_introducion_response ]: message = update.message.text_markdown with session_scope() as sess: if action == Actions.set_on_new_chat_member_message_response: chat = Chat(id=chat_id, on_new_chat_member_message=message) if action == Actions.set_on_known_new_chat_member_message_response: chat = Chat(id=chat_id, on_known_new_chat_member_message=message) if action == Actions.set_on_successful_introducion_response: chat = Chat(id=chat_id, on_introduce_message=message) if action == Actions.set_notify_message: chat = Chat(id=chat_id, notify_message=message) sess.merge(chat) user_data['action'] = None keyboard = [ [ InlineKeyboardButton('К настройке чата', callback_data=json.dumps({ 'chat_id': chat_id, 'action': Actions.select_chat })), InlineKeyboardButton('К списку чатов', callback_data=json.dumps( {'action': Actions.start_select_chat})) ], ] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text(constants.on_set_new_message, reply_markup=reply_markup)
def watch(bot, update): ''' Returns a link to the video of episode. ''' def parse(text): matches = [ re.search(r'/watch (.+) s(\d+) e(\d+)', text), re.search(r'/watch (.+) s(\d+)', text), re.search(r'/watch (.+)', text) ] if not matches[0] is None: show_title, season_number, episode_number = matches[0].group( 1, 2, 3) elif not matches[1] is None: show_title, season_number, episode_number = matches[1].group( 1, 2) + (None, ) elif not matches[2] is None: show_title, season_number, episode_number = (matches[2].group(1), None, None) else: show_title, season_number, episode_number = ('', None, None) return show_title.strip().lower(), season_number, episode_number chat = Chat.get_or_create(id=update.message.chat_id) response, reply_markup = None, ReplyKeyboardHide() if not chat.referer: show_title, season_number, episode_number = parse(update.message.text) else: show_title, season_number, episode_number = parse(chat.referer) if not show_title: show_title = update.message.text[7:].strip().lower() elif not season_number: try: season_number = int( update.message.text.split(chat.referer + ' s')[1]) except ValueError: response = _('Invalide season number.') else: try: episode_number = int( update.message.text.split(chat.referer + ' e')[1]) except ValueError: response = _('Invalid episode number.') if not response: if show_title: try: show = Show.nodes.get(title_lower=show_title) if show.is_available: if season_number: try: season = show.seasons.get(number=season_number) if season.is_available: if episode_number: try: episode = season.episodes.get( number=episode_number) if episode.is_available: response = _( 'We will send you video soon.') chat.referer = update.message.text VideoFinder( bot=bot, chat_id=update.message.chat_id, episode=episode).start() else: raise DoesNotExist({ 'episode_number': episode_number }) except DoesNotExist: response = _( 'This episode is not available.') chat.referer = '' else: response = _( 'Which episode would you like to see?') chat.referer, l = update.message.text, sorted( [ str(ep.number) for ep in season.available_episodes ], key=lambda x: int(x)) reply_markup = ReplyKeyboardMarkup([ l[i:i + 3] for i in range(0, len(l), 3) ]) else: raise DoesNotExist( {'season_number': season_number}) except DoesNotExist: response = _('This season is not available.') chat.referer = '' else: response = _('Which season would you like to see?') chat.referer, l = update.message.text, sorted( [str(s.number) for s in show.available_seasons], key=lambda x: int(x)) reply_markup = ReplyKeyboardMarkup( [l[i:i + 3] for i in range(0, len(l), 3)]) else: raise DoesNotExist({'show_title': show_title}) 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() else: response = _('Which TV show would you like to see?') chat.referer = update.message.text bot.sendMessage(chat_id=update.message.chat_id, text=response, reply_markup=reply_markup) chat.save()