def create_list_promo(update: Update, context):
    admin_info = get_admin_db(update.effective_user.id)
    if not admin_info.get('groups', []):
        update.effective_message.reply_text(
            "You don't have any groups registered with us")
        """elif context.user_data.get('list created today', 0) >= 4:
		update.effective_message.reply_text("You have reached the limit for list creation today.")"""
    else:
        # Removing this validation for now
        if 1 or valid_create_list(admin_info['groups']):
            update.effective_message.reply_text(
                "Gimme a minute, I'm creating the lists for you")
            if create_list(update, context):
                change_grp_status_db(admin_info['groups'],
                                     STATUS.LIST_PUBLISHED)
                if 'list created today' in context.user_data:
                    context.user_data['list created today'] += 1
                else:
                    context.user_data['list created today'] = 1

                update.effective_message.reply_text(
                    "Shared the lists in channel")

            else:
                update.effective_message.reply_text(
                    "We're facing some difficulties in creating the lists")
        else:
            update.effective_message.reply_text(
                "Current status of your groups doesn't allow creating list"
                "\nIt's either new (or) previous list is not deleted (or) not started registration"
            )
def start_regstr_promo(update: Update, context):
    admin_info = get_admin_db(update.effective_user.id)
    if not admin_info.get('groups', []):
        update.effective_message.reply_text(
            "You don't have any groups registered with us")
    else:
        if valid_open_regstr(admin_info['groups']):
            for grp in admin_info['groups']:
                context.bot.send_message(
                    chat_id=grp,
                    text=new_pin_tx,
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            'Register here',
                            url=f'{context.bot.link}?start={grp}')
                    ]]))
            change_grp_status_db(admin_info['groups'],
                                 STATUS.REGISTRATION_OPEN)
            update.effective_message.reply_text(
                "Registrations are open for all your groups")
        else:
            update.effective_message.reply_text(
                "Current status of your groups doesn't allow opening registration"
                "\nIt's either already open (or) previous list is not deleted yet"
            )
Esempio n. 3
0
def remove_channel(update, context):
    if context.args:
        chnlid = get_admin_db(update.effective_user.id).get('channel id')
        remove_channel_db(chnl_id=chnlid, rem_chnl_id=context.args[0])
        update.effective_message.reply_text("Channel removed successfully")
    else:
        update.effective_message.reply_text("Not enough parameters"
                                            "\nExample: /remove chnlid")
Esempio n. 4
0
def reset_registrations_db(adminid, grps):
    chnlid = get_admin_db(adminid).get('channel id')
    coll = db[chnlid]
    for grp in grps:
        coll.update_many({'in group': grp},
                         {'$set': {
                             'shared on': None,
                             'msgid': None
                         }})
        # coll.update_many({'in group': grp, 'permanent': 1}, {'$set': {'eligible': 1}})
    db.statistics.update_one({'_id': 0},
                             {'$inc': {
                                 'Total Promos Done': len(grps)
                             }})
def add_group(update, context):
	admininfo = get_admin_db(update.effective_user.id)
	if not admininfo.get('groups'):
		update.message.reply_text("You haven't added any groups yet")
		update.message.reply_text("Send 'Register for PromoGroup Admins' > 'Reset All' and start the registration process from the top")
		return ConversationHandler.END
	else:
		update.message.reply_text('Send me the group id')
		update.message.reply_text("To know your group id,"
		                          "\n1. Add me into your group as an admin "
		                          f"\n2. Send /configure@{context.bot.username} in group"
		                          "\n3. Group ID will be sent to your group"
		                          "\n4. Forward me the message", reply_markup = cancel_markup)
		return ADDG
def delete_list_promo(update: Update, context):
    admin_info = get_admin_db(update.effective_user.id)
    if not admin_info.get('groups', []):
        update.effective_message.reply_text(
            "You don't have any groups registered with us")
    else:
        if valid_del_list(admin_info['groups']):
            update.effective_message.reply_text(
                "Gimme a minute, I'm deleting the lists for you")
            delete_lists(update, context)
            change_grp_status_db(admin_info['groups'], STATUS.LIST_DELETED)
            update.effective_message.reply_text(
                "Deleted the lists from the channels")
        else:
            update.effective_message.reply_text(
                "Current status of your groups doesn't allow deleting list"
                "\nIt's either new (or) list is already deleted (or) not started registration"
            )
