from __future__ import with_statement  # If you really need this, keep it at the top
import sys
import os
import telebot
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from gina.models import User, Likepostsgroup,Commentspostsgroup,LikesCommentspostsgroup,UserLinks
from gina.database import get_session, init_db
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
# from engagement import has_user_liked_post,has_user_commented_post,has_user_interacted_with_post
import re
import time
from instabot import Bot
from datetime import datetime, timedelta, timezone
from sqlalchemy import func
import os
import sys
from dotenv import load_dotenv
import ast


# send_start_get_links
# Load the .env file
load_dotenv()
access_token =os.getenv("access_token")
likes_group = os.getenv("likes_group")
comments_group = os.getenv("comments_group")
likes_comments_group = os.getenv("likes_comments_group")
likes_group=ast.literal_eval(likes_group)
comments_group=ast.literal_eval(comments_group)
likes_comments_group=ast.literal_eval(likes_comments_group)
print(access_token)
print(likes_group)
print(comments_group)
print(likes_comments_group)
init_db()
session = get_session()
	
bot = telebot.TeleBot(access_token)
bot.set_webhook()

def restart_program():
	"""Restarts the current program"""
	print("Restarting the bot...")
	os.execv(sys.executable, [sys.executable] + sys.argv)
print("going in /start command")  
@bot.message_handler(commands=['start'])
def start_command(message):
	start_command(message)



@bot.message_handler(func=lambda message: True)  # This will handle any text message
def handle_all_messages(message):
	print(type(message.chat.id))
	print(type(likes_group))
	if message.text=="/help":
		help_command(message)
	if message.text=="/list":
		start_command2(message)
	if message.text=="/rules":
		help_command_rules(message)
	# if message.text=="/rules"and not message.chat.id==1443405613:
	#     help_command_rules(message)
	else:
		if message.chat.id == likes_group:
			# print(f"New message in group {message.chat.title}: {message.text}")
			handle_likes_group_message(message)
		if message.chat.id == comments_group:
			print(f"New message in group {message.chat.title}: {message.text}")
			handle_comments_group_message(message)
		if message.chat.id == likes_comments_group and not message.text=='/help':
			print("HI ")
			print(f"New message in group {message.chat.title}: {message.text}")
			handle_likes_and_comments_group_message(message)
		else:
			start_command(message)


def start_command(message):
		print('start_command')
		print(message.text)
		print(message.from_user.id)
		if  not message.text=='/help':
			print(message.chat.id)
			markup = telebot.types.InlineKeyboardMarkup()
			markup.add(telebot.types.InlineKeyboardButton("✅Join Now✅", url="https://t.me/+LvULKGvlIJ80NTU1"))
			markup.add(telebot.types.InlineKeyboardButton(" 🌎Shop 🌎", url="https://t.me/+LvULKGvlIJ80NTU1"))
			markup.add(telebot.types.InlineKeyboardButton("👉 Join All Groups 👈", url="https://t.me/+LvULKGvlIJ80NTU1"))
			markup.add(telebot.types.InlineKeyboardButton(" 🖥Admin🖥", url="https://t.me/+LvULKGvlIJ80NTU1"))
			markup.add(telebot.types.InlineKeyboardButton("🔔Updates 🔔", url="https://t.me/+LvULKGvlIJ80NTU1"))
			markup.add(telebot.types.InlineKeyboardButton("🚫Remove Group ban🚫", url="https://t.me/+LvULKGvlIJ80NTU1"))
			if message.chat.id==1443405613 and not message.text in ['/help','/rules']:
				print("in message.chat.id==1443405613 ")
				bot.send_message(
					message.chat.id,
					'Hey! I am taking care of the groups.✅\n\nYou have successfully started this bot ✅👉.\n\nTo proceed with the engagement, go back and type /list in the group to receive the list you need to engage with.\n\nTo see the help section type /help.\n\nIf you want to know the group rules, type /rules in the group.♥️ \n\nThank you for being part of our community! Happy engaging! ♥️⬇️ Supercharge Your Instagram Presence And Go Viral ⬇️\n\n',reply_markup=markup
				)
			else:
				print('in start else')
				print(message.chat.id)
				if message.chat.id not in [likes_group, comments_group, likes_comments_group]:
					print("sidhu")
					bot.send_message(
						message.from_user.id,
						'Hey! I am taking care of the groups.✅\n\nYou have successfully started this bot ✅👉.\n\nTo proceed with the engagement, go back and type /list in the group to receive the list you need to engage with.\n\nTo see the help section type /help.\n\nIf you want to know the group rules, type /rules in the group.♥️ \n\nThank you for being part of our community! Happy engaging! ♥️⬇️ Supercharge Your Instagram Presence And Go Viral ⬇️\n\n',reply_markup=markup
					)
					bot.delete_message(message.chat.id, message.message_id)
				elif message.chat.id in [likes_group, comments_group, likes_comments_group] and message.text=='/start':
					print("moosewala")
					bot.send_message(
						message.from_user.id,
						'Hey! I am taking care of the groups.✅\n\nYou have successfully started this bot ✅👉.\n\nTo proceed with the engagement, go back and type /list in the group to receive the list you need to engage with.\n\nTo see the help section type /help.\n\nIf you want to know the group rules, type /rules in the group.♥️ \n\nThank you for being part of our community! Happy engaging! ♥️⬇️ Supercharge Your Instagram Presence And Go Viral ⬇️\n\n',reply_markup=markup
					)
					bot.delete_message(message.chat.id, message.message_id)
			
		else:
			if not message.chat.id==1443405613:
				bot.send_message(
							message.chat.id, 
							f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the correct format to use to send your photo is: Dx30 PhotoLink",
						)
				bot.delete_message(message.chat.id, message.message_id)

