import telebot
import os
import logging
from telebot import types
import openai
from flask import Flask, request
import time





# Logging
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)

ADMIN_ID = '6011835055'  # Define the admin ID as a string
ADMIN_PASSWORD = 'neriya019283'  # Define the password as a string
bot = telebot.TeleBot("6438598259:AAHwhokFdMUYDk6AKDS0-yDOjnIUayLVY0U")

logged_in = False
banned_users = []  # List to keep track of banned users
unban_requests = {}  # Dictionary to keep track of unban requests

@bot.message_handler(func=lambda message: any(letter in message.text for letter in ["ا", "ب", "ت", "ث", "ج", "ح", "خ", "د", "ذ", "ר", "ز", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق", "ك", "ل", "م", "ن", "ه", "و", "ي", "ة", "🇵🇸"]))
def delete_and_ban(message):
    try:
        bot.delete_message(message.chat.id, message.message_id)
        bot.kick_chat_member(message.chat.id, message.from_user.id)
        banned_users.append(message.from_user.id)  # Add user to banned list
    except telebot.apihelper.ApiException as e:
        print(e)

@bot.message_handler(commands=['dp'])
def request_unban(message):
    if message.from_user.id in banned_users:
        unban_requests[message.from_user.id] = message.text  # Add unban request
        bot.send_message(ADMIN_ID, f"המשתמש: {message.from_user.id} מבקש לצאת מרשימת החסומים📜. אנא אשר על ידי תגובה להודעה זו, עם הפקודה: /okd. 👨‍⚖️")

@bot.message_handler(commands=['okd'])
def approve_unban(message):
    if logged_in and message.reply_to_message:
        user_id = int(message.reply_to_message.text.split()[1])
        if user_id in unban_requests:
            banned_users.remove(user_id)  # Remove user from banned list
            del unban_requests[user_id]  # Remove unban request
            bot.send_message(user_id, "הוסרת מרשימת החסומים בהצלחה!! ✅")







# Admin password
@bot.message_handler(func=lambda msg: msg.text == 'neriya019283')  
def admin_panel(message):
    if message.from_user.id == str(ADMIN_ID):  # Check if the user is the admin
        bot.reply_to(message, "שלום מנהל, אתה כעת בפאנל הניהול.")
    else:
        bot.reply_to(message, "מצטער, אתה לא מנהל.")



@bot.message_handler(commands=['login'])
def login(message):
    global logged_in
    sent_password = ' '.join(message.text.split()[1:])  # Get the text after '/login'
    if str(message.from_user.id) == str(ADMIN_ID) and sent_password == ADMIN_PASSWORD:
        bot.reply_to(message, "התחברת בהצלחה!")
        logged_in = True
    else:
        bot.reply_to(message, "סיסמה שגויה או שאינך מנהל.")





ADMIN_ID = 6011835055
ADMIN_PASSWORD = 'neriya019283'

@bot.message_handler(commands=['settings'])
def send_settings(message):
    if message.from_user.id == ADMIN_ID:
        keyboard = types.InlineKeyboardMarkup()
        key_1 = types.InlineKeyboardButton(text='📝😌רשימת החסומים בבוט', callback_data='blockedusers')
        keyboard.add(key_1)
        key_2 = types.InlineKeyboardButton(text='הגדרה 2', callback_data='setting_2')
        keyboard.add(key_2)
        key_3 = types.InlineKeyboardButton(text='🚨!!כיבוי חירום🚨', callback_data='shutdown')
        keyboard.add(key_3)
        bot.send_message(message.chat.id, "לפקודתך אדוני המנהל!! 🫡. אני שולח לך את ההגדרות בפרטי, לשמור על הפרטיות✨🔍")
        bot.send_message(ADMIN_ID, "שלום אדוני המנהל!👨‍💼😃 אתה הבוס🫡😇. איזה הגדרות אתה צריך?😁", reply_markup=keyboard)

@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    if call.data == "blockedusers":
        blocked_users_str = ', '.join(str(id) for id in banned_users)
        bot.send_message(call.message.chat.id, f"רשימת המשתמשים החסומים: {blocked_users_str}")
    elif call.data == "setting_2":
        # פה אתה יכול להוסיף את הפקודות שאתה רוצה שהמנהל יוכל לבצע
        pass
    elif call.data == "shutdown":
        bot.stop_polling()






@bot.message_handler(commands=['ניהול'])
def send_group_settings(message):
    if message.chat.type == "group" or message.chat.type == "supergroup": # בדיקה אם המשתמש הוא מנהל של קבוצה
        if bot.get_chat_member(message.chat.id, message.from_user.id).status in ["creator", "administrator"]: # בדיקה אם המשתמש הוא מנהל של הקבוצה
            keyboard = types.InlineKeyboardMarkup(row_width=2) # יצירת תפריט כפתורים
            # יצירת כפתורים להגדרות של הקבוצה
            key_1 = types.InlineKeyboardButton("חסימת קישורים", callback_data='block_links')
            key_2 = types.InlineKeyboardButton("מחיקת מילים רעות", callback_data='delete_bad_words')
            key_3 = types.InlineKeyboardButton("מחיקת סטיקרים", callback_data='delete_stickers')
            # ... תוסיף כאן עוד כפתורים לפי הצורך
            keyboard.add(key_1, key_2, key_3) # הוספת הכפתורים לתפריט
            bot.send_message(message.chat.id, "הגדרות הקבוצה נשלחו למנהל בפרטי✅")
            bot.send_message(message.from_user.id, "שלום מנהל! איזה הגדרות אתה צריך?", reply_markup=keyboard) # שליחת הודעה למנהל עם התפריט
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    if call.message:
        if call.data == 'block_links':
            bot.send_message(call.message.chat.id, "הפקודה לחסימת קישורים הופעלה")
        elif call.data == 'delete_bad_words':
            bot.send_message(call.message.chat.id, "הפקודה למחיקת מילים רעות הופעלה")
        elif call.data == 'delete_stickers':
            bot.send_message(call.message.chat.id, "הפקודה למחיקת סטיקרים הופעלה")
        # ... תוסיף כאן עוד פקודות לפי הצורך







bad_words = ["זין", "שית", "פאק", "שרמוטה", "זונה", "מנייאק", "מניאק", "כוסאימאישך", "כוס אימא", "כוס אמא", "כוסאמאשך", "כוסאמאשלך", "כוסאימאשלך", "חרא", "בן אלף","פאק", "ח", "תזדיין", "זדיין", "תזדין", "זדין", "זרג", "סקס", "*****", "זייו", "ציצי", "בן אלף", "בן ***", "שוכב עליי", "שוכבת עליי"]

@bot.message_handler(func=lambda message: check_bad_words(message, bad_words))
def delete_message(message):
  bot.delete_message(chat_id=message.chat.id,  
                    message_id=message.message_id)

def check_bad_words(message, bad_words):
  for word in bad_words:
    if word in message.text:
      return True
  return False






# Server messages replies
@bot.message_handler(content_types=['new_chat_members'])
def welcome_new_members(message):
    for new_member in message.new_chat_members:
        bot.reply_to(message, f'ברוך הבא לקבוצה הכי מטורפת בטלגרם!!🔥😱💫, {new_member.first_name}')
        time.sleep(5)
        bot.delete_message(message.chat.id, message.message_id)

@bot.message_handler(content_types=['left_chat_member'])
def farewell_left_member(message):
    left_member = message.left_chat_member
    bot.reply_to(message, f'להתראות!!👋👋, {left_member.first_name}')
    time.sleep(5)
    bot.delete_message(message.chat.id, message.message_id)






# Buttons
commands_buttons = types.InlineKeyboardMarkup() 
onoff_buttons = types.InlineKeyboardMarkup()
# Populate buttons...

# Commands  
commands = {
    "/start": ("שלום😃!!! הגעתם לבוט הראשון שלי 🐣🤖❤️\n🤖הבוט הכי אלוף בטלגרם. נקודה.🤖\n\nבוט זה עדיין בפיתוח!!! לאט לאט יתווספו יותר ויותר דברים😃🏆\n\nמה אני יכול לעשות כעת🤔📜:\n✅ לסנן מילים ותוכן\n✅ חסימה והוצאה של מי ששולח תכנים בערבית 🚫\n✅ שידרוג הקבוצה על ידי הודעת פתיח פרטית למי שנכנס לקבוצות, במקום הודעת {הצטרף} 🎉🎉\n\nמתוכנן:\n❇️ פקודות נוספות לכיופים עם הבוט 🤪\n\n❇️ פקודות ודברים שיעזרו לכם לנהל את הקבוצה 👨‍⚖️\n\n❇️ ולאט לאט נתרחב עוד😁 \n\nאזזזז... למה אתם מחכים??? תכניסו אותי לקבוצה😏, ונתחיל לעבוד! 💫\n\n👈הבוט נוצר על ידי נריה עומסי. ניתן לפנות לתמיכה, ייעוץ, בקשה, הערה, או אפילו למילה טובה😊😉☎️: \n@alufhabot \n\nתיהנו!!🎊"),
    "/help": ("ok"),
}



# Validate admin
def validate_admin(message):
    return message.from_user.id == 6011835055 and message.contact.phone_number == '+972515961649'




# Handle server messages  
@bot.message_handler(content_types=['new_chat_members','left_chat_member'])
def handle_server_messages(message):
    bot.reply_to(message, server_messages[message.content_type])

    
# Ban bad words    
@bot.message_handler(func=lambda msg: msg.text and any(word in msg.text.lower() for word in bad_words))    
def ban_bad_words(message):
    bot.kick_chat_member(message.chat.id, message.from_user.id)
   

# Built in commands 
@bot.message_handler(commands=['start', 'help'])
def handle_text_commands(message):   
    bot.reply_to(message, commands[message.text])
   

# Additional commands
additional_commands = ["/help", "/start"]

@bot.message_handler(func=lambda msg: msg.text in additional_commands)
def handle_additional_commands(message):

    if message.text == "/help":
        bot.reply_to(message, "פקודות זמינות: /help /start")

    elif message.text == "/start": 
        bot.reply_to(message, "ברוך הבא לבוט!")

    else:
        bot.reply_to(message, "פקודה לא זוהתה, נסה שוב")



@bot.message_handler(func=lambda message: True)
def default_reply(message):
    if message.text is None:
        bot.send_message(
            message.chat.id, 
            "סליחה😅, לא הבנתי למה התכוונת🥺. אנא בדוק את ההודעה, כי היא לא מוכרת לי🤓"
        )



def handle_text(message):
    if message.text not in commands:
        bot.send_message(message.chat.id, "logip")


    
@bot.message_handler(content_types=["new_chat_members"])
def on_user_joins(message):
    new_member = message.new_chat_member.first_name
    bot.send_message(message.chat.id, f"היי {new_member}, ברוך הבא לקבוצה הכי מטורפת בטלגרם!!🔥😱💫")
    



#gpt
client = OpenAI(api_key="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")


@bot.message_handler(commands=['ai'])
def handle_message(message):
  question = message.text[len(
      '/ai '):]  # Strip out the command part of the message "/ai "

  if question:
    try:
      # This is where we interact with the GPT-3 model.
      response = client.chat.completions.create(
          model="gpt-3.5-turbo",
          messages=[{
              "role": "system",
              "content": "You are a helpful assistant."
          }, {
              "role": "user",
              "content": question
          }])

      answer = response.choices[0].message['content']
      bot.send_message(message.chat.id, answer)
    except Exception as e:
      bot.send_message(message.chat.id, str(e))
  else:
    # Prompt the user to enter a question if the /ai command was input without any text following it.
    bot.send_message(
        message.chat.id,
        "נא לשאול שאלה לאחר הפקודה. לדוגמה: /ai איך מזג האוויר היום?")



bot.infinity_polling() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling