def update_lang_stat(self): videos = self.db_handler.get_all_videos() for video in videos: if video.title: video.lang = get_lang(video.title) self.db_handler.commit()
def stats(session, speed = None, lang = None): lang = get_lang(lang) word_count = rusty_stats(session) if lang == 'r' else py_stats(session) print SUCCESS, fmt_text('There are {:,} words in your diary!'.format(word_count), 'yellow') speed = 20.0 if not speed else float(speed) print '\n(Assuming an average typing speed of %s words per minute)...' % int(speed) msg = fmt_text("\n Approximate time you've spent on this diary: %s" , 'blue') print msg % fmt_text(time_calc((word_count / speed) * 60), 'green')
def send_welcome(message): User.get_or_create_user(message) lng = get_lang(message) message_keyboard = ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=2) message_keyboard.add(*WORDS[lng]['start_keyboard'].values()) bot.send_message(message.chat.id, Texts.get_text('Greetings', lng), reply_markup=message_keyboard)
def stats(session, speed=None, lang=None): lang = get_lang(lang) word_count = rusty_stats(session) if lang == 'r' else py_stats(session) print SUCCESS, fmt_text( 'There are {:,} words in your diary!'.format(word_count), 'yellow') speed = 20.0 if not speed else float(speed) print '\n(Assuming an average typing speed of %s words per minute)...' % int( speed) msg = fmt_text("\n Approximate time you've spent on this diary: %s", 'blue') print msg % fmt_text(time_calc((word_count / speed) * 60), 'green')
def submit_cart(call): lng = get_lang(call) current_user = User.objects.get(user_id=call.from_user.id) cart = Cart.objects.filter(user=current_user, is_archived=False).first() cart.is_archived = True order_history = OrdersHistory.get_or_create(current_user) order_history.orders.append(cart) bot.send_message(call.message.chat.id, WORDS[lng]['thanks']) cart.save() order_history.save()
def _get_release_notes_uri_query_string(self, dist): q = "?" # get the lang lang = get_lang() if lang: q += "lang=%s&" % lang # get the os os = get_ubuntu_flavor() q += "os=%s&" % os # get the version to upgrade to q += "ver=%s" % dist.version return q
def help_command(bot, update, args): lang = utils.get_lang(data, update.effective_user) if len(args) == 0: update.effective_message.reply_text(tr(lang, 'help')) else: module_name = " ".join(args) if module_name in modloader.DISABLED or module_name in modloader.FAILURE: update.effective_message.reply_text('Module is disabled') elif module_name in modloader.ENABLED: modloader.ENABLED.get(module_name).help(update.effective_message, [], lang) else: update.effective_message.reply_text('Module not found')
def module_list(bot, update): lang = utils.get_lang(data, update.effective_user) modlist = '' for module_name in sorted(modloader.ENABLED): modlist += ' - {0}\n'.format(module_name) fail_modlist = '' for (module_name, e) in sorted(modloader.FAILURE.items()): fail_modlist += ' - {0}: {1}\n'.format(module_name, e) disabled_modlist = '' for module_name in sorted(modloader.DISABLED): disabled_modlist += ' - {0}\n'.format(module_name) update.effective_message.reply_text(tr(lang, 'modules').format(modlist, fail_modlist, disabled_modlist), parse_mode='HTML')
def help(bot, update, args): lang = utils.get_lang(data, update.effective_user) if len(args) == 0: update.effective_message.reply_text(tr(lang, 'help')) else: module_name = " ".join(args) if module_name in modloader.DISABLED or module_name in modloader.FAILURE: update.effective_message.reply_text('Module is disabled') elif module_name in modloader.ENABLED: try: modloader.ENABLED.get(module_name).help(update.effective_message, [], lang) except NotImplementedError: update.effective_message.reply_text('Module developer had not implemented `help()`', parse_mode=ParseMode.MARKDOWN) else: update.effective_message.reply_text('Module not found')
def show_history(message): lng = get_lang(message) current_user = User.objects.get(user_id=message.from_user.id) carts = Cart.objects.filter(user=current_user, is_archived=True) text = '' if not carts: bot.send_message(message.chat.id, WORDS[lng]['history_empty']) return for cart in carts: text += '\n\n' sum_price = 0 if not cart.products: continue for prod in cart.products: text += f'{prod.title} $*{prod.price / 100}* \n' sum_price += prod.price text += f'`{WORDS[lng]["order_sum"]} ${sum_price / 100}` \n' bot.send_message(message.chat.id, text=text, parse_mode='Markdown')
def sub_cat(call): lng = get_lang(call) if bot_messages: bot.delete_message(call.message.chat.id, bot_messages[-1]) subcats_kb = InlineKeyboardMarkup(row_width=2) subcats_buttons = list() category = Category.objects.get(id=call.data.split('_')[1]) for i in category.sub_categories: cb_data = 'category_' + str(i.id) if i.is_parent: cb_data = 'subcategory_' + str(i.id) subcats_buttons.append( InlineKeyboardButton(text=i.get_title(lng), callback_data=cb_data)) subcats_kb.add(*subcats_buttons) t = bot.send_message(call.message.chat.id, text=f'{category.get_title(lng)}:', reply_markup=subcats_kb) bot_messages.append(t.message_id)
def show_cats(message): if bot_messages: bot.delete_message(message.chat.id, bot_messages[-1]) lng = get_lang(message) cats_kb = InlineKeyboardMarkup(row_width=2) cats_buttons = [] all_cats = Category.objects.all() for i in all_cats: if i.is_parent: cb_data = 'subcategory_' + str(i.id) cats_buttons.append( InlineKeyboardButton(text=i.get_title(lng), callback_data=cb_data)) cat_text = WORDS[lng]['cats'] cats_kb.add(*cats_buttons) t = bot.send_message(message.chat.id, text=cat_text, reply_markup=cats_kb, parse_mode='Markdown') bot_messages.append(t.message_id)
def product(call): lng = get_lang(call) medias = list() prod = Product.objects.get(id=call.data.split('_')[1]) # if bot_messages: # c = len(prod.category.category_products) # for i in bot_messages[-c:]: # bot.delete_message(call.message.chat.id, i) for p in prod.photos: medias.append(telebot.types.InputMediaPhoto(p)) product_kb = InlineKeyboardMarkup(row_width=2) product_kb.add( InlineKeyboardButton( text=' \U00002B05 ' + prod.category.get_title(lng), callback_data='category_' + str(prod.category.id)), InlineKeyboardButton(text=WORDS[lng]['text_cart'], callback_data='addtocart_' + str(prod.id))) weight = str(prod.weigth) + WORDS[lng]['g'] if prod.weigth >= 1000: weight = str(prod.weigth / 1000) + WORDS[lng]['kg'] title = f'_{prod.get_title(lng)}_ `$`*{prod.price/100}* \n ' \ f'`{prod.get_description(lng)} \n' \ f'{WORDS[lng]["weight"]} {weight}\n' \ f'{WORDS[lng]["quantity"]} {prod.quantity}`' try: bot.send_media_group(call.message.chat.id, medias) except: bot.send_photo(call.message.chat.id, prod.photos[0]) t = bot.send_message(call.message.chat.id, title, reply_markup=product_kb, parse_mode='Markdown') bot_messages.append(t.message_id)
def show_cart(message): lng = get_lang(message) current_user = User.objects.get(user_id=message.from_user.id) cart = Cart.objects.filter(user=current_user, is_archived=False).first() if not cart: bot.send_message(message.chat.id, WORDS[lng]['empty']) return if not cart.products: bot.send_message(message.chat.id, WORDS[lng]['empty']) sum_cart = 0 for prod in cart.products: text = f'{prod.title} `$`*{prod.price / 100}*' remove_kb = InlineKeyboardMarkup() remove_button = InlineKeyboardButton(text=WORDS[lng]['remove'], callback_data='rmproduct_' + str(prod.id)) remove_kb.add(remove_button) bot.send_message(message.chat.id, text, reply_markup=remove_kb, parse_mode='Markdown') sum_cart += prod.price text = f'`{WORDS[lng]["order_sum"]} ${sum_cart / 100}`\n*{WORDS[lng]["confirm"]}*' submit_kb = InlineKeyboardMarkup() submit_button = InlineKeyboardButton(text=WORDS[lng]['checkout'], callback_data='submit') submit_kb.add(submit_button) bot.send_message(message.chat.id, text, reply_markup=submit_kb, parse_mode='Markdown')
def products_by_cat(call): lng = get_lang(call) if bot_messages: bot.delete_message(call.message.chat.id, bot_messages[-1]) cat = Category.objects.filter(id=call.data.split('_')[1]).first() products = cat.category_products t = bot.send_message(call.message.chat.id, text=f'{cat.get_title(lng)}:') bot_messages.append(t.message_id) for p in products: products_kb = InlineKeyboardMarkup(row_width=2) products_kb.add( InlineKeyboardButton(text=WORDS[lng]['text_cart'], callback_data='addtocart_' + str(p.id)), InlineKeyboardButton(text=WORDS[lng]['text_detals'], callback_data='product_' + str(p.id))) title = f'_{p.get_title(lng)}_ `$`*{p.price/100}*' t = bot.send_photo(call.message.chat.id, p.photos[0], caption=title, reply_markup=products_kb, parse_mode='Markdown') bot_messages.append(t.message_id)
def search(session, word = None, lang = None, start = None, end = None, grep = 7): '''Invokes one of the searching functions and does some useful stuff''' clear_screen() now = datetime.now() def check_date(date): if date in ['today', 'now', 'end']: return now elif date in ['start', 'birthday']: return session.birthday try: return datetime.strptime(date, '%Y-%m-%d') except (TypeError, ValueError): return None sys.stdout.set_mode(1, 0.01) # Phase 1: Get the user input required for searching through the stories word = force_input(word, "\nEnter a word: ", ERROR + ' You must enter a word to continue!') lang = get_lang(lang) start, end = map(check_date, [start, end]) while not all([start, end]): try: print WARNING, 'Enter dates in the form YYYY-MM-DD (Mind you, with hyphen!)\n' if not start: lower_bound = session.birthday start_date = raw_input('Start date (Press [Enter] to begin from the start of your diary): ') start = datetime.strptime(start_date, '%Y-%m-%d') if start_date else session.birthday assert (start >= lower_bound and start <= now), 'S' if not end: lower_bound = start end_date = raw_input("End date (Press [Enter] for today's date): ") end = datetime.strptime(end_date, '%Y-%m-%d') if end_date else now assert (end > lower_bound and end <= now), 'E' except AssertionError as msg: print ERROR, '%s date should be after %s and before %s' % \ (msg, lower_bound.strftime('%b. %d, %Y'), now.strftime('%b. %d, %Y')) if str(msg) == 'S': start = None else: end = None except ValueError: print ERROR, 'Oops! Error in input. Try again...' # Phase 2: Send the datetimes to the respective searching functions print "\nSearching your stories for the word '%s'..." % word search_function = rusty_search if lang == 'r' else py_search try: occurrences, timing = search_function(session, start, end, word) except AssertionError: print ERROR, 'There are no stories in the given location!' return def print_stuff(grep): # function to choose between pretty and ugly printing sys.stdout.set_mode(0) results_begin = '\nSearch results from %s to %s:' % (start.strftime('%B %d, %Y'), end.strftime('%B %d, %Y')) + \ "\n\nStories on these days have the word '%s' in them...\n" % word if grep: # pretty printing the output (at the cost of decrypting time) try: timer_start = timer() print results_begin for i, (n, word_count, indices) in enumerate(occurrences): colored = [] date = start + timedelta(n) content = Story(session, date).decrypt() numbers = str(i + 1) + '. ' + date.strftime('%B %d, %Y (%A)') text, indices = mark_text(content, indices, jump) # precisely indicate the word in text for idx in indices: # find the word occurrences left_bound = find_line_boundary(text, idx, grep, -1) right_bound = find_line_boundary(text, idx, grep, 1) sliced = '\t' + '... ' + text[left_bound:right_bound].strip() + ' ...' colored.append(sliced) print numbers, '\n%s' % '\n'.join(colored) # print the numbers along with the word occurrences timer_stop = timer() except (KeyboardInterrupt, EOFError): sleep(CAPTURE_WAIT) grep = 0 # default back to ugly printing clear_screen() print "Yep, it takes time! Let's go back to the good ol' days..." if not grep: # Yuck, but cleaner way to print the results sys.stdout.set_mode(0) print results_begin for i, (n, word_count, _indices) in enumerate(occurrences): date = session.birthday + timedelta(n) numbers = ' ' + str(i + 1) + '. ' + date.strftime('%B %d, %Y (%A)') spaces = 40 - len(numbers) print numbers, ' ' * spaces, '[ %s ]' % word_count # print only the datetime and counts in each file sys.stdout.set_mode(1, 0.015) msg = fmt_text('Found a total of %d occurrences in %d stories!' % (total_count, num_stories), 'yellow') print '\n%s %s\n' % (SUCCESS, msg) print fmt_text(' Time taken for searching: ', 'blue') + \ fmt_text('%s seconds!' % timing, 'green') if grep: print fmt_text(' Time taken for pretty printing: ', 'blue') + \ fmt_text('%s seconds!' % (timer_stop - timer_start), 'green') # Phase 3: Print the results (in a pretty or ugly way) using the giant function below jump, num_stories = len(word), len(occurrences) total_count = sum(map(lambda stuff: stuff[1], occurrences)) print SUCCESS, 'Done! Time taken: %s seconds! (%d occurrences in %d stories!)' \ % (timing, total_count, num_stories) if not total_count: print ERROR, "Bummer! There are no stories containing '%s'..." % word return print_stuff(grep) # Phase 4: Get the user input and display the stories while occurrences: try: sys.stdout.set_mode(2) print '\nEnter a number to see the corresponding story...' print "\r(Enter 'pretty' or 'ugly' to print those search results again, or press [Enter] to exit)" ch = raw_input('\nInput: ') if ch == 'pretty': clear_screen() print_stuff(grep = 7) # '7' is default, because it looks kinda nice elif ch == 'ugly': clear_screen() print_stuff(grep = 0) elif not ch: return elif int(ch) <= 0: raise ValueError else: n_day, word_count, indices = occurrences[int(ch) - 1] date = start + timedelta(n_day) (data, top, bottom) = Story(session, date).view(return_text = True) sys.stdout.set_mode(3) print top, mark_text(data, indices, jump, 'skyblue')[0], bottom except (ValueError, IndexError): print ERROR, 'Oops! Bad input! Try again...'
def parse(self): self._debug("MetaRelease.parse()") current_dist_name = self.current_dist_name self._debug("current dist name: '%s'" % current_dist_name) current_dist = None dists = [] # parse the metarelease_information file index_tag = apt_pkg.TagFile(self.metarelease_information) step_result = index_tag.step() while step_result: if "Dist" in index_tag.section: name = index_tag.section["Dist"] self._debug("found distro name: '%s'" % name) rawdate = index_tag.section["Date"] date = time.mktime(rfc822.parsedate(rawdate)) supported = int(index_tag.section["Supported"]) version = index_tag.section["Version"] # add the information to a new date object dist = Dist(name, version, date,supported) if "ReleaseNotes" in index_tag.section: dist.releaseNotesURI = index_tag.section["ReleaseNotes"] lang = get_lang() if lang: dist.releaseNotesURI += "?lang=%s" % lang if "ReleaseNotesHtml" in index_tag.section: dist.releaseNotesHtmlUri = index_tag.section["ReleaseNotesHtml"] query = self._get_release_notes_uri_query_string(dist) if query: dist.releaseNotesHtmlUri += query if "UpgradeTool" in index_tag.section: dist.upgradeTool = index_tag.section["UpgradeTool"] if "UpgradeToolSignature" in index_tag.section: dist.upgradeToolSig = index_tag.section["UpgradeToolSignature"] if "UpgradeBroken" in index_tag.section: dist.upgrade_broken = index_tag.section["UpgradeBroken"] dists.append(dist) if name == current_dist_name: current_dist = dist step_result = index_tag.step() # first check if the current runing distro is in the meta-release # information. if not, we assume that we run on something not # supported and silently return if current_dist is None: self._debug("current dist not found in meta-release file\n") return False # then see what we can upgrade to upgradable_to = "" for dist in dists: if dist.date > current_dist.date: upgradable_to = dist self._debug("new dist: %s" % upgradable_to) break # only warn if unsupported and a new dist is available (because # the development version is also unsupported) if upgradable_to != "" and not current_dist.supported: self.dist_no_longer_supported(current_dist) if upgradable_to != "": self.new_dist_available(upgradable_to) # parsing done and sucessfully return True
def about(bot, update): lang = utils.get_lang(data, update.effective_user) update.effective_message.reply_text(tr(lang, 'about').format(config.version))
@bot.message_handler(commands=['start']) def send_welcome(message): User.get_or_create_user(message) lng = get_lang(message) message_keyboard = ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=2) message_keyboard.add(*WORDS[lng]['start_keyboard'].values()) bot.send_message(message.chat.id, Texts.get_text('Greetings', lng), reply_markup=message_keyboard) @bot.message_handler(func=lambda message: message.text == WORDS[get_lang( message)]['start_keyboard']['cats']) def show_cats(message): if bot_messages: bot.delete_message(message.chat.id, bot_messages[-1]) lng = get_lang(message) cats_kb = InlineKeyboardMarkup(row_width=2) cats_buttons = [] all_cats = Category.objects.all() for i in all_cats: if i.is_parent: cb_data = 'subcategory_' + str(i.id) cats_buttons.append( InlineKeyboardButton(text=i.get_title(lng), callback_data=cb_data)) cat_text = WORDS[lng]['cats']
def test_get_lang_kanji(): title = u'文妮,過了今天你可能會爆紅,記得幫我跟邰哥要張簽名好嗎?' lang = get_lang(title) print lang
def parse(self): self._debug("MetaRelease.parse()") current_dist_name = self.current_dist_name self._debug("current dist name: '%s'" % current_dist_name) current_dist = None dists = [] # parse the metarelease_information file index_tag = apt_pkg.TagFile(self.metarelease_information) step_result = index_tag.step() while step_result: if "Dist" in index_tag.section: name = index_tag.section["Dist"] self._debug("found distro name: '%s'" % name) rawdate = index_tag.section["Date"] date = time.mktime(rfc822.parsedate(rawdate)) supported = int(index_tag.section["Supported"]) version = index_tag.section["Version"] # add the information to a new date object dist = Dist(name, version, date, supported) if "ReleaseNotes" in index_tag.section: dist.releaseNotesURI = index_tag.section["ReleaseNotes"] lang = get_lang() if lang: dist.releaseNotesURI += "?lang=%s" % lang if "ReleaseNotesHtml" in index_tag.section: dist.releaseNotesHtmlUri = index_tag.section[ "ReleaseNotesHtml"] query = self._get_release_notes_uri_query_string(dist) if query: dist.releaseNotesHtmlUri += query if "UpgradeTool" in index_tag.section: dist.upgradeTool = index_tag.section["UpgradeTool"] if "UpgradeToolSignature" in index_tag.section: dist.upgradeToolSig = index_tag.section[ "UpgradeToolSignature"] if "UpgradeBroken" in index_tag.section: dist.upgrade_broken = index_tag.section["UpgradeBroken"] dists.append(dist) if name == current_dist_name: current_dist = dist step_result = index_tag.step() # first check if the current runing distro is in the meta-release # information. if not, we assume that we run on something not # supported and silently return if current_dist is None: self._debug("current dist not found in meta-release file\n") return False # then see what we can upgrade to upgradable_to = "" for dist in dists: if dist.date > current_dist.date: upgradable_to = dist self._debug("new dist: %s" % upgradable_to) break # only warn if unsupported and a new dist is available (because # the development version is also unsupported) if upgradable_to != "" and not current_dist.supported: self.dist_no_longer_supported(current_dist) if upgradable_to != "": self.new_dist_available(upgradable_to) # parsing done and sucessfully return True
def start(bot, update): lang = utils.get_lang(data, update.effective_user) update.effective_message.reply_text(tr(lang, 'start'))
def rep_keyboard(message): lng = get_lang(message) if WORDS[lng]['start_keyboard']['news'] in message.text: bot.send_message(message.chat.id, Texts.get_text('news', lng)) if WORDS[lng]['start_keyboard']['info'] in message.text: bot.send_message(message.chat.id, Texts.get_text('info', lng))
def process_update(bot, update): lang = utils.get_lang(self._storage, update.effective_user) callback(update.effective_message, lang)