@bot.message_handler()
def start_command2(message):
	print("start_command")
	print(message.chat.id)
	print(message.text)
	if message.text=="/list" and message.chat.id == likes_group or message.text=="/list" and  message.  chat.id == comments_group or message.text=="/list" and  message.chat.id == likes_comments_group:
		
		keyboard = InlineKeyboardMarkup()
		redirect_button = InlineKeyboardButton(
			"Click here to continue", 
			url=f"https://t.me/@my_tele_insta_bot"
		)
		keyboard.add(redirect_button)
		bot.send_message(
					message.chat.id, 
					f"👈 This bot just sent you in private chat the list of photos you need to engage with!",
					reply_markup=keyboard
				)
		
		bot.delete_message(message.chat.id, message.message_id)
		send_links(message,message.from_user.id)
	elif message.text=="/help":
		help_command(message)
	else:
		print('message.chat.id',message.chat.id)
		if message.text=="/rules" and message.chat.id in [likes_group,comments_group,likes_comments_group]:
			print('in if message.text=="/rules" and message.chat.id == likes_group or message.text=="/rules" and message.chat.id == comments_group or message.text=="/rules" and message.chat.id == likes_comments_group:')
			send_instructions(message)
		if message.chat.id == likes_group:
			print(f"message.chat.id == likes_group")
			handle_likes_group_message(message)
		if message.chat.id == comments_group:
			print(f"message.chat.id == comments_group")
			handle_comments_group_message(message)
		if message.chat.id == likes_comments_group:
			print(f"message.chat.id == likes_comments_group")
			handle_likes_and_comments_group_message(message)
		else:
			print("in else 2")
			print(message.from_user.id)
			if not message.from_user.id==1443405613:
				print(" if not message.from_user.id==1443405613:")
				start_command(message)
		


