Aayco

make bot

Mar 15th, 2025 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.34 KB | None | 0 0
  1. import requests
  2. import json
  3. import telebot
  4. import random
  5. from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
  6. from telebot import types
  7. from datetime import datetime
  8. import re
  9. API_TOKEN = 'YOUR_BOTU'
  10. bot = telebot.TeleBot(API_TOKEN)
  11. banned_users = set()
  12. admins = set([5541407305])  # ضع معرف الأدمن هنا
  13. users = {}
  14. broadcast_list = []
  15. mandatory_channels = set()  # مجموعة تحتوي على قنوات الاشتراك الإجباري
  16. def botusername():
  17.     user = bot.get_me().username
  18.     if user.startswith('@'):
  19.         user = user[1:]
  20.     return user
  21. try:
  22.     bu = botusername()
  23. except Exception as e:
  24.     print('error in botusername', e)
  25. @bot.message_handler(commands=['start'])
  26. def start(message):
  27.     try:
  28.         if message.chat.type == 'private':
  29.             if message.from_user.id in banned_users:
  30.                 bot.send_message(message.chat.id, "أنت محظور من استخدام هذا البوت❎.")
  31.                 return
  32.             if message.from_user.id not in users:
  33.                 users[message.from_user.id] = {"username": message.from_user.username, "joined": datetime.now()}
  34.                 broadcast_list.append(message.from_user.id)
  35.             if mandatory_channels and not check_mandatory_subscription(message.from_user.id):
  36.                 return
  37.             if message.from_user.id in admins:
  38.                 bot.send_message(message.chat.id, "مرحبًا بك في لوحة التحكم", reply_markup=get_admin_menu())
  39.             else:
  40.                 C4_ = types.InlineKeyboardMarkup()
  41.                 C4_.row_width = 2
  42.                 AIM = types.InlineKeyboardButton(text="ضيفني لـ  قناتك ", url=f"https://t.me/{bu}?startchannel")
  43.                 X = types.InlineKeyboardButton(text="المالك", url=f"https://t.me/HN_0K")
  44.                 HLTV = types.InlineKeyboardButton(text="ضيفني لـ مجموعتك", url=f"https://t.me/{bu}?startgroup")
  45.                 C4_.add(AIM, X, HLTV)
  46.                 name_of_C4 = f"{message.from_user.first_name}"
  47.                 text = f'''•مرحبا عزيزي {name_of_C4}, أنا بوت تفاعل برموز تعبيرية متعددة يمكنك إضافتي إلى مجموعة أو قناة للتفاعل•'''
  48.                 bot.send_message(message.chat.id, text, reply_markup=C4_, parse_mode='Markdown')
  49.     except Exception as e:
  50.         print('error in start', e)
  51. @bot.channel_post_handler()
  52. def react_to_channel_message(message):
  53.     print('channel_post_handler')
  54.     try:
  55.         reactions = ["👍", "❤️", "🔥", "🥰", "👏", "😁", "❤️‍🔥", "🤯", " 😘", "🤤", "😎", "🥹", "🗿", "😐" "🫡", "👀", "👨🏼‍💻", "😭", "🤩", "💯", "🌚", "👾", "🐳" "🥲" "💔" "" "😂" "👻" "⚡" "🤣" "🤔" "😇" "😴" "😨" "😱" "🤗" "🙏🏼" "👌🏼" "🎉" "⚡" "🕊️" "🙈" "😈" "💋" "👨🏼‍💻" "🤷🏼‍♂️" "🐳" "🤡" "🥴" "🥱" "🍓" "🏆" "😐" "🤨" "🤬" "🤓" "💘" "🎅🏼" "🆒"]
  56.         emoji = random.choice(reactions)
  57.         send_message_react({
  58.             'chat_id': message.chat.id,
  59.             'message_id': message.message_id,
  60.             'reaction': [{'type': "emoji", "emoji": emoji}]
  61.         })
  62.     except Exception as e:
  63.         print('error in react_to_channel_message', e)
  64. @bot.message_handler(func=lambda message: True)
  65. def react_to_message(message):
  66.     print('message_handler')
  67.     try:
  68.         reactions = ["👍", "❤️", "🔥", "🥰", "👏", "😁", "❤️‍🔥", "🤯", " 😘", "🤤", "😎", "🥹", "🗿", "😐" "🫡", "👀", "👨🏼‍💻", "😭", "🤩", "💯", "🌚", "👾", "🐳" "🥲" "💔" "" "😂" "👻" "⚡" "🤣" "🤔" "😇" "😴" "😨" "😱" "🤗" "🙏🏼" "👌🏼" "🎉" "⚡" "🕊️" "🙈" "😈" "💋" "👨🏼‍💻" "🤷🏼‍♂️" "🐳" "🤡" "🥴" "🥱" "🍓" "🏆" "😐" "🤨" "🤬" "🤓" "💘" "🎅🏼" "🆒"]
  69.         emoji = random.choice(reactions)
  70.         send_message_react({
  71.             'chat_id': message.chat.id,
  72.             'message_id': message.message_id,
  73.             'reaction': [{'type': "emoji", "emoji": emoji}]
  74.         })
  75.     except Exception as e:
  76.         print('error in react_to_message', e)
  77. def send_message_react(datas={}):
  78.     try:
  79.         url = "https://api.telegram.org/bot" + API_TOKEN + "/" + 'setMessageReaction'
  80.         response = requests.post(url, json=datas)
  81.         if response.status_code != 200:
  82.             return "Error: " + response.text
  83.         else:
  84.             return response.json()
  85.     except Exception as e:
  86.         print('error in send_message_react', e)
  87. # لوحة التحكم للأدمن
  88. def get_statistics():
  89.     total_users = len(users)
  90.     last_users = list(users.keys())[-10:]
  91.     last_users_str = "\n".join([f"@{users[user_id]['username']}" for user_id in last_users if users[user_id]['username']])
  92.     total_admins = len(admins)
  93.     admins_str = "\n".join([f"{i+1}- @{bot.get_chat(admin).username}" for i, admin in enumerate(admins)])
  94.     total_banned = len(banned_users)
  95.     banned_users_str = "\n".join([f"{i+1}- @{bot.get_chat(banned).username}" for i, banned in enumerate(banned_users)])
  96.     total_channels = len(mandatory_channels)
  97.     channels_str = "\n".join([f"{i+1}- @{bot.get_chat(channel).username}" for i, channel in enumerate(mandatory_channels)])
  98.     stats_message = (
  99.         f"👥 عدد المستخدمين: {total_users}\n\n"
  100.         f"📋 آخر 10 مستخدمين:\n{last_users_str if last_users_str else 'لا يوجد'}\n\n"
  101.         f"🔧 عدد الأدمنية: {total_admins}\n{admins_str if admins_str else 'لا يوجد'}\n\n"
  102.         f"🚫 عدد المحظورين: {total_banned}\n{banned_users_str if banned_users_str else 'لا يوجد'}\n\n"
  103.         f"📡 عدد قنوات الاشتراك الإجباري: {total_channels}\n{channels_str if channels_str else 'لا يوجد'}"
  104.     )
  105.     return stats_message
  106. def broadcast_message(message):
  107.     for user_id in broadcast_list:
  108.         try:
  109.             bot.send_message(user_id, message)
  110.         except:
  111.             pass
  112. def get_admin_menu():
  113.     markup = types.InlineKeyboardMarkup()
  114.     markup.add(types.InlineKeyboardButton("👥 إدارة المستخدمين", callback_data="manage_users"))
  115.     markup.add(types.InlineKeyboardButton("📊 الإحصائيات", callback_data="statistics"))
  116.     markup.add(types.InlineKeyboardButton("📢 الإذاعة", callback_data="broadcast"))
  117.     markup.add(types.InlineKeyboardButton("📎 إعداد قناة الاشتراك الإجباري", callback_data="set_channel_options"))
  118.     return markup
  119. def get_manage_users_menu():
  120.     markup = types.InlineKeyboardMarkup()
  121.     markup.add(types.InlineKeyboardButton("➕ رفع أدمن", callback_data="add_admin"))
  122.     markup.add(types.InlineKeyboardButton("➖ إزالة أدمن", callback_data="remove_admin"))
  123.     markup.add(types.InlineKeyboardButton("🚫 حظر مستخدم", callback_data="ban_user"))
  124.     markup.add(types.InlineKeyboardButton("🔓 فك حظر مستخدم", callback_data="unban_user"))
  125.     markup.add(types.InlineKeyboardButton("📋 عرض الأدمنية", callback_data="show_admins"))
  126.     markup.add(types.InlineKeyboardButton("📋 عرض المستخدمين المحظورين", callback_data="show_banned_users"))
  127.     return markup
  128. def get_mandatory_subscription_menu():
  129.     markup = types.InlineKeyboardMarkup()
  130.     markup.add(types.InlineKeyboardButton("➕ إضافة قناة اشتراك إجباري", callback_data="add_channel"))
  131.     markup.add(types.InlineKeyboardButton("➖ حذف قناة من الاشتراك الإجباري", callback_data="remove_channel"))
  132.     markup.add(types.InlineKeyboardButton("📋 عرض قنوات الاشتراك الإجباري", callback_data="show_channels"))
  133.     return markup
  134. def get_channel_name(channel_username):
  135.     try:
  136.         channel_info = bot.get_chat(channel_username)
  137.         return channel_info.title  # إعادة اسم القناة
  138.     except telebot.apihelper.ApiException as e:
  139.         print(f"Error fetching channel name: {e}")
  140.         return None
  141. # دالة للتحقق من الاشتراك الإجباري
  142. def check_mandatory_subscription(user_id):
  143.     for channel in mandatory_channels:
  144.         try:
  145.             status = bot.get_chat_member(channel, user_id).status
  146.             if status in ['left', 'kicked']:
  147.                 # الحصول على اسم القناة باستخدام الدالة
  148.                 channel_name = get_channel_name(channel)
  149.                 if channel_name is None:
  150.                     bot.send_message(user_id, "حدث خطأ في جلب معلومات القناة. يرجى المحاولة لاحقًا.")
  151.                     return False
  152.                
  153.                 # إنشاء زر ينقل المستخدم إلى القناة
  154.                 markup = InlineKeyboardMarkup()
  155.                 channel_button = InlineKeyboardButton(f"{channel_name}", url=f"https://t.me/{channel.replace('@', '')}")
  156.                 markup.add(channel_button)
  157.                
  158.                 # رسالة الاشتراك
  159.                 bot.send_message(user_id, f'''يجب ان تشترك في القناة
  160. اشترك ثم ارسل  /start''', reply_markup=markup)
  161.                 return False
  162.         except telebot.apihelper.ApiException as e:
  163.             print(f"Error checking subscription: {e}")
  164.             bot.send_message(user_id, "حدث خطأ يرجى المحاولة لاحقًا وشكرًا 🤍.")
  165.             return False
  166.     return True
  167. @bot.callback_query_handler(func=lambda call: True)
  168. def callback_query(call):
  169.     user_id = call.from_user.id
  170.     if user_id in banned_users:
  171.         bot.send_message(user_id, "أنت محظور من استخدام هذا البوت❎.")
  172.         return
  173.     if call.data == "manage_users":
  174.         if user_id in admins:
  175.             bot.send_message(user_id, "إدارة المستخدمين", reply_markup=get_manage_users_menu())
  176.     elif call.data == "ban_user":
  177.         if user_id in admins:
  178.             msg = bot.send_message(user_id, "أرسل معرف المستخدم لحظره🌠:")
  179.             bot.register_next_step_handler(msg, ban_user)
  180.     elif call.data == "unban_user":
  181.         if user_id in admins:
  182.             msg = bot.send_message(user_id, "أرسل معرف المستخدم لفك الحظر عنه🤍:")
  183.             bot.register_next_step_handler(msg, unban_user)
  184.     elif call.data == "unban_user":
  185.         if user_id in admins:
  186.             msg = bot.send_message(user_id, "أرسل معرف المستخدم لفك الحظر عنه🤍:")
  187.             bot.register_next_step_handler(msg, unban_user)
  188.     elif call.data == "add_admin":
  189.         if user_id in admins:
  190.             msg = bot.send_message(user_id, "أرسل معرف أو ID المستخدم لإضافته كأدمن⚡:")
  191.             bot.register_next_step_handler(msg, add_admin)
  192.     elif call.data == "remove_admin":
  193.         if user_id in admins:
  194.             msg = bot.send_message(user_id, "أرسل معرف أو ID المستخدم لحذفه من الأدمن🙂:")
  195.             bot.register_next_step_handler(msg, remove_admin)
  196.     elif call.data == "statistics":
  197.         if user_id in admins:
  198.             stats = get_statistics()
  199.             bot.send_message(user_id, stats)
  200.     elif call.data == "broadcast":
  201.         if user_id in admins:
  202.             msg = bot.send_message(user_id, "أرسل الرسالة التي تريد إرسالها لجميع المستخدمين✅:")
  203.             bot.register_next_step_handler(msg, send_broadcast)
  204.     elif call.data == "set_channel_options":
  205.         if user_id in admins:
  206.             bot.send_message(user_id, "خيارات قناة الاشتراك الإجباري🤍", reply_markup=get_mandatory_subscription_menu())
  207.     elif call.data == "add_channel":
  208.         if user_id in admins:
  209.             msg = bot.send_message(user_id, "أرسل معرف أو رابط القناة لإضافتها كقناة اشتراك إجباري🚸:")
  210.             bot.register_next_step_handler(msg, add_mandatory_channel)
  211.     elif call.data == "remove_channel":
  212.         if user_id in admins:
  213.             msg = bot.send_message(user_id, "أرسل معرف أو رابط القناة التي تريد حذفها من الاشتراك الإجباري🤍:")
  214.             bot.register_next_step_handler(msg, remove_mandatory_channel)
  215.     elif call.data == "show_channels":
  216.         if user_id in admins:
  217.             show_mandatory_channels(user_id)
  218.     elif call.data == "show_admins":
  219.         if user_id in admins:
  220.             show_admins(user_id)
  221.     elif call.data == "show_banned_users":
  222.         if user_id in admins:
  223.             show_banned_users(user_id)
  224. def extract_channel_id(text):
  225.     if text.startswith('@'):
  226.         return text
  227.     elif 't.me/' in text:
  228.         match = re.search(r"t\.me/(.+)", text)
  229.         if match:
  230.             return '@' + match.group(1)
  231.     return None
  232. def add_mandatory_channel(message):
  233.     channel_id = extract_channel_id(message.text)
  234.     if channel_id:
  235.         try:
  236.             channel_info = bot.get_chat(channel_id)
  237.             member_status = bot.get_chat_member(channel_id, bot.get_me().id).status
  238.             if member_status in ['administrator', 'creator']:
  239.                 mandatory_channels.add(channel_id)
  240.                 bot.send_message(message.chat.id, f"تم إضافة القناة {channel_id} إلى الاشتراك الإجباري ✅")
  241.             else:
  242.                 bot.send_message(message.chat.id, "البوت ليس أدمن في القناة ❎")
  243.         except telebot.apihelper.ApiException as e:
  244.             if 'chat not found' in str(e):
  245.                 bot.send_message(message.chat.id, "عذرًا، القناة التي أرسلتها غير موجودة ❎")
  246.             else:
  247.                 bot.send_message(message.chat.id, "حدث خطأ أو البوت ليس أدمن في القناة 🤍.")
  248.     else:
  249.         bot.send_message(message.chat.id, "يرجى إدخال معرف أو رابط قناة صالح.")
  250. def remove_mandatory_channel(message):
  251.     channel_id = extract_channel_id(message.text)
  252.     if channel_id and channel_id in mandatory_channels:
  253.         mandatory_channels.remove(channel_id)
  254.         bot.send_message(message.chat.id, f"تم حذف القناة {channel_id} من الاشتراك الإجباري ✅")
  255.     else:
  256.         bot.send_message(message.chat.id, "القناة غير موجودة في قائمة الاشتراك الإجباري 🚸")
  257. def show_mandatory_channels(user_id):
  258.     if mandatory_channels:
  259.         channels_list = "\n".join(mandatory_channels)
  260.         bot.send_message(user_id, f"القنوات المضافة للاشتراك الإجباري:\n{channels_list}")
  261.     else:
  262.         bot.send_message(user_id, "لا توجد قنوات مضافة للاشتراك الإجباري.")
  263. def show_admins(user_id):
  264.     if admins:
  265.         admins_list = "\n".join([str(admin) for admin in admins])
  266.         bot.send_message(user_id, f"الأدمنية في النظام:\n{admins_list}")
  267.     else:
  268.         bot.send_message(user_id, "لا يوجد أدمنية في النظام.")
  269. def show_banned_users(user_id):
  270.     if banned_users:
  271.         banned_list = "\n".join([str(user) for user in banned_users])
  272.         bot.send_message(user_id, f"المستخدمين المحظورين:\n{banned_list}")
  273.     else:
  274.         bot.send_message(user_id, "لا يوجد مستخدمين محظورين.")
  275. def ban_user(message):
  276.     try:
  277.         user_id_to_ban = int(message.text)
  278.         if user_id_to_ban not in banned_users:
  279.             banned_users.add(user_id_to_ban)
  280.             bot.send_message(message.chat.id, f"تم حظر المستخدم: {user_id_to_ban}")
  281.         else:
  282.             bot.send_message(message.chat.id, "المستخدم محظور بالفعل.")
  283.     except ValueError:
  284.         bot.send_message(message.chat.id, "يرجى إدخال معرف مستخدم صالح.")
  285. def unban_user(message):
  286.     try:
  287.         user_id_to_unban = int(message.text)
  288.         if user_id_to_unban in banned_users:
  289.             banned_users.discard(user_id_to_unban)
  290.             bot.send_message(message.chat.id, f"تم فك الحظر عن المستخدم: {user_id_to_unban}")
  291.         else:
  292.             bot.send_message(message.chat.id, "المستخدم ليس محظوراً.")
  293.     except ValueError:
  294.         bot.send_message(message.chat.id, "يرجى إدخال معرف مستخدم صالح.")
  295. def add_admin(message):
  296.     try:
  297.         new_admin = message.text
  298.         if new_admin.startswith('@'):
  299.             new_admin_id = bot.get_chat(new_admin).id
  300.         else:
  301.             new_admin_id = int(new_admin)
  302.         if new_admin_id not in admins:
  303.             admins.add(new_admin_id)
  304.             bot.send_message(message.chat.id, f"تمت إضافة الأدمن: {new_admin_id}")
  305.         else:
  306.             bot.send_message(message.chat.id, "المستخدم هو بالفعل أدمن.")
  307.     except (ValueError, telebot.apihelper.ApiException):
  308.         bot.send_message(message.chat.id, "يرجى إدخال معرف أو ID صالح.")
  309. def remove_admin(message):
  310.     try:
  311.         admin_to_remove = message.text
  312.         if admin_to_remove.startswith('@'):
  313.             admin_id_to_remove = bot.get_chat(admin_to_remove).id
  314.         else:
  315.             admin_id_to_remove = int(admin_to_remove)
  316.         if admin_id_to_remove in admins:
  317.             admins.discard(admin_id_to_remove)
  318.             bot.send_message(message.chat.id, f"تم حذف الأدمن: {admin_id_to_remove}")
  319.         else:
  320.             bot.send_message(message.chat.id, "المستخدم ليس أدمن.")
  321.     except (ValueError, telebot.apihelper.ApiException):
  322.         bot.send_message(message.chat.id, "يرجى إدخال معرف أو ID صالح.")
  323. def send_broadcast(message):
  324.     broadcast_message(message.text)
  325.     bot.send_message(message.chat.id, "تم إرسال الرسالة بنجاح!")
  326. print('running...')
  327. #مكتبه لازم تكون موجوده 👇🏻
  328. import time
  329. # الكود مال حل مشكله قطعله البوت 🌚 👇🏻
  330. while True:
  331.     try:
  332.         bot.polling(none_stop=True)
  333.     except Exception as e:
  334.         print(f"حدث خطأ")
  335.         #المده 15 ثانيه عوفها احسن مده هاي لاتغير بيها 🌚
  336.         time.sleep(15)
  337. # وبس بوتك راح يشتغل
Advertisement
Add Comment
Please, Sign In to add comment