def group_commands(update, context):
	admininfo = get_admin_db(update.effective_user.id)
	grps = admininfo.get('groups')
	if not grps or not grps[0]:
		update.message.reply_text("You haven't added any groups yet")
		return ConversationHandler.END
	
	elif search('.*Edit', update.message.text):
		context.user_data['edit'] = True
		# kbgrpmenu = [[]] >>>>
	kbgrpmenu = [[]]
	# reserved for future releases >>>>
	'''else:
		context.user_data['edit'] = False
		kbgrpmenu = [[KeyboardButton('All Groups')]]
		context.user_data['channel'] = admininfo.get('channel id')
		context.user_data['channel_username'] = admininfo.get('channel username')
		context.user_data['premium_1'] = admininfo.get('premium_1', [])
		context.user_data['premium_2'] = admininfo.get('premium_2', [])
		context.user_data['premium_3'] = admininfo.get('premium_3', [])'''
	context.user_data['groups'] = []
	context.user_data['adminid'] = update.effective_user.id
	context.user_data['group_dict'] = {}
	for grp in grps:
		if not context.user_data['edit']:
			continue
		context.user_data['groups'].append(grp)
		context.user_data['group_dict'].update({grp: get_groupinfo_db(grp)})
		kbgrpmenu.append([KeyboardButton(str(grp)+' | '+str(context.user_data['group_dict'][grp].get('name')))])
	# reserved for future releases >>>>
	'''if len(kbgrpmenu) < 2:
		update.message.reply_text('Lists have been scheduled/posted in all groups'
		                          '\nWait till it finishes')
		return cancel(update, context)'''
	kbgrpmenu.append([KeyboardButton('/cancel')])
	kbgrpmenu_markup = ReplyKeyboardMarkup(kbgrpmenu, resize_keyboard = True, one_time_keyboard = True)
	context.bot.send_message(chat_id = update.message.chat_id, text = 'Select a Group', reply_markup = kbgrpmenu_markup)
	return SELECT_GROUP
Esempio n. 8
0
def delete_lists(update, context):
    admin_info = get_admin_db(update.effective_user.id)
    for grp in admin_info['groups']:
        to_delete = check_shared_db(chnlid=admin_info['channel id'], grpid=grp)
        failed = f'Deletion Failed:\n'
        if to_delete:
            for chnl in to_delete:
                try:
                    context.bot.delete_message(chat_id=chnl['_id'],
                                               message_id=chnl['msgid'])
                    sleep(0.1)
                except Exception as e:
                    failed += f"\n{chnl['name']} - {e}"
            if len(failed) > 20:
                context.bot.send_message(chat_id=grp, text=failed)
            else:
                context.bot.send_message(
                    chat_id=grp, text=f'All lists deleted successfully')
        else:
            update.message.reply_text(
                f'No one shared the lists in group ({get_groupinfo_db(grp).get("name", "")})'
            )
    reset_registrations_db(update.effective_user.id, admin_info['groups'])
Esempio n. 9
0
def reg_channels_db(adminid, groupid):
    chnlid = get_admin_db(adminid).get('channel id')
    coll = db[chnlid]
    return coll.find({'in group': groupid, 'eligible': 1})
Esempio n. 10
0
def create_list(update: Update, context):
    try:
        admin_info = get_admin_db(update.effective_user.id)
        for grp in admin_info['groups']:
            ''' grp -> Group ID
					grp_info -> Group Dict '''
            grp_info = get_groupinfo_db(grp)
            if grp_info:
                header = grp_info['header']
                footer = grp_info['footer']
                chnls = reg_channels_db(adminid=update.effective_user.id,
                                        groupid=grp)
                chnl_list = []
                for chnl in chnls:
                    chnl_list.append(chnl)
                if not chnl_list:
                    context.bot.send_message(
                        text=
                        f"No Channels registered for the group {grp_info['name']}",
                        chat_id=admin_info['_id'])
                    continue
                chnl_list.sort(key=lambda x: x.get('members count'),
                               reverse=True)

                #################################
                ''' List Creation Logic  '''
                '''   quotient = No of Lists '''

                f = True
                num = MIN_CHNLS_PER_LIST // 2
                quotient = 1
                remain = 0
                total = len(chnl_list)
                if total > MIN_CHNLS_PER_LIST:
                    while f:
                        quotient = total // num
                        remain = total % num
                        if quotient >= remain:
                            f = False
                        else:
                            num += 1
                else:
                    num = total
                num2 = num + 1
                n = 0
                emoticon_1 = choice(list_emojis)
                for g in range(quotient):
                    post = f'*' + e_m(str(header)) + '*\n' + e_m(
                        10 * '━━') + '\n\n'
                    if not remain:
                        num2 = num
                    else:
                        remain -= 1
                    to_send = {}

                    for _ in range(num2):
                        to_send.update({
                            chnl_list[n].get('_id'):
                            chnl_list[n].get('name')
                        })
                        post += f"{emoticon_1}[{chnl_list[n].get('name')[1:]}]({chnl_list[n].get('invitelink')})" \
                                f"\n\t\t\t\t\t\t*{chnl_list[n].get('description')}*\n\n"
                        n += 1

                    if admin_info.get('premium_1', []):
                        post += f"\n\t[{admin_info['premium_1']['text']}]({admin_info['premium_1']['url']})"
                        if admin_info.get('premium_2', []):
                            post += f"\t|\t[{admin_info['premium_2']['text']}]({admin_info['premium_2']['url']})"
                            if admin_info.get('premium_3', []):
                                post += f"\t|\t[{admin_info['premium_3']['text']}]({admin_info['premium_3']['url']})"
                    grpname = context.bot.get_chat(chat_id=grp).title
                    post += f"\n{e_m(10*'━━')}\n[{footer['text']}]({footer['url']})"
                    kb = [[
                        InlineKeyboardButton(text=grpname,
                                             callback_data='prbt_1')
                    ],
                          [
                              InlineKeyboardButton(text='Created by this bot',
                                                   url=context.bot.link)
                          ]]
                    list_link = context.bot.send_message(
                        text=post,
                        chat_id=admin_info['channel id'],
                        parse_mode='Markdown',
                        reply_markup=InlineKeyboardMarkup(kb),
                        disable_web_page_preview=True)
                    if str(type(list_link)).endswith("Promise'>"):
                        list_link = list_link.result()
                    context.user_data['list_link'] = list_link.link
                    list_id = get_next_list_num_db()['Total Lists Created']
                    insert_list_db(list_id=list_id,
                                   grpname=grp_info['name'],
                                   text=post)
                    to_chnl = f"List {g + 1}\n" \
                              f"\t\t⏩ `@PromoAssistant_bot {list_id}`\n\n\t"
                    to_chnl += '\n\t'.join(e_m(v) for v in to_send.values())
                    context.bot.send_message(chat_id=admin_info['channel id'],
                                             text=to_chnl,
                                             parse_mode='Markdown')

                    failed = 'Auto-Posting failed in these Channels::\nShare the list manually\n\n'
                    for chnl in to_send.keys():
                        try:
                            shared = context.bot.send_message(
                                text=post,
                                chat_id=chnl,
                                disable_web_page_preview=True,
                                parse_mode='Markdown')
                            if str(type(shared)).endswith("Promise'>"):
                                shared = shared.result()
                                # Private chnls will have None as link
                            context.bot.send_message(
                                text=f"#shared|{to_send[chnl]}|{shared.link}",
                                chat_id=grp,
                                disable_notification=True,
                                disable_web_page_preview=True)
                            update_shared_db(
                                chnlid=chnl,
                                forwarded_from=admin_info['channel id'],
                                time=shared.date,
                                msgid=shared.message_id)
                            sleep(0.1)  # Cooldown, prevents flooding
                        except:
                            failed += f"{to_send[chnl]}\n"
                            sleep(0.2)  # Cooldown, prevents flooding
                    if len(failed) > 60:
                        context.bot.send_message(text=failed, chat_id=grp)
            context.bot.send_message(text=pub_pin_tx.replace(
                '||', context.user_data['list_link']),
                                     chat_id=grp,
                                     disable_web_page_preview=True)
            log_this(
                f" List created for the admin {admin_info['_id']}\n{admin_info['channel username']}"
            )
        if not admin_info['groups']:
            context.bot.send_message(
                text="You don't have any groups registered",
                chat_id=update.effective_user.id)
    except Exception as e:
        context.bot.send_message(
            chat_id=update.effective_user.id,
            text=f"Error occurred during list creation, \n\n{e}",
            reply_markup=kbmenu_markup)