def help_command(message):
	if not message.chat.id in [likes_group,comments_group,likes_comments_group] :
		print("Received /help command")  
		markup = telebot.types.InlineKeyboardMarkup()
		markup.add(telebot.types.InlineKeyboardButton("✅Join Now✅", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton(" 🌎Shop 🌎", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton("👉 Join All Groups 👈", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton(" 🖥Admin🖥", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton("🔔Updates 🔔", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton("🚫Remove Group ban🚫", url="https://t.me/+LvULKGvlIJ80NTU1"))
		bot.send_message(
			message.chat.id,
			'👋 Hello, and welcome to the HELP SECTION of this bot!\n\n 📋 Main commands of the bot:-\n\n /help | Show this section-\n\n /list | Show the complete list of posts to be engaged-\n\n /rules | Show group rules👮🏻♂\n\n Do you like this bot, and would like to have a custom one for your group?❕ ',reply_markup=markup
		)

@bot.message_handler(commands=['rules'])
def help_command_rules(message):
	if message.text=="/rules" and message.chat.id in [likes_group ,comments_group, likes_comments_group]:
		print("hahahahahaha")
		print(f"New message in group {message.chat.title}: {message.text}")
		send_instructions(message)
	
	elif message.chat.id == likes_group:
		print("HO1")
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_likes_group_message(message)
	elif message.chat.id == comments_group:
		print("HO2")
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_comments_group_message(message)
	elif message.chat.id == likes_comments_group:
		print("HO")
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_likes_and_comments_group_message(message)
	else:
		markup = telebot.types.InlineKeyboardMarkup()
		markup.add(telebot.types.InlineKeyboardButton("✅Join Now✅", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton(" 🌎Shop 🌎", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton("👉 Join All Groups 👈", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton(" 🖥Admin🖥", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton("🔔Updates 🔔", url="https://t.me/+LvULKGvlIJ80NTU1"))
		markup.add(telebot.types.InlineKeyboardButton("🚫Remove Group ban🚫", url="https://t.me/+LvULKGvlIJ80NTU1"))
		bot.send_message(
			message.chat.id,
			'👋 Hello, and welcome to the HELP SECTION of this bot!\n\n 📋 Main commands of the bot:-\n\n /help | Show this section-\n\n /list | Show the complete list of posts to be engaged-\n\n /rules | Show group rules👮🏻♂ \n\nDo you like this bot, and would like to have a custom one for your group?❕ ',reply_markup=markup)

@bot.message_handler(content_types=['new_chat_members'])
def handle_new_member(message):
	print("in handle_new_member")
	if message.chat.id == likes_group:
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_likes_group_member(message)
	elif message.chat.id == comments_group:
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_comments_group_member(message)
		
	elif message.chat.id == likes_comments_group:
		print("Heee")
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_likes_and_comments_group_member(message)
	else:
		print(f"New message in group {message.chat.title}: {message.text}")
		print("in handle_new_member")
		print(message.chat.id)
		new_members = message.new_chat_members
		Getlikes='https://t.me/+x5rX6FR91oVmMjll'
		Getcomments='https://t.me/+wGzJi_gDLpdkNzll'
		Getlikescomments='https://t.me/+PM-zHrHxt0VlNDU1'
		for member in new_members:
			user_id = member.id
			first_name = member.first_name
			last_name = member.last_name or ''
			username = member.username or ''
			
			# Prepare a welcome message with user details
			welcome_message =  f"""🌟 Welcome to our community! 🌟\n\nWe're thrilled to have you with us! Dive into our Instagram Engagement Groups below:\n\n🚫 Please note: Fake and mirror accounts are strictly prohibited🚫\n\n ✅ LIKES \n\n **For getting links to like 30 posts**: {Getlikes} 🚀\n\n\n✅ **For getting links to like 30 posts**: {Getlikes} 🚀\n\n\n**For getting links to like 30 posts**: {Getlikes} 🚀\n\n\n✅ COMMENTS \n\n**For getting links to comment on 30 posts**: {Getcomments}\n\n\n**For getting links to comment on 30 posts**: {Getcomments}\n\n\n✅ LIKES+COMMENTS \n\n**For getting links to likes+comments on 30 posts**:   {Getlikescomments}\n\n\n**For getting links to likes+comments on 30 posts**:     {Getlikescomments}\n\n\nEnjoy engaging with others and making the most of our groups! 🚀"""

			print(welcome_message)
			# Send the welcome message to the group
			# Optional: Print the details to the console
			print(f"New member joined: {first_name} {last_name} (@{username}), User ID: {user_id}")
		bot.send_message(message.chat.id, welcome_message)
		get_user=session.query(User).filter(User.name == first_name).first()
		if not get_user:
			new_user = User(name=first_name)
			session.add(new_user)
			session.commit()
	
		if message.chat.id == likes_group:
			handle_likes_group_member(message)
		elif message.chat.id == comments_group:
			handle_comments_group_member(message)
		elif message.chat.id == likes_comments_group:
			handle_likes_and_comments_group_member(message)
		else:
			print("Unhandled group or type")


@bot.message_handler(content_types=['new_chat_members'])
def handle_likes_group_member(message):
	print("in likes group member")
	print(type(message.chat.id))
	new_members = message.new_chat_members
	for member in new_members:
		user_id = member.id
		first_name = member.first_name
		last_name = member.last_name or ''
		username = member.username or ''
		
		# Prepare a welcome message with user details
		# welcome_message =  f"""Welcome {first_name}"""

		# print(welcome_message)
		# # Send the welcome message to the group
		# bot.send_message(message.chat.id, welcome_message)
		get_user=session.query(User).filter(User.name == first_name).first()
		if get_user:
			print("in if")
			add_user = Likepostsgroup(user_id=get_user.id, name=None)
		else:
			print("in else")
			new_user = User(name=first_name)
			session.add(new_user)
			add_user = Likepostsgroup(user_id=new_user.id)
		session.add(add_user)
		session.commit()
	   
		print(f"New member joined: {first_name} {last_name} (@{username}), User ID: {user_id}")

@bot.message_handler(content_types=['new_chat_members'])
def handle_comments_group_member(message):
	print("Unhandled group or type")
	print("in handle_comments_group_member")
	print(message.chat.id)
	new_members = message.new_chat_members
	for member in new_members:
		user_id = member.id
		first_name = member.first_name
		last_name = member.last_name or ''
		username = member.username or ''
		
		# Prepare a welcome message with user details
		# welcome_message =  f"""Welcome {first_name}"""

		# print(welcome_message)
		# # Send the welcome message to the group
		# bot.send_message(message.chat.id, welcome_message)
		get_user=session.query(User).filter(User.name == first_name).first()
		if get_user:
			print("in if")
			add_user = Commentspostsgroup(user_id=get_user.id, name=None)
		else:
			print("in else")
			new_user = User(name=first_name)
			session.add(new_user)
			add_user = Commentspostsgroup(user_id=new_user.id)
		session.add(add_user)
		session.commit()

		
		# Optional: Print the details to the console
		print(f"New member joined: {first_name} {last_name} (@{username}), User ID: {user_id}")

@bot.message_handler(content_types=['new_chat_members'])
def handle_likes_and_comments_group_member(message):
	print("Unhandled group or type")
	print("in handle_likes_and_comments_group_message")
	print(message.chat.id)
	new_members = message.new_chat_members
	for member in new_members:
		user_id = member.id
		first_name = member.first_name
		last_name = member.last_name or ''
		username = member.username or ''
		
		# Prepare a welcome message with user details
		# welcome_message =  f"""Welcome {first_name}"""

		# print(welcome_message)
		# # Send the welcome message to the group
		# bot.send_message(message.chat.id, welcome_message)
		get_user=session.query(User).filter(User.name == first_name).first()
		if get_user:
			print("in if")
			add_user = LikesCommentspostsgroup(user_id=get_user.id, name=None)
		else:                                          
			print("in else")
			new_user = User(name=first_name)
			session.add(new_user)
			add_user = LikesCommentspostsgroup(user_id=new_user.id)
		session.add(add_user)
		session.commit()

		
		# Optional: Print the details to the console
		print(f"New member joined: {first_name} {last_name} (@{username}), User ID: {user_id}")

@bot.message_handler(content_types=['text'])
def handle_new_member(message):
	print("in handle_new_member")
	print(message.text)
	if message.text=="/rules" and message.chat.id in [likes_group ,comments_group ,likes_comments_group]:
		print("HOEDKD")
		print(f"New message in group {message.chat.title}: {message.text}")
		send_instructions(message)
	
	elif message.chat.id == likes_group:
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_likes_group_message(message)
	elif message.chat.id == comments_group:
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_comments_group_message(message)
	elif message.chat.id == likes_comments_group :
		print("eeeeeeeeeee")
		print(f"New message in group {message.chat.title}: {message.text}")
		handle_likes_and_comments_group_message(message)

# GROUP_ID = int("-4569634225")
# @bot.message_handler(func=lambda message: message.chat.id == int(-4569634225))
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
	if call.data == "list_button":
		send_links(call.message,call.from_user.id)

def cron_message(message):
	markup = telebot.types.InlineKeyboardMarkup()
	markup.add(telebot.types.InlineKeyboardButton("✅ Join Now ✅", url="https://t.me/+LvULKGvlIJ80NTU1"))
	markup.add(telebot.types.InlineKeyboardButton("✅ Shop ✅", url="https://t.me/+LvULKGvlIJ80NTU1"))
	launch_message=bot.send_message(
					message.chat.id, 
					f"Supercharge Your Instagram Presence And Go Viral! 🚀\n✅ Manual generated engagement only\n✅ Rank on hashtags & explore page\n✅ No use of bots or fake accounts\n✅ Up to 500+ automatic or manual reposts per promotion",reply_markup=markup)
	time.sleep(5)
	markup = telebot.types.InlineKeyboardMarkup()
	markup.add(telebot.types.InlineKeyboardButton("✅ Start ✅", url="https://t.me/+LvULKGvlIJ80NTU1"))
	markup.add(telebot.types.InlineKeyboardButton("🚫 Remove Ban 🚫", url="https://t.me/+LvULKGvlIJ80NTU1"))
	launch_message=bot.send_message(
					message.chat.id, 
					f"Launch our credit bot using the button below to earn credits, which can be used to promote your posts in any group of your choice! ✅",reply_markup=markup)
	keyboard = InlineKeyboardMarkup([

						[InlineKeyboardButton("👈Click here for the list👈", callback_data='list_button')],
					
					])
	bot.send_message(
					message.chat.id, 
					f"👈 This bot will send you in private chat the list of posts you need to engage with!",reply_markup=keyboard)
	time.sleep(5)
	# restart_program()


def handle_likes_group_message(message):
	print("handle_likes_group_message")
	# send_start_get_links(message)
	keyboard = InlineKeyboardMarkup()
	redirect_button = InlineKeyboardButton(
		"Click here to continue", 
		url="https://t.me/@my_tele_insta_bot"
	)
	keyboard.add(redirect_button)

	
	get_user = session.query(UserLinks).filter(UserLinks.insta_post_link.isnot(None),UserLinks.user_group=='likes_group').order_by(UserLinks.id.desc()).limit(30).all()
	
	# Prepare the links list
	links = [record.insta_post_link.strip() for record in get_user]
	# links=['https://www.instagram.com/p/C_bIdProGfv','https://www.instagram.com/p/C_cpCduP6wJ','https://www.instagram.com/p/C_cm0dPSFlc','https://www.instagram.com/p/C_cjZUNoaUU','https://www.instagram.com/p/C-vGZp8tSma']
	print(links)
	if "@instagramusername" in message.text  or "https://www.instagram.com/p/xxxxxxxxxxxx/" in message.text :
		not_valid_message=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the link you sent is not valid: Maybe you have a private profile, or your photo has age restrictions",
					)
		bot.delete_message(message.chat.id, message.message_id)
		time.sleep(30)
		bot.delete_message(not_valid_message.chat.id, not_valid_message.message_id)
		send_links(message,message.from_user.id)
	
	elif "Dx @" in message.text:
		print('DX')
		waiting_message=bot.send_message(
		message.chat.id, 
		f"🔎 {message.from_user.first_name} {message.from_user.last_name}, i'm checking if you correctly engaged"
		)
		
		match = re.search(r'@([^ ]+) https://', message.text)
		url_pattern = r'https?://[^\s/$.?#].[^\s]*'
		urls = re.findall(url_pattern, message.text)
		print(urls)
		# today_date=datetie

		check_link = session.query(UserLinks).filter(
			UserLinks.insta_post_link == urls[0],UserLinks.user_group=='likes_group',
			func.date(UserLinks.created_at) == datetime.today().date()
		)

		print('check_link',check_link.all())
		if check_link.all():
			bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			bot.delete_message(message.chat.id, message.message_id)
			just_shared=bot.send_message(
					message.chat.id, 
					f"⚠️ {message.from_user.first_name} {message.from_user.last_name}, You have just shared your link ,please wait for some time to share your link again",
				)
			
			time.sleep(10)
			bot.delete_message(just_shared.chat.id, just_shared.message_id)
		elif match:
			print("in match")
			username = match.group(1)

			user_info = check_user_info(username)
			print(user_info)
			if user_info:
				bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
				bot.delete_message(message.chat.id, message.message_id)
				not_valid_message=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the link you sent is not valid: Maybe you have a private profile, or your photo has age restrictions",
					)
				
				time.sleep(30)
				bot.delete_message(not_valid_message.chat.id, not_valid_message.message_id)
				
				send_links(message,message.from_user.id)
			else:
				
				data=has_user_liked_post(links, username)
				if False in data:
					bot.delete_message(message.chat.id, message.message_id)
					check_link=session.query(UserLinks).filter(UserLinks.insta_post_link == urls[0])
					print(check_link)
					if check_link:
						warn=bot.send_message(message.chat.id, f"Warning Amanpreet Singh, you forgot to engage some posts! You got a warn! You have 10 minutes to engage and remove it! Your post was reposted but not added to the engagement list, resulting in you not receiving any engagement. Start the bot in private to receive the list of posts!")
						time.sleep(15)
						bot.delete_message(warn.chat.id, warn.message_id)
					instructions=bot.send_message(
					message.chat.id, 
					f"Read instructions carefully and like all the posts to get added to the engagement list!")
					time.sleep(5)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					print("after deleting waiting message")

					bot.delete_message(instructions.chat.id, instructions.message_id)
					print("after deleting waiting message")
					send_links(message,message.from_user.id)
					send_instructions(message)
					cron_message(message)
					time.sleep(5)
					
				elif "?" in str(urls):
					print("in elif")
					bot.delete_message(message.chat.id, message.message_id)
					message=bot.send_message(
					message.chat.id, 
					f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, clean your link before posting!\nRemove ?igshid part!")
					time.sleep(10)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					bot.delete_message(message.chat.id, message.message_id)
					cron_message(message)


				else:
					print("False else")
					keyboard = InlineKeyboardMarkup([

						[InlineKeyboardButton("📄Request list📄", callback_data='list_button')],
						[InlineKeyboardButton("✅Join All Our Groups✅", url="https://t.me/+LvULKGvlIJ80NTU1")]
					])
					sender = message.from_user
					print('sender',sender)
					get_user = session.query(User).filter(User.name == sender.first_name).first()

					if get_user:
						# If user exists, create a new UserLinks entry
						new_link = UserLinks(
							user_id=get_user.id,
							insta_post_link=urls[0],
							insta_username=username,
							user_group='likes_group'
						)
					else:
						# If user does not exist, create a new User
						new_user = User(
							name=sender.first_name,
						)
						session.add(new_user)  # Add the new user to the session
						session.commit()  # Commit to save the new user and get the id

						# Now create the UserLinks entry for the new user
						new_link = UserLinks(
							user_id=new_user.id,
							insta_post_link=urls[0],
							insta_username=username,
							user_group='likes_group'
						)

					# Add the new UserLinks to the session and commit
					session.add(new_link)
					session.commit()  # Commit to save the new link
					bot.delete_message(message.chat.id, message.message_id)
					bot.send_message(message.chat.id, f"❤️ Dx30 (@{username})\n 📸 {urls}\n💰️ Earn 30 credits for engaging correctly ",reply_markup=keyboard)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					cron_message(message)

		else:
			print("HAHAH")
			bot.delete_message(message.chat.id, message.message_id)
			bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			cron_message(message)
			send_instructions(message)
			# engage=bot.send_message(
			# 		message.chat.id, 
			# 		f"👈This bot will send you in private chat the list of posts you need to engage with!",
			# 		reply_markup=keyboard
			# 	)
			# bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			# bot.delete_message(engage.chat.id, engage.message_id)
			# send_links(message,message.from_user.id)
			# print("No match found")
	else:
		print('HEEEE')
		if not message.text=='/rules':
			bot.delete_message(message.chat.id, message.message_id)
			# send_instructions(message)
			correct_format=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the correct format to use to send your photo is: Dx30 PhotoLink",
					)
			# bot.delete_message(engage.chat.id, engage.message_id)
			print('send_links(message,message.from_user.id)')
			
			time.sleep(15)
			bot.delete_message(correct_format.chat.id, correct_format.message_id)
			#restart_program()
		else:
			bot.delete_message(message.chat.id, message.message_id)
		# send_links(message,message.from_user.id)
		# bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
@bot.message_handler()
def send_links(message,user_id):
	chat_id=message.chat.id
	print(type(message.text),message.text)
	if not message.text=='/rules':
		if chat_id==likes_group:
			print("likes_group")
			get_user = session.query(UserLinks).filter(UserLinks.insta_post_link.isnot(None),UserLinks.user_group=='likes_group').order_by(UserLinks.id.desc()).limit(30).all()
			print(get_user)
		if chat_id==comments_group:
			print("comments_group")
			get_user = session.query(UserLinks).filter(UserLinks.insta_post_link.isnot(None),UserLinks.user_group=='comment_group').order_by(UserLinks.id.desc()).limit(10).all()
			print(get_user)

		if chat_id==likes_comments_group:
			print("likes_comments_group")
			get_user =session.query(UserLinks).filter(UserLinks.insta_post_link.isnot(None),UserLinks.user_group=='likes_comments_group').order_by(UserLinks.id.desc()).limit(10).all()
			print(get_user)
			
		# Prepare the links list
		links = [record.insta_post_link for record in get_user]
		print(links)
		# Create the formatted message
		formatted_links = "\n\n".join(f"{i+1}){link}" for i, link in enumerate(links))
		message_text = (
			"⚠️ Engage with the following posts to get successfully added to the engagement list, then go back and post your link into the group! 👇🏻\n\n"

			f"{formatted_links}\n\n\n📌 After completing the list you can drop your link into the group. Use the button below to get back to the group."
		)
		chat = bot.get_chat(message.chat.id)
		if chat.invite_link:
			invite_link = chat.invite_link
		keyboard = InlineKeyboardMarkup()
		group_button = InlineKeyboardButton(f"👥{message.chat.title}👥", url=invite_link)
		keyboard.add(group_button)
		print(message.from_user.id)
		print("I have reached here")
		bot.send_message(
			user_id, 
			message_text,
			reply_markup=keyboard)
		cron_message(message)
		# bot.polling(none_stop=True, interval=0)
		#restart_program()

def handle_comments_group_message(message):  
	keyboard = InlineKeyboardMarkup()
	redirect_button = InlineKeyboardButton(
		"Click here to continue", 
		url=f"https://t.me/@my_tele_insta_bot"
	)
	keyboard.add(redirect_button)

	
	get_user = session.query(UserLinks).filter(UserLinks.insta_post_link.isnot(None),UserLinks.user_group=='comment_group').order_by(UserLinks.id.desc()).limit(10).all()
	
	# Prepare the links list
	links = [record.insta_post_link.strip() for record in get_user]
	# links=['https://www.instagram.com/p/C_bIdProGfv','https://www.instagram.com/p/C_cpCduP6wJ','https://www.instagram.com/p/C_cm0dPSFlc','https://www.instagram.com/p/C_cjZUNoaUU','https://www.instagram.com/p/C-vGZp8tSma']
	print(links)
	if message.text in ["@instagramusername" , "https://www.instagram.com/p/xxxxxxxxxxxx/"]:
		not_valid_message=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the link you sent is not valid: Maybe you have a private profile, or your photo has age restrictions",
					)
		bot.delete_message(message.chat.id, message.message_id)
		time.sleep(30)
		bot.delete_message(not_valid_message.chat.id, not_valid_message.message_id)
		send_links(message,message.from_user.id)
	
	elif "Dx @" in message.text:
		waiting_message=bot.send_message(
		message.chat.id, 
		f"🔎 {message.from_user.first_name} {message.from_user.last_name}, i'm checking if you correctly engaged"
		)
		
		match = re.search(r'@([^ ]+) https://', message.text)
		url_pattern = r'https?://[^\s/$.?#].[^\s]*'
		urls = re.findall(url_pattern, message.text)
		print(urls)
		# Find all URLs in the text
		check_link = session.query(UserLinks).filter(
			UserLinks.insta_post_link == urls[0],UserLinks.user_group=='comment_group',
			func.date(UserLinks.created_at) == datetime.today().date()
		)

		print('check_link',check_link.all())
		if check_link.all():
			bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			bot.delete_message(message.chat.id, message.message_id)
			just_shared=bot.send_message(
					message.chat.id, 
					f"⚠️ {message.from_user.first_name} {message.from_user.last_name}, You have just shared your link ,please wait for some time to share your link again",
				)
			
			time.sleep(10)
			bot.delete_message(just_shared.chat.id, just_shared.message_id)
		
		elif match:
			print("in match")
			username = match.group(1)

			user_info = check_user_info(username)
			print(user_info)
			if user_info:
				bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
				bot.delete_message(message.chat.id, message.message_id)
				not_valid_message=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the link you sent is not valid: Maybe you have a private profile, or your photo has age restrictions",
					)
				
				time.sleep(30)
				bot.delete_message(not_valid_message.chat.id, not_valid_message.message_id)
				send_links(message,message.from_user.id)
			else:
				
				data=has_user_commented_post(links, username)
				if False in data:
					

					bot.delete_message(message.chat.id, message.message_id)
					check_link=session.query(UserLinks).filter(UserLinks.insta_post_link == urls[0])
					print(check_link)
					if check_link:
						warn=bot.send_message(message.chat.id, f"Warning Amanpreet Singh, you forgot to engage some posts! You got a warn! You have 10 minutes to engage and remove it! Your post was reposted but not added to the engagement list, resulting in you not receiving any engagement. Start the bot in private to receive the list of posts!")
						time.sleep(15)
						bot.delete_message(warn.chat.id, warn.message_id)
					instructions=bot.send_message(
					message.chat.id, 
					f"Read instructions carefully and comment all the posts to get added to the engagement list!")
					time.sleep(5)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					bot.delete_message(instructions.chat.id, instructions.message_id)
					send_links(message,message.from_user.id)
					send_instructions(message)
					cron_message(message)
					time.sleep(5)
					
					# bot.send_message(
					# 	message.chat.id, 
					# 	f"👈This bot will send you in private chat the list of posts you need to engage with!",
					# 	reply_markup=keyboard
					# )
					
					# bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
				elif "?" in str(urls):
					print("in elif")
					bot.delete_message(message.chat.id, message.message_id)
					message=bot.send_message(
					message.chat.id, 
					f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, clean your link before posting!\nRemove ?igshid part!")
					time.sleep(10)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					bot.delete_message(message.chat.id, message.message_id)
					cron_message(message)



				else:
					print("False else")
					keyboard = InlineKeyboardMarkup([

						[InlineKeyboardButton("📄Request list📄", callback_data='list_button')],
						[InlineKeyboardButton("✅Join All Our Groups✅", url="https://t.me/+LvULKGvlIJ80NTU1")]
					])
					sender = message.from_user
					get_user = session.query(User).filter(User.name == sender.first_name).first()
					

					

					if get_user:
						# If user exists, create a new UserLinks entry
						new_link = UserLinks(
							user_id=get_user.id,
							insta_post_link=urls[0],
							insta_username=username,
							user_group='comment_group'
						)
					else:
						# If user does not exist, create a new User
						new_user = User(
							name=sender.first_name,
						)
						session.add(new_user)  # Add the new user to the session
						session.commit()  # Commit to save the new user and get the id

						# Now create the UserLinks entry for the new user
						new_link = UserLinks(
							user_id=new_user.id,
							insta_post_link=urls[0],
							insta_username=username,
							user_group='comment_group'
						)

					# Add the new UserLinks to the session and commit
					session.add(new_link)
					session.commit()  # Commit to save the new link
					
					bot.delete_message(message.chat.id, message.message_id)
					bot.send_message(message.chat.id, f"✅Dx30 ({urls[0]})\n💬 Write meaningful comments to support each other\n📩 Report users who spam the same or inappropriate comments",reply_markup=keyboard)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					cron_message(message)

		else:
			bot.delete_message(message.chat.id, message.message_id)
			bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			send_links(message,message.from_user.id)
			cron_message(message)
			send_instructions(message)

			# engage=bot.send_message(
			# 		message.chat.id, 
			# 		f"👈This bot will send you in private chat the list of posts you need to engage with!",
			# 		reply_markup=keyboard
			# 	)
			# bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			# send_links(message,message.from_user.id)
			# # print("No match found")
	else:
		if not message.text=='/rules':
			bot.delete_message(message.chat.id, message.message_id)
			# send_instructions(message)
			correct_format=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the correct format to use to send your photo is: Dx30 PhotoLink",
					)
			time.sleep(15)
			bot.delete_message(correct_format.chat.id, correct_format.message_id)
		bot.delete_message(message.chat.id, message.message_id)


def handle_likes_and_comments_group_message(message):
	   
	keyboard = InlineKeyboardMarkup()
	redirect_button = InlineKeyboardButton(
		"Click here to continue", 
		url=f"https://t.me/@my_tele_insta_bot"
	)
	keyboard.add(redirect_button)

	get_user = session.query(UserLinks).filter(UserLinks.insta_post_link.isnot(None),UserLinks.user_group=='likes_comments_group').order_by(UserLinks.id.desc()).limit(10).all()
	
	# Prepare the links list
	links = [record.insta_post_link.strip() for record in get_user]
	# links=['https://www.instagram.com/p/C_bIdProGfv','https://www.instagram.com/p/C_cpCduP6wJ','https://www.instagram.com/p/C_cm0dPSFlc','https://www.instagram.com/p/C_cjZUNoaUU','https://www.instagram.com/p/C-vGZp8tSma']
	print(links)
	if "@instagramusername" in message.text  or "https://www.instagram.com/p/xxxxxxxxxxxx/" in message.text:
		not_valid_message=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the link you sent is not valid: Maybe you have a private profile, or your photo has age restrictions",
					)
		bot.delete_message(message.chat.id, message.message_id)
		time.sleep(30)
		bot.delete_message(not_valid_message.chat.id, not_valid_message.message_id)
		send_links(message,message.from_user.id)
	
	elif "Dx @" in message.text:
		waiting_message=bot.send_message(
		message.chat.id, 
		f"🔎 {message.from_user.first_name} {message.from_user.last_name}, i'm checking if you correctly engaged"
		)
		
		match = re.search(r'@([^ ]+) https://', message.text)
		url_pattern = r'https?://[^\s/$.?#].[^\s]*'
		urls = re.findall(url_pattern, message.text)
		print(urls)
		# Find all URLs in the text
		check_link = session.query(UserLinks).filter(
			UserLinks.insta_post_link == urls[0],UserLinks.user_group=='likes_comments_group',
			func.date(UserLinks.created_at) == datetime.today().date()
		)

		print('check_link',check_link.all())
		if check_link.all():
			bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			bot.delete_message(message.chat.id, message.message_id)
			just_shared=bot.send_message(
					message.chat.id, 
					f"⚠️ {message.from_user.first_name} {message.from_user.last_name}, You have just shared your link ,please wait for some time to share your link again",
				)
			
			time.sleep(10)
			bot.delete_message(just_shared.chat.id, just_shared.message_id)
		elif match:
			print("in match")
			username = match.group(1)

			user_info = check_user_info(username)
			print(user_info)
			if user_info:
				bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
				bot.delete_message(message.chat.id, message.message_id)
				not_valid_message=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the link you sent is not valid: Maybe you have a private profile, or your photo has age restrictions",
					)
				
				time.sleep(30)
				bot.delete_message(not_valid_message.chat.id, not_valid_message.message_id)
				send_links(message,message.from_user.id)
			else:
				
				data=has_user_liked_post(links, username)
				username = match.group(1)
				data=has_user_interacted_with_post(links, username)
				if False in data:
					bot.delete_message(message.chat.id, message.message_id)
					check_link=session.query(UserLinks).filter(UserLinks.insta_post_link == urls[0])
					print(check_link)
					if check_link:
						warn=bot.send_message(message.chat.id, f"Warning Amanpreet Singh, you forgot to engage some posts! You got a warn! You have 10 minutes to engage and remove it! Your post was reposted but not added to the engagement list, resulting in you not receiving any engagement. Start the bot in private to receive the list of posts!")
						time.sleep(15)
						bot.delete_message(warn.chat.id, warn.message_id)
					instructions=bot.send_message(
					message.chat.id, 
					f"Read instructions carefully and comment all the posts to get added to the engagement list!")
					time.sleep(5)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					bot.delete_message(instructions.chat.id, instructions.message_id)
					send_links(message,message.from_user.id)
					time.sleep(5)
					send_instructions(message)
				elif "?" in str(urls):
					print("in elif")
					bot.delete_message(message.chat.id, message.message_id)
					message=bot.send_message(
					message.chat.id, 
					f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, clean your link before posting!\nRemove ?igshid part!")
					time.sleep(10)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					bot.delete_message(message.chat.id, message.message_id)


				else:
					print("False else")
					keyboard = InlineKeyboardMarkup([

						[InlineKeyboardButton("📄Request list📄", callback_data='list_button')],
						[InlineKeyboardButton("✅Join All Our Groups✅", url="https://t.me/+LvULKGvlIJ80NTU1")]
					])
					sender = message.from_user
					print('sender',sender)
					get_user = session.query(User).filter(User.name == sender.first_name).first()

					if get_user:
						# If user exists, create a new UserLinks entry
						new_link = UserLinks(
							user_id=get_user.id,
							insta_post_link=urls[0],
							insta_username=username,
							user_group='likes_comments_group'
						)
					else:
						# If user does not exist, create a new User
						new_user = User(
							name=sender.first_name,
						)
						session.add(new_user)  # Add the new user to the session
						session.commit()  # Commit to save the new user and get the id

						# Now create the UserLinks entry for the new user
						new_link = UserLinks(
							user_id=new_user.id,
							insta_post_link=urls[0],
							insta_username=username,
							user_group='likes_comments_group'
						)

					# Add the new UserLinks to the session and commit
					session.add(new_link)
					session.commit()  # Commit to save the new link
					bot.delete_message(message.chat.id, message.message_id)
					bot.send_message(message.chat.id, f"✅ Dx30 ({username})\n📸 {urls[0]}\n💰️ Earn 25 credits for engaging correctly \n(@EngagementRewardBot)",reply_markup=keyboard)
					bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
					cron_message(message)

		else:
			bot.delete_message(message.chat.id, message.message_id)
			# send_instructions(message)
			bot.delete_message(waiting_message.chat.id, waiting_message.message_id)
			cron_message(message)
			send_instructions(message)

			# engage=bot.send_message(
			# 		message.chat.id, 
			# 		f"👈This bot will send you in private chat the list of posts you need to engage with!",
			# 		reply_markup=keyboard
			# 	)
			# bot.delete_message(waiting_message.chat.id, waiting_message.message_id)  
			# send_links(message,message.from_user.id)
			# print("No match found")
	else:
		if not message.text=='/rules':
			bot.delete_message(message.chat.id, message.message_id)
			# send_instructions(message)
			correct_format=bot.send_message(
						message.chat.id, 
						f"⚠️ Warning {message.from_user.first_name} {message.from_user.last_name}, the correct format to use to send your photo is: Dx30 PhotoLink",
					)
			time.sleep(15)
			bot.delete_message(correct_format.chat.id, correct_format.message_id)
			# bot.delete_message(engage.chat.id, engage.message_id)
			# print('send_links(message,message.from_user.id)')
			# send_links(message,message.from_user.id)
		bot.delete_message(message.chat.id, message.message_id)









		


def send_instructions(message):
	print("Received /rules command")  
	markup = telebot.types.InlineKeyboardMarkup()
	markup.add(telebot.types.InlineKeyboardButton("✅Join Now✅", url="https://t.me/+LvULKGvlIJ80NTU1"))
	bot.send_message(
		message.from_user.id,
		'1️⃣ Start @my_tele_insta_bot (Click on Send Message, Click Start)\n2️⃣ Go back to this group and type /list to get your links to catchup\n3️⃣ Engage with all the Instagram links the bot sent you\n4️⃣ When you are done, you can post your link in the following format:\n\n\nDx @instagramusername\nhttps://www.instagram.com/p/xxxxxxxxxxxx/\n\n⚠️ONLY users who engaged correctly will be added to the engagement list. If you do not engage correctly, our bot will repost your post but not add it to the engagement list. If you forgot to catch up on some posts, this chat will give you the list of missed posts!⚠️\n✖️  Dx means „Done x“\n✖️ Follow all of these rules to prevent getting warned and banned\n✖️ 5 warns results in a ban\n✖️ Make sure your account is public\n✖️ Make sure your link and username are valid\n✖️ Be kind to everyone',reply_markup=markup)
	bot.delete_message(message.chat.id, message.message_id)

if __name__ == "__main__":
	print(f"Bot is starting...")
	bot.polling(none_stop=True, interval=0)