def what_submodule(): now = datetime.now() if now.weekday() == 6: # if Sunday then random all_submodules = get_all_public_submodules() all_submodules.remove('reddit2telegram') return random.choice(all_submodules) config = get_config() db = pymongo.MongoClient(host=config['db']['host'])[config['db']['name']] settings = db['settings'] if settings.find_one({'setting': SETTING_NAME}) is None: update_promotion_order() setting_result = settings.find_one({'setting': SETTING_NAME}) already_promoted = setting_result['already_promoted'] promotion_order = setting_result['promotion_order'] for submodule in sorted(promotion_order.keys(), key=promotion_order.get, reverse=1): if submodule not in already_promoted: return submodule # If every is promoted. settings.find_one_and_update({'setting': SETTING_NAME}, { '$inc': { 'counter': 1 }, '$set': { 'already_promoted': list() } })
def send_post(submission, r2t): now = datetime.now() today = datetime(now.year, now.month, now.day) taday_date_string = today.strftime('%Y %b %d') random_number = abs( int(hashlib.sha1(taday_date_string.encode('utf-8')).hexdigest(), 16)) # Twice a week update promotion order if (now.weekday() == 5) and (now.hour in [0, 23]) and (now.minute == 1): update_promotion_order() return SupplyResult.STOP_THIS_SUPPLY # If Saturday then no promotion if now.weekday() == 5: return SupplyResult.STOP_THIS_SUPPLY # If weekday or Sunday then regular promotion once a day if (now.weekday() != 5) and ((now.hour == random_number % 24) and (now.minute == random_number % 30)): result = make_nice_submission(submission, r2t, submodule_name_to_promte) if result == SupplyResult.SUCCESSFULLY: if now.weekday() < 5: config = get_config() db = pymongo.MongoClient( host=config['db']['host'])[config['db']['name']] settings = db['settings'] settings.find_one_and_update( {'setting': SETTING_NAME}, {'$push': { 'already_promoted': submodule_name_to_promte }}) return SupplyResult.SUCCESSFULLY return result return SupplyResult.STOP_THIS_SUPPLY
def update_promotion_order(): config = get_config() db = pymongo.MongoClient(host=config['db']['host'])[config['db']['name']] settings = db['settings'] first_date_view = db['view_with_first_dates'] all_submodules = get_all_public_submodules() all_submodules.remove('reddit2telegram') submodules_and_dates = dict() for submodule in all_submodules: imported = importlib.import_module('channels.{}.app'.format(submodule)) channel = imported.t_channel first_date_result = first_date_view.find_one({'_id': channel.lower()}) if first_date_result is None: continue submodules_and_dates[submodule] = first_date_result['first_date'] if settings.find_one({'setting': SETTING_NAME}) is None: settings.insert_one({ 'setting': SETTING_NAME, 'promotion_order': submodules_and_dates, 'already_promoted': list(), 'counter': 0 }) settings.find_one_and_update( {'setting': SETTING_NAME}, {'$set': { 'promotion_order': submodules_and_dates }})
def send_post(submission, r2t): channels_list = get_all_public_channels(r2t) for submodule_name in get_all_public_submodules(): submodule = importlib.import_module( 'channels.{}.app'.format(submodule_name)) channel = submodule.t_channel bd_party, years = is_birthday_today(r2t, channel) if bd_party and years > 0: plural = 's' if years != 1 else '' # To the @r_channels long_sleep() r2t.t_channel = '@r_channels' cakes = '🎂' * years text_to_send = '{cake}\n🎁 Today {channel} is {years_cnt} year{s} old.\n🎉 Congratulations! 🎈'.format( channel=channel, years_cnt=years, s=plural, cake=cakes) r2t.send_text(text_to_send) # To the dev channel long_sleep() r2t.t_channel = get_dev_channel() r2t.send_text(text_to_send) # To the channels itself long_sleep() r2t.t_channel = channel text1_to_send = text_to_send list_of_channels = generate_list_of_channels( channels_list, random_permutation=True) text3_to_send = default_ending() r2t.send_text(text1_to_send) short_sleep() text2_to_send = 'Other @reddit2telegram channels powered by @r_channels:\n' for l in chunker(list_of_channels, 100): text2_to_send += '\n'.join(l) r2t.send_text(text2_to_send) text2_to_send = '' short_sleep() r2t.send_text(text3_to_send) long_sleep() if channel != '@reddit2telegram': config = get_config() send_to_channel_from_subreddit( how_to_post=make_nice_submission, channel_to_post='@reddit2telegram', subreddit=submodule.subreddit, submodule_name_to_promte=submodule_name, submissions_ranking='top', submissions_limit=1000, config=config, extra_args=True, extra_ending=text_to_send) long_sleep() # It's not a proper supply, so just stop. return SupplyResult.STOP_THIS_SUPPLY
def send_post(submission, r2t): now = datetime.now() today = datetime(now.year, now.month, now.day) taday_date_string = today.strftime('%Y %b %d') random_number = abs( int(hashlib.sha1(taday_date_string.encode('utf-8')).hexdigest(), 16)) # Twice a week update promotion order if (now.weekday() == 5) and (now.hour in [0, 23]) and (now.minute == 1): update_promotion_order() return SupplyResult.STOP_THIS_SUPPLY # If Saturday then no promotion if now.weekday() == 5: return SupplyResult.STOP_THIS_SUPPLY # If weekday or Sunday then regular promotion once a day if (now.weekday() != 5) and ((now.hour == random_number % 24) and (now.minute == random_number % 30)): tags = get_tags(submodule_name_to_promte) if tags is not None: if len(tags) > 0: tags_string = ' '.join(tags) submission.title # to make it non-lazy result = r2t.send_simple( submission, channel_to_promote=what_channel(submodule_name_to_promte), date=datetime.utcfromtimestamp( submission.created_utc).strftime('%Y %b %d'), tags=tags_string, text= '{title}\n\n{self_text}\n\n{upvotes} upvotes\n/r/{subreddit_name}\n{date}\n{short_link}\nby {channel_to_promote}\n{tags}', other= '{title}\n{link}\n\n{upvotes} upvotes\n/r/{subreddit_name}\n{date}\n{short_link}\nby {channel_to_promote}\n{tags}', album= '{title}\n{link}\n\n{upvotes} upvotes\n/r/{subreddit_name}\n{date}\n{short_link}\nby {channel_to_promote}\n{tags}', gif= '{title}\n\n{upvotes} upvotes\n/r/{subreddit_name}\n{date}\n{short_link}\nby {channel_to_promote}\n{tags}', img= '{title}\n\n{upvotes} upvotes\n/r/{subreddit_name}\n{date}\n{short_link}\nby {channel_to_promote}\n{tags}' ) if result == SupplyResult.SUCCESSFULLY: if now.weekday() < 5: config = get_config() db = pymongo.MongoClient( host=config['db']['host'])[config['db']['name']] settings = db['settings'] settings.find_one_and_update( {'setting': SETTING_NAME}, {'$push': { 'already_promoted': submodule_name_to_promte }}) return SupplyResult.SUCCESSFULLY return result return SupplyResult.STOP_THIS_SUPPLY
def say_congrats(submodule_name, channel, achievement): short_sleep() config = get_config() submodule = importlib.import_module('channels.{}.app'.format(submodule_name)) subreddit_name = submodule.subreddit send_to_channel_from_subreddit( how_to_post=make_nice_submission, channel_to_post='@reddit2telegram', subreddit=subreddit_name, submodule_name_to_promte=submodule_name, submissions_ranking='top', submissions_limit=1000, config=config, extra_args=True, extra_ending='🏆 Great achievement!\n💪 Milestone of {number} subscribers.'.format( number=achievement ) ) long_sleep()
def say_congrats(submodule_name, channel, achievement): short_sleep() config = get_config() submodule = utils.channels_stuff.import_submodule(submodule_name) subreddit_name = submodule.subreddit send_to_channel_from_subreddit( how_to_post=make_nice_submission, channel_to_post='@reddit2telegram', subreddit=subreddit_name, submodule_name_to_promte=submodule_name, submissions_ranking='top', submissions_limit=1000, config=config, extra_args=True, extra_ending= '🏆 Great achievement!\n💪 Milestone of {number} subscribers.'.format( number=achievement)) short_sleep() bot = utils.Reddit2TelegramSender(submodule.t_channel) bot.forward_last_message_from_the_channel('@reddit2telegram') long_sleep()
def say_congrats(submodule_name, channel, archivement): short_sleep() config = get_config() r2t_main_chat = utils.Reddit2TelegramSender('@r_channels', config) r2t_main_chat.send_text( '🏆 Great achivement!\n💪 {channel} just passed the milestone of {number} subscribers.' .format(channel=channel, number=archivement)) short_sleep() submodule = importlib.import_module( 'channels.{}.app'.format(submodule_name)) subreddit_name = submodule.subreddit send_to_channel_from_subreddit( how_to_post=make_nice_submission, channel_to_post='@reddit2telegram', subreddit=subreddit_name, submodule_name_to_promte=submodule_name, submissions_ranking='top', submissions_limit=1000, config=config, extra_args=True, extra_ending= '🏆 Great achivement!\n💪 Milestone of {number} subscribers.'.format( number=archivement)) long_sleep()
def send_post(submission, r2t): # To check previous achievements config = get_config() db = pymongo.MongoClient(host=config['db']['host'])[config['db']['name']] settings = db['settings'] # Start logging! r2t.send_text('Regular bypass started.') short_sleep() total = { 'channels': 0, 'members': 0, 'admins': 0, 'errors': 0, 'prev_members': 0 } all_submodules = get_all_submodules() number_of_modules = len(all_submodules) # sleep_coef = math.log(450 / number_of_modules) / math.log(2.718281828 / 3.14159) sleep_coef = 2000 / 3 / 2 / number_of_modules channels_stat = dict() for submodule_name in random.sample(all_submodules, k=number_of_modules): short_sleep(sleep_coef) submodule = utils.channels_stuff.import_submodule(submodule_name) channel_name = submodule.t_channel stat_to_store = { 'channel': channel_name.lower(), 'ts': datetime.utcnow(), 'submodule': submodule_name } total['channels'] += 1 try: admins = get_admins_list(r2t, channel_name) stat_to_store['admins'] = admins total['admins'] += len(admins) except Exception as e: total['errors'] += 1 err_to_send = 'Failed to get admins for {channel}.'.format( channel=channel_name) r2t.send_text(err_to_send) logging.error(err_to_send) short_sleep(sleep_coef) try: current_members_cnt = r2t.telegram_bot.get_chat_members_count( chat_id=channel_name) stat_to_store['members_cnt'] = current_members_cnt total['members'] += current_members_cnt prev_members_cnt = get_last_members_cnt(r2t, channel_name) total['prev_members'] += prev_members_cnt channels_stat[channel_name] = { 'prev_cnt': prev_members_cnt, 'curr_cnt': current_members_cnt, 'diff': current_members_cnt - prev_members_cnt, 'perc_diff': (current_members_cnt - prev_members_cnt) / prev_members_cnt } except Exception as e: total['errors'] += 1 err_to_send = 'Failed to get members count for {channel}.'.format( channel=channel_name) r2t.send_text(err_to_send) logging.error(err_to_send) else: # If they pass something special for achievement in GREAT_ACHIEVEMENTS: if (prev_members_cnt < achievement) and (achievement <= current_members_cnt): # Achievement reached r2t.send_text('🏆 {channel}\n{n1} ➡️ {n2}'.format( n1=prev_members_cnt, n2=current_members_cnt, channel=channel_name)) setting_result = settings.find_one( {'setting': SETTING_NAME}) if setting_result is None: set_achievement(submodule_name, channel_name, achievement, settings) elif channel_name.lower( ) not in setting_result['channels']: set_achievement(submodule_name, channel_name, achievement, settings) elif achievement not in setting_result['channels'][ channel_name.lower()]: set_achievement(submodule_name, channel_name, achievement, settings) else: # Was already archived long_sleep() r2t.stats.insert_one(stat_to_store) members_diff = total['members'] - total['prev_members'] perc_diff = round((members_diff / total['prev_members']) * 100, 2) if members_diff < 0: sign = '' elif members_diff == 0: sign = '±' else: sign = '+' text_to_send = 'Ok, regular bypass results.\n\n' text_to_send += '<pre>Active channels: {n}.</pre>\n'.format( n=total['channels']) text_to_send += '<pre>Subscribers: {n}.</pre>\n'.format(n=total['members']) text_to_send += '<pre>Cnt diff: {sign}{diff} ({sign}{perc_diff}%).</pre>\n'.format( n=total['members'], sign=sign, diff=members_diff, perc_diff=perc_diff) text_to_send += '<pre>Admins: {n}.</pre>\n'.format(n=total['admins']) text_to_send += '<pre>Errors during bypass: {n}.</pre>\n'.format( n=total['errors']) text_to_send += '\n<i>See you!</i>' r2t.send_text(text_to_send, parse_mode='HTML') short_sleep() text_to_send = '📈 <b>TOP 5 GAIN</b> 📈\n' top_5_gain = dict( sorted(channels_stat.items(), key=lambda item: item[1]['diff'], reverse=True)[:5]) bottom_5_gain = dict( sorted(channels_stat.items(), key=lambda item: item[1]['diff'])[:5]) for k, v in top_5_gain.items(): if v['diff'] < 0: sign = '' elif v['diff'] == 0: sign = '±' else: sign = '+' text_to_send += '{channel}: {from_cnt} {s}{diff} ({s}{perc_diff}%) → {to_cnt}\n'.format( channel=k, from_cnt=v['prev_cnt'], s=sign, diff=v['diff'], to_cnt=v['curr_cnt'], perc_diff=round(v['perc_diff'] * 100, 2)) r2t.send_text(text_to_send, parse_mode='HTML') short_sleep() text_to_send = '📉 <b>TOP 5 FALL</b> 📉\n' for k, v in bottom_5_gain.items(): if v['diff'] < 0: sign = '' elif v['diff'] == 0: sign = '±' else: sign = '+' text_to_send += '{channel}: {from_cnt} {s}{diff} ({s}{perc_diff}%) → {to_cnt}\n'.format( channel=k, from_cnt=v['prev_cnt'], s=sign, diff=v['diff'], to_cnt=v['curr_cnt'], perc_diff=round(v['perc_diff'] * 100, 2)) r2t.send_text(text_to_send, parse_mode='HTML') # It's not a proper supply, so just stop. return SupplyResult.STOP_THIS_SUPPLY
def send_post(submission, r2t): def say_congrats(submodule_name, channel, achievement): short_sleep() config = get_config() submodule = importlib.import_module('channels.{}.app'.format(submodule_name)) subreddit_name = submodule.subreddit send_to_channel_from_subreddit( how_to_post=make_nice_submission, channel_to_post='@reddit2telegram', subreddit=subreddit_name, submodule_name_to_promte=submodule_name, submissions_ranking='top', submissions_limit=1000, config=config, extra_args=True, extra_ending='🏆 Great achievement!\n💪 Milestone of {number} subscribers.'.format( number=achievement ) ) long_sleep() def set_achievement(submodule_name, channel, achievement): if settings.find_one({'setting': SETTING_NAME}) is None: settings.insert_one({ 'setting': SETTING_NAME, 'channels': { channel.lower(): [achievement] } }) else: current_state = settings.find_one({'setting': SETTING_NAME}) channels = current_state['channels'] if channel.lower() in channels: channels[channel.lower()].append(achievement) else: channels[channel.lower()] = [achievement] settings.find_one_and_update( { 'setting': SETTING_NAME }, { '$set': { 'channels': channels } } ) say_congrats(submodule_name, channel, achievement) # To check previous achievements config = get_config() db = pymongo.MongoClient(host=config['db']['host'])[config['db']['name']] settings = db['settings'] # Start logging! r2t.send_text('Regular bypass started.') short_sleep() total = { 'channels': 0, 'members': 0, 'admins': 0, 'errors': 0, 'prev_members': 0 } all_submodules = get_all_submodules() for submodule_name in random.sample(all_submodules, k=len(all_submodules)): short_sleep(SLEEP_COEF) submodule = importlib.import_module('channels.{}.app'.format(submodule_name)) channel_name = submodule.t_channel stat_to_store = { 'channel': channel_name.lower(), 'ts': datetime.utcnow(), 'submodule': submodule_name } total['channels'] += 1 try: admins = get_admins_list(r2t, channel_name) stat_to_store['admins'] = admins total['admins'] += len(admins) except Exception as e: total['errors'] += 1 err_to_send = 'Failed to get admins for {channel}.'.format(channel=channel_name) r2t.send_text(err_to_send) logging.error(err_to_send) short_sleep(SLEEP_COEF) try: current_members_cnt = r2t.telegram_bot.get_chat_members_count(chat_id=channel_name) stat_to_store['members_cnt'] = current_members_cnt total['members'] += current_members_cnt prev_members_cnt = get_last_members_cnt(r2t, channel_name) total['prev_members'] += prev_members_cnt except Exception as e: total['errors'] += 1 err_to_send = 'Failed to get members count for {channel}.'.format(channel=channel_name) r2t.send_text(err_to_send) logging.error(err_to_send) else: # If they pass something special for achievement in GREAT_ACHIEVEMENTS: if (prev_members_cnt < achievement) and (achievement <= current_members_cnt): # Achievement reached r2t.send_text('🏆 {channel}\n{n1} ➡️ {n2}'.format( n1=prev_members_cnt, n2=current_members_cnt, channel=channel_name )) setting_result = settings.find_one({'setting': SETTING_NAME}) if setting_result is None: set_achievement(submodule_name, channel_name, achievement) elif channel_name.lower() not in setting_result['channels']: set_achievement(submodule_name, channel_name, achievement) elif achievement not in setting_result['channels'][channel_name.lower()]: set_achievement(submodule_name, channel_name, achievement) else: # Was already archived long_sleep() r2t.stats.insert_one(stat_to_store) members_diff = total['members'] - total['prev_members'] perc_diff = round((members_diff / total['prev_members']) * 100, 2) if members_diff < 0: sign = '' elif members_diff == 0: sign = '±' else: sign = '+' text_to_send = 'Ok, regular bypass results.\n\n' text_to_send += '<pre>Active channels: {n}.</pre>\n'.format(n=total['channels']) text_to_send += '<pre>Subscribers: {n}.</pre>\n'.format(n=total['members']) text_to_send += '<pre>Cnt diff: {sign}{diff} ({sign}{perc_diff}%).</pre>\n'.format( n=total['members'], sign=sign, diff=members_diff, perc_diff=perc_diff ) text_to_send += '<pre>Admins: {n}.</pre>\n'.format(n=total['admins']) text_to_send += '<pre>Errors during bypass: {n}.</pre>\n'.format(n=total['errors']) text_to_send += '\n<i>See you!</i>' r2t.send_text(text_to_send, parse_mode='HTML') # It's not a proper supply, so just stop. return SupplyResult.STOP_THIS_SUPPLY