Upload folder using huggingface_hub
Browse files- README.md +14 -23
- app.py +8 -8
- main.py +8 -35
- requirements.txt +4 -3
- telegram/__init__.py +714 -0
- telegram/constants.py +12 -0
- telegram/ext/__init__.py +360 -0
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
title: Telegram Pro Bot v5
|
| 3 |
emoji: 🤖
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
|
@@ -9,33 +9,24 @@ app_file: app.py
|
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
-
# 🤖 البوت الشامل الاحترافي — ProBot v5.0
|
| 13 |
|
| 14 |
-
بوت تليجرام متكامل
|
| 15 |
|
| 16 |
## 🚀 التشغيل على Hugging Face Spaces
|
| 17 |
|
| 18 |
-
1.
|
| 19 |
-
2.
|
| 20 |
-
|
| 21 |
-
- `
|
| 22 |
-
- `
|
| 23 |
-
- `
|
| 24 |
-
- `
|
| 25 |
-
|
| 26 |
-
4. سيعمل البوت تلقائياً مع لوحة الحالة الآمنة على المنفذ `7860`.
|
| 27 |
|
| 28 |
-
## 💻 التشغيل المحلي على ويندوز
|
| 29 |
|
| 30 |
-
```
|
| 31 |
py -m pip install -r requirements.txt
|
| 32 |
-
|
| 33 |
-
# عدّل ملف .env وحط BOT_TOKEN و OWNER_ID
|
| 34 |
-
py main.py
|
| 35 |
```
|
| 36 |
-
|
| 37 |
-
## 📂 تخصيص ملفاتك الخاصة
|
| 38 |
-
|
| 39 |
-
- **أسئلة الكت والصراحة:** استبدل `data/kit_50000.txt` و `data/saraha_50000.txt` بملفاتك (كل سؤال في سطر)، وتُحمّل تلقائياً بدون إعادة تشغيل.
|
| 40 |
-
- **غلاف تشغيل الموسيقى:** استبدل `assets/music_bg.png` بصورتك أو شعارك ليتم دمجه تلقائياً مع غلاف كل أغنية شغالة.
|
| 41 |
-
- **ستيكرات الصلاة:** مضبوطة تلقائياً على الحزمة `ghgds25s4dfs_by_Stick_MakerBot` (فجر، ظهر، عصر، مغرب، عشاء، جمعة) عند تفعيل `تفعيل الاذان`.
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Telegram Pro Bot v5 (Telethon MTProto)
|
| 3 |
emoji: 🤖
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
|
|
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# 🤖 البوت الشامل الاحترافي — ProBot v5.0 (Telethon MTProto)
|
| 13 |
|
| 14 |
+
بوت تليجرام متكامل يعمل بالكامل عبر **Telethon MTProto** (بدون أي اتصال بـ `api.telegram.org`)، جاهز للتشغيل المباشر على **Hugging Face Spaces** أو محلياً على ويندوز باستخدام `py -m`.
|
| 15 |
|
| 16 |
## 🚀 التشغيل على Hugging Face Spaces
|
| 17 |
|
| 18 |
+
1. افتح الـ Space بتاعك وارفع محتويات مجلد `probot_v5_telethon`.
|
| 19 |
+
2. من **Settings → Variables and secrets** أضف الـ **Secrets** التالية:
|
| 20 |
+
- `API_ID` (من [my.telegram.org](https://my.telegram.org))
|
| 21 |
+
- `API_HASH` (من [my.telegram.org](https://my.telegram.org))
|
| 22 |
+
- `BOT_TOKEN` (من BotFather)
|
| 23 |
+
- `OWNER_ID` (الآيدي الرقمي لمالك البوت)
|
| 24 |
+
- `BOT_NAME` (اختياري — اسم البوت)
|
| 25 |
+
3. اعمل Restart للـ Space وهيشتغل مباشرة عبر MTProto مع Keep-Alive Ping كل 40 ثانية.
|
|
|
|
| 26 |
|
| 27 |
+
## 💻 التشغيل المحلي على ويندوز
|
| 28 |
|
| 29 |
+
```powershell
|
| 30 |
py -m pip install -r requirements.txt
|
| 31 |
+
py -m main
|
|
|
|
|
|
|
| 32 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""نقطة التشغيل لمنصة Hugging Face Spaces (بورت 7860 + لوحة حالة آمنة
|
| 2 |
import asyncio
|
| 3 |
import threading
|
| 4 |
import time
|
|
@@ -12,19 +12,19 @@ from main import build_app, BOT_STATUS
|
|
| 12 |
|
| 13 |
|
| 14 |
def _run_bot_forever():
|
| 15 |
-
if not config.BOT_TOKEN:
|
| 16 |
-
print("⚠️
|
| 17 |
return
|
| 18 |
while True:
|
| 19 |
loop = asyncio.new_event_loop()
|
| 20 |
asyncio.set_event_loop(loop)
|
| 21 |
try:
|
| 22 |
app = build_app()
|
| 23 |
-
app.run_polling(
|
| 24 |
except Exception as exc:
|
| 25 |
BOT_STATUS["connected"] = False
|
| 26 |
-
print(f"⚠️ إعادة الاتصال ب
|
| 27 |
-
time.sleep(
|
| 28 |
finally:
|
| 29 |
try:
|
| 30 |
loop.close()
|
|
@@ -37,7 +37,7 @@ threading.Thread(target=_run_bot_forever, daemon=True).start()
|
|
| 37 |
|
| 38 |
def get_status():
|
| 39 |
now_str = datetime.now(ZoneInfo(config.PRAYER_TZ)).strftime("%Y-%m-%d %H:%M:%S")
|
| 40 |
-
conn = f"متصل (@{BOT_STATUS['username']}) ✅" if BOT_STATUS["connected"] else "جاري الاتصال ⏳"
|
| 41 |
active_groups = sum(1 for k, v in settings.d.items() if k != "global" and v.get("active"))
|
| 42 |
return (
|
| 43 |
f"🤖 حالة البوت: {conn}\n"
|
|
@@ -48,7 +48,7 @@ def get_status():
|
|
| 48 |
|
| 49 |
|
| 50 |
with gr.Blocks(title="Telegram Pro Bot") as demo:
|
| 51 |
-
gr.Markdown("## 🤖 لوحة متابعة البوت المباشرة")
|
| 52 |
box = gr.Textbox(value=get_status, label="الحالة", lines=4)
|
| 53 |
btn_ref = gr.Button("تحديث الحالة 🔄")
|
| 54 |
btn_ref.click(fn=get_status, outputs=box)
|
|
|
|
| 1 |
+
"""نقطة التشغيل لمنصة Hugging Face Spaces عبر Telethon MTProto (بورت 7860 + لوحة حالة آمنة)."""
|
| 2 |
import asyncio
|
| 3 |
import threading
|
| 4 |
import time
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
def _run_bot_forever():
|
| 15 |
+
if not config.API_ID or not config.API_HASH or not config.BOT_TOKEN:
|
| 16 |
+
print("⚠️ يرجى ضبط API_ID و API_HASH و BOT_TOKEN في Hugging Face Secrets!")
|
| 17 |
return
|
| 18 |
while True:
|
| 19 |
loop = asyncio.new_event_loop()
|
| 20 |
asyncio.set_event_loop(loop)
|
| 21 |
try:
|
| 22 |
app = build_app()
|
| 23 |
+
app.run_polling()
|
| 24 |
except Exception as exc:
|
| 25 |
BOT_STATUS["connected"] = False
|
| 26 |
+
print(f"⚠️ انقطع اتصال MTProto ({type(exc).__name__}: {exc}) — إعادة الاتصال بعد 3 ثواني...")
|
| 27 |
+
time.sleep(3)
|
| 28 |
finally:
|
| 29 |
try:
|
| 30 |
loop.close()
|
|
|
|
| 37 |
|
| 38 |
def get_status():
|
| 39 |
now_str = datetime.now(ZoneInfo(config.PRAYER_TZ)).strftime("%Y-%m-%d %H:%M:%S")
|
| 40 |
+
conn = f"متصل عبر MTProto (@{BOT_STATUS['username']}) ✅" if BOT_STATUS["connected"] else "جاري الاتصال ⏳"
|
| 41 |
active_groups = sum(1 for k, v in settings.d.items() if k != "global" and v.get("active"))
|
| 42 |
return (
|
| 43 |
f"🤖 حالة البوت: {conn}\n"
|
|
|
|
| 48 |
|
| 49 |
|
| 50 |
with gr.Blocks(title="Telegram Pro Bot") as demo:
|
| 51 |
+
gr.Markdown("## 🤖 لوحة متابعة البوت المباشرة (Telethon MTProto)")
|
| 52 |
box = gr.Textbox(value=get_status, label="الحالة", lines=4)
|
| 53 |
btn_ref = gr.Button("تحديث الحالة 🔄")
|
| 54 |
btn_ref.click(fn=get_status, outputs=box)
|
main.py
CHANGED
|
@@ -1,19 +1,6 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import socket
|
| 3 |
-
|
| 4 |
-
_orig_getaddrinfo = socket.getaddrinfo
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
def _ipv4_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
|
| 8 |
-
return _orig_getaddrinfo(host, port, socket.AF_INET, type, proto, flags)
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
socket.getaddrinfo = _ipv4_getaddrinfo
|
| 12 |
-
|
| 13 |
import logging
|
| 14 |
from telegram import Update
|
| 15 |
from telegram.ext import Application, MessageHandler, CommandHandler, filters
|
| 16 |
-
from telegram.request import HTTPXRequest
|
| 17 |
import config
|
| 18 |
from strings_ar import S
|
| 19 |
from core import router
|
|
@@ -176,31 +163,17 @@ async def post_init(app):
|
|
| 176 |
quran_prayer.setup_jobs(app)
|
| 177 |
|
| 178 |
|
| 179 |
-
def _make_request():
|
| 180 |
-
return HTTPXRequest(
|
| 181 |
-
connect_timeout=30.0,
|
| 182 |
-
read_timeout=30.0,
|
| 183 |
-
write_timeout=30.0,
|
| 184 |
-
pool_timeout=30.0,
|
| 185 |
-
http_version="1.1",
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
|
| 189 |
def build_app():
|
| 190 |
-
if not config.BOT_TOKEN:
|
| 191 |
-
raise SystemExit("يرجى ضبط BOT_TOKEN في متغيرات البيئة (.env أو Hugging Face Secrets).")
|
| 192 |
-
|
| 193 |
Application.builder()
|
| 194 |
.token(config.BOT_TOKEN)
|
| 195 |
-
.
|
| 196 |
-
.
|
| 197 |
.post_init(post_init)
|
|
|
|
| 198 |
)
|
| 199 |
-
api_url = os.getenv("BOT_API_URL", "").strip()
|
| 200 |
-
if api_url:
|
| 201 |
-
base = api_url.rstrip("/")
|
| 202 |
-
builder = builder.base_url(f"{base}/bot").base_file_url(f"{base}/file/bot")
|
| 203 |
-
app = builder.build()
|
| 204 |
app.add_handler(CommandHandler("start", start))
|
| 205 |
all_mods = (
|
| 206 |
games, admin, admin_pro, settings_mod, locks, fun, services, bank,
|
|
@@ -219,8 +192,8 @@ def build_app():
|
|
| 219 |
|
| 220 |
def main():
|
| 221 |
app = build_app()
|
| 222 |
-
app.run_polling(
|
| 223 |
|
| 224 |
|
| 225 |
if __name__ == "__main__":
|
| 226 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
from telegram import Update
|
| 3 |
from telegram.ext import Application, MessageHandler, CommandHandler, filters
|
|
|
|
| 4 |
import config
|
| 5 |
from strings_ar import S
|
| 6 |
from core import router
|
|
|
|
| 163 |
quran_prayer.setup_jobs(app)
|
| 164 |
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
def build_app():
|
| 167 |
+
if not config.API_ID or not config.API_HASH or not config.BOT_TOKEN:
|
| 168 |
+
raise SystemExit("يرجى ضبط API_ID و API_HASH و BOT_TOKEN في متغيرات البيئة (.env أو Hugging Face Secrets).")
|
| 169 |
+
app = (
|
| 170 |
Application.builder()
|
| 171 |
.token(config.BOT_TOKEN)
|
| 172 |
+
.api_id(config.API_ID)
|
| 173 |
+
.api_hash(config.API_HASH)
|
| 174 |
.post_init(post_init)
|
| 175 |
+
.build()
|
| 176 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
app.add_handler(CommandHandler("start", start))
|
| 178 |
all_mods = (
|
| 179 |
games, admin, admin_pro, settings_mod, locks, fun, services, bank,
|
|
|
|
| 192 |
|
| 193 |
def main():
|
| 194 |
app = build_app()
|
| 195 |
+
app.run_polling()
|
| 196 |
|
| 197 |
|
| 198 |
if __name__ == "__main__":
|
| 199 |
+
main()
|
requirements.txt
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
python-dotenv==1.0.1
|
| 3 |
deep-translator==1.11.4
|
| 4 |
Pillow>=10.0.0
|
| 5 |
-
gradio>=
|
|
|
|
| 6 |
tzdata>=2024.1
|
| 7 |
-
audioop-lts
|
|
|
|
| 1 |
+
telethon>=1.36.0
|
| 2 |
+
cryptg>=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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""طبقة الكائنات المتوافقة بالكامل مع Telethon MTProto (بدون أي اتصال بـ api.telegram.org)."""
|
| 2 |
+
import html
|
| 3 |
+
import io
|
| 4 |
+
import random
|
| 5 |
+
from types import SimpleNamespace
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _norm_parse_mode(pm):
|
| 9 |
+
if not pm:
|
| 10 |
+
return None
|
| 11 |
+
low = str(pm).lower()
|
| 12 |
+
if low == "html":
|
| 13 |
+
return "html"
|
| 14 |
+
if low in ("markdown", "markdownv2", "md"):
|
| 15 |
+
return "md"
|
| 16 |
+
return None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _convert_markup(reply_markup):
|
| 20 |
+
"""يحول InlineKeyboardMarkup / ReplyKeyboardMarkup / ReplyKeyboardRemove إلى أزرار Telethon."""
|
| 21 |
+
if reply_markup is None:
|
| 22 |
+
return None
|
| 23 |
+
from telethon import Button
|
| 24 |
+
if isinstance(reply_markup, ReplyKeyboardRemove):
|
| 25 |
+
return Button.clear()
|
| 26 |
+
if isinstance(reply_markup, InlineKeyboardMarkup):
|
| 27 |
+
rows = []
|
| 28 |
+
for row in reply_markup.inline_keyboard:
|
| 29 |
+
t_row = []
|
| 30 |
+
for b in row:
|
| 31 |
+
if b.url:
|
| 32 |
+
t_row.append(Button.url(str(b.text), str(b.url)))
|
| 33 |
+
elif b.callback_data is not None:
|
| 34 |
+
data = b.callback_data
|
| 35 |
+
if isinstance(data, str):
|
| 36 |
+
data = data.encode("utf-8")
|
| 37 |
+
t_row.append(Button.inline(str(b.text), data))
|
| 38 |
+
if t_row:
|
| 39 |
+
rows.append(t_row)
|
| 40 |
+
return rows if rows else None
|
| 41 |
+
if isinstance(reply_markup, ReplyKeyboardMarkup):
|
| 42 |
+
rows = []
|
| 43 |
+
for row in reply_markup.keyboard:
|
| 44 |
+
t_row = []
|
| 45 |
+
for item in row:
|
| 46 |
+
txt = item.text if hasattr(item, "text") else str(item)
|
| 47 |
+
t_row.append(Button.text(txt, resize=reply_markup.resize_keyboard))
|
| 48 |
+
if t_row:
|
| 49 |
+
rows.append(t_row)
|
| 50 |
+
return rows if rows else None
|
| 51 |
+
return reply_markup
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _resolve_media(file_ref):
|
| 55 |
+
"""يحول file_id النصي أو البايتات أو الرابط إلى كائن صالح لـ Telethon send_file."""
|
| 56 |
+
if isinstance(file_ref, (bytes, bytearray)):
|
| 57 |
+
buf = io.BytesIO(file_ref)
|
| 58 |
+
buf.name = "media.png"
|
| 59 |
+
return buf
|
| 60 |
+
if isinstance(file_ref, io.BytesIO):
|
| 61 |
+
if not getattr(file_ref, "name", None):
|
| 62 |
+
file_ref.name = "media.png"
|
| 63 |
+
try:
|
| 64 |
+
file_ref.seek(0)
|
| 65 |
+
except Exception:
|
| 66 |
+
pass
|
| 67 |
+
return file_ref
|
| 68 |
+
if isinstance(file_ref, str):
|
| 69 |
+
if file_ref.startswith(("http://", "https://")) or "/" in file_ref or "\\" in file_ref:
|
| 70 |
+
return file_ref
|
| 71 |
+
try:
|
| 72 |
+
from telethon.utils import resolve_bot_file_id
|
| 73 |
+
resolved = resolve_bot_file_id(file_ref)
|
| 74 |
+
if resolved is not None:
|
| 75 |
+
return resolved
|
| 76 |
+
except Exception:
|
| 77 |
+
pass
|
| 78 |
+
return file_ref
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _pack_id(media):
|
| 82 |
+
try:
|
| 83 |
+
from telethon.utils import pack_bot_file_id
|
| 84 |
+
fid = pack_bot_file_id(media)
|
| 85 |
+
if fid:
|
| 86 |
+
return fid
|
| 87 |
+
except Exception:
|
| 88 |
+
pass
|
| 89 |
+
return str(getattr(media, "id", ""))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class InlineKeyboardButton:
|
| 93 |
+
def __init__(self, text, callback_data=None, url=None, **kwargs):
|
| 94 |
+
self.text = str(text)
|
| 95 |
+
self.callback_data = callback_data
|
| 96 |
+
self.url = url
|
| 97 |
+
self.extra = kwargs
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class InlineKeyboardMarkup:
|
| 101 |
+
def __init__(self, inline_keyboard):
|
| 102 |
+
self.inline_keyboard = list(inline_keyboard or [])
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class ReplyKeyboardMarkup:
|
| 106 |
+
def __init__(self, keyboard, resize_keyboard=True, one_time_keyboard=False, **kwargs):
|
| 107 |
+
self.keyboard = list(keyboard or [])
|
| 108 |
+
self.resize_keyboard = resize_keyboard
|
| 109 |
+
self.one_time_keyboard = one_time_keyboard
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class ReplyKeyboardRemove:
|
| 113 |
+
def __init__(self, **kwargs):
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class ChatPermissions:
|
| 118 |
+
def __init__(
|
| 119 |
+
self,
|
| 120 |
+
can_send_messages=None,
|
| 121 |
+
can_send_audios=None,
|
| 122 |
+
can_send_documents=None,
|
| 123 |
+
can_send_photos=None,
|
| 124 |
+
can_send_videos=None,
|
| 125 |
+
can_send_video_notes=None,
|
| 126 |
+
can_send_voice_notes=None,
|
| 127 |
+
can_send_polls=None,
|
| 128 |
+
can_send_other_messages=None,
|
| 129 |
+
can_add_web_page_previews=None,
|
| 130 |
+
can_change_info=None,
|
| 131 |
+
can_invite_users=None,
|
| 132 |
+
can_pin_messages=None,
|
| 133 |
+
**kwargs,
|
| 134 |
+
):
|
| 135 |
+
self.can_send_messages = can_send_messages
|
| 136 |
+
self.can_send_audios = can_send_audios
|
| 137 |
+
self.can_send_documents = can_send_documents
|
| 138 |
+
self.can_send_photos = can_send_photos
|
| 139 |
+
self.can_send_videos = can_send_videos
|
| 140 |
+
self.can_send_video_notes = can_send_video_notes
|
| 141 |
+
self.can_send_voice_notes = can_send_voice_notes
|
| 142 |
+
self.can_send_polls = can_send_polls
|
| 143 |
+
self.can_send_other_messages = can_send_other_messages
|
| 144 |
+
self.can_add_web_page_previews = can_add_web_page_previews
|
| 145 |
+
self.can_change_info = can_change_info
|
| 146 |
+
self.can_invite_users = can_invite_users
|
| 147 |
+
self.can_pin_messages = can_pin_messages
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class MediaFile:
|
| 151 |
+
def __init__(self, file_id="", raw=None):
|
| 152 |
+
self.file_id = file_id
|
| 153 |
+
self._raw = raw
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class PhotoSize(MediaFile):
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class UserProfilePhotos:
|
| 161 |
+
def __init__(self, photos=None):
|
| 162 |
+
self.photos = photos or []
|
| 163 |
+
self.total_count = len(self.photos)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class StickerSet:
|
| 167 |
+
def __init__(self, stickers=None):
|
| 168 |
+
self.stickers = stickers or []
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class User:
|
| 172 |
+
def __init__(self, id, first_name="", last_name="", username=None, is_bot=False, _raw=None):
|
| 173 |
+
self.id = int(id)
|
| 174 |
+
self.first_name = first_name or ""
|
| 175 |
+
self.last_name = last_name or ""
|
| 176 |
+
self.username = username or None
|
| 177 |
+
self.is_bot = bool(is_bot)
|
| 178 |
+
self._raw = _raw
|
| 179 |
+
|
| 180 |
+
@property
|
| 181 |
+
def full_name(self):
|
| 182 |
+
return f"{self.first_name} {self.last_name}".strip() or self.first_name or "مستخدم"
|
| 183 |
+
|
| 184 |
+
def mention_html(self, name=None):
|
| 185 |
+
label = html.escape(name or self.full_name)
|
| 186 |
+
return f'<a href="tg://user?id={self.id}">{label}</a>'
|
| 187 |
+
|
| 188 |
+
@classmethod
|
| 189 |
+
def from_telethon(cls, u):
|
| 190 |
+
if u is None:
|
| 191 |
+
return None
|
| 192 |
+
return cls(
|
| 193 |
+
id=getattr(u, "id", 0),
|
| 194 |
+
first_name=getattr(u, "first_name", "") or "",
|
| 195 |
+
last_name=getattr(u, "last_name", "") or "",
|
| 196 |
+
username=getattr(u, "username", None),
|
| 197 |
+
is_bot=bool(getattr(u, "bot", False)),
|
| 198 |
+
_raw=u,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class ChatMember:
|
| 203 |
+
def __init__(self, user, status="member", custom_title=None):
|
| 204 |
+
self.user = user
|
| 205 |
+
self.status = status
|
| 206 |
+
self.custom_title = custom_title
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class Chat:
|
| 210 |
+
def __init__(self, id, type="private", title="", username=None, description="", bio="", _client=None, _raw=None):
|
| 211 |
+
self.id = int(id)
|
| 212 |
+
self.type = type
|
| 213 |
+
self.title = title or ""
|
| 214 |
+
self.username = username or None
|
| 215 |
+
self.description = description or ""
|
| 216 |
+
self.bio = bio or ""
|
| 217 |
+
self._client = _client
|
| 218 |
+
self._raw = _raw
|
| 219 |
+
|
| 220 |
+
@classmethod
|
| 221 |
+
def from_telethon(cls, entity, chat_id, client=None):
|
| 222 |
+
from telethon.tl import types as tl
|
| 223 |
+
ctype = "private"
|
| 224 |
+
title = ""
|
| 225 |
+
username = getattr(entity, "username", None)
|
| 226 |
+
if isinstance(entity, tl.Channel):
|
| 227 |
+
ctype = "supergroup" if getattr(entity, "megagroup", False) else "channel"
|
| 228 |
+
title = getattr(entity, "title", "") or ""
|
| 229 |
+
elif isinstance(entity, tl.Chat):
|
| 230 |
+
ctype = "group"
|
| 231 |
+
title = getattr(entity, "title", "") or ""
|
| 232 |
+
elif isinstance(entity, tl.User):
|
| 233 |
+
ctype = "private"
|
| 234 |
+
title = f"{getattr(entity, 'first_name', '') or ''} {getattr(entity, 'last_name', '') or ''}".strip()
|
| 235 |
+
else:
|
| 236 |
+
if int(chat_id) < 0:
|
| 237 |
+
ctype = "supergroup"
|
| 238 |
+
return cls(id=chat_id, type=ctype, title=title, username=username, _client=client, _raw=entity)
|
| 239 |
+
|
| 240 |
+
async def get_member(self, user_id):
|
| 241 |
+
if not self._client:
|
| 242 |
+
return ChatMember(User(user_id), "member")
|
| 243 |
+
perms = await self._client.get_permissions(self.id, int(user_id))
|
| 244 |
+
u_ent = None
|
| 245 |
+
try:
|
| 246 |
+
u_ent = await self._client.get_entity(int(user_id))
|
| 247 |
+
except Exception:
|
| 248 |
+
pass
|
| 249 |
+
user = User.from_telethon(u_ent) if u_ent else User(int(user_id))
|
| 250 |
+
if perms.is_creator:
|
| 251 |
+
st = "creator"
|
| 252 |
+
elif perms.is_admin:
|
| 253 |
+
st = "administrator"
|
| 254 |
+
elif getattr(perms, "is_banned", False):
|
| 255 |
+
st = "kicked"
|
| 256 |
+
elif hasattr(perms, "send_messages") and perms.send_messages is False:
|
| 257 |
+
st = "restricted"
|
| 258 |
+
else:
|
| 259 |
+
st = "member"
|
| 260 |
+
title = getattr(getattr(perms, "participant", None), "rank", None)
|
| 261 |
+
return ChatMember(user=user, status=st, custom_title=title)
|
| 262 |
+
|
| 263 |
+
async def get_administrators(self):
|
| 264 |
+
if not self._client:
|
| 265 |
+
return []
|
| 266 |
+
from telethon.tl import types as tl
|
| 267 |
+
admins = []
|
| 268 |
+
participants = await self._client.get_participants(self.id, filter=tl.ChannelParticipantsAdmins)
|
| 269 |
+
for u in participants:
|
| 270 |
+
part = getattr(u, "participant", None)
|
| 271 |
+
if isinstance(part, (tl.ChannelParticipantCreator, tl.ChatParticipantCreator)):
|
| 272 |
+
st = "creator"
|
| 273 |
+
else:
|
| 274 |
+
st = "administrator"
|
| 275 |
+
admins.append(ChatMember(user=User.from_telethon(u), status=st, custom_title=getattr(part, "rank", None)))
|
| 276 |
+
return admins
|
| 277 |
+
|
| 278 |
+
async def get_member_count(self):
|
| 279 |
+
if not self._client:
|
| 280 |
+
return 0
|
| 281 |
+
res = await self._client.get_participants(self.id, limit=0)
|
| 282 |
+
return getattr(res, "total", 0) or 0
|
| 283 |
+
|
| 284 |
+
async def ban_member(self, user_id, until_date=None):
|
| 285 |
+
await self._client.edit_permissions(self.id, int(user_id), view_messages=False, until_date=until_date)
|
| 286 |
+
|
| 287 |
+
async def unban_member(self, user_id):
|
| 288 |
+
await self._client.edit_permissions(self.id, int(user_id), view_messages=True, send_messages=True)
|
| 289 |
+
|
| 290 |
+
async def restrict_member(self, user_id, permissions, until_date=None):
|
| 291 |
+
kw = {}
|
| 292 |
+
if permissions.can_send_messages is not None:
|
| 293 |
+
kw["send_messages"] = permissions.can_send_messages
|
| 294 |
+
if permissions.can_send_other_messages is not None:
|
| 295 |
+
kw["send_stickers"] = permissions.can_send_other_messages
|
| 296 |
+
kw["send_gifs"] = permissions.can_send_other_messages
|
| 297 |
+
kw["send_inline"] = permissions.can_send_other_messages
|
| 298 |
+
if permissions.can_send_photos is not None or permissions.can_send_videos is not None:
|
| 299 |
+
kw["send_media"] = bool(permissions.can_send_photos or permissions.can_send_videos)
|
| 300 |
+
if permissions.can_add_web_page_previews is not None:
|
| 301 |
+
kw["embed_links"] = permissions.can_add_web_page_previews
|
| 302 |
+
await self._client.edit_permissions(self.id, int(user_id), until_date=until_date, **kw)
|
| 303 |
+
|
| 304 |
+
async def ban_sender_chat(self, sender_chat_id):
|
| 305 |
+
await self._client.edit_permissions(self.id, int(sender_chat_id), view_messages=False)
|
| 306 |
+
|
| 307 |
+
async def export_invite_link(self):
|
| 308 |
+
from telethon import functions
|
| 309 |
+
res = await self._client(functions.messages.ExportChatInviteRequest(peer=self.id))
|
| 310 |
+
return getattr(res, "link", "")
|
| 311 |
+
|
| 312 |
+
async def set_title(self, title):
|
| 313 |
+
from telethon import functions
|
| 314 |
+
from telethon.tl import types as tl
|
| 315 |
+
ent = await self._client.get_input_entity(self.id)
|
| 316 |
+
if isinstance(ent, tl.InputPeerChannel):
|
| 317 |
+
await self._client(functions.channels.EditTitleRequest(channel=ent, title=title))
|
| 318 |
+
else:
|
| 319 |
+
await self._client(functions.messages.EditChatTitleRequest(chat_id=abs(self.id), title=title))
|
| 320 |
+
|
| 321 |
+
async def set_description(self, description):
|
| 322 |
+
from telethon import functions
|
| 323 |
+
ent = await self._client.get_input_entity(self.id)
|
| 324 |
+
await self._client(functions.messages.EditChatAboutRequest(peer=ent, about=description or ""))
|
| 325 |
+
|
| 326 |
+
async def set_photo(self, photo):
|
| 327 |
+
from telethon import functions
|
| 328 |
+
from telethon.tl import types as tl
|
| 329 |
+
media = _resolve_media(photo)
|
| 330 |
+
data = await self._client.download_media(media, bytes)
|
| 331 |
+
uploaded = await self._client.upload_file(data, file_name="chat.jpg")
|
| 332 |
+
ent = await self._client.get_input_entity(self.id)
|
| 333 |
+
if isinstance(ent, tl.InputPeerChannel):
|
| 334 |
+
await self._client(functions.channels.EditPhotoRequest(channel=ent, photo=tl.InputChatUploadedPhoto(file=uploaded)))
|
| 335 |
+
else:
|
| 336 |
+
await self._client(functions.messages.EditChatPhotoRequest(chat_id=abs(self.id), photo=tl.InputChatUploadedPhoto(file=uploaded)))
|
| 337 |
+
|
| 338 |
+
async def set_administrator_custom_title(self, user_id, custom_title):
|
| 339 |
+
await self._client.edit_admin(self.id, int(user_id), title=custom_title[:16])
|
| 340 |
+
|
| 341 |
+
async def unpin_message(self, message_id=None):
|
| 342 |
+
await self._client.unpin_message(self.id, message_id)
|
| 343 |
+
|
| 344 |
+
async def unpin_all_messages(self):
|
| 345 |
+
await self._client.unpin_message(self.id)
|
| 346 |
+
|
| 347 |
+
async def leave(self):
|
| 348 |
+
await self._client.delete_dialog(self.id)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def _convert_entities(raw_entities):
|
| 352 |
+
if not raw_entities:
|
| 353 |
+
return []
|
| 354 |
+
from telethon.tl import types as tl
|
| 355 |
+
mapping = {
|
| 356 |
+
tl.MessageEntityUrl: "url",
|
| 357 |
+
tl.MessageEntityTextUrl: "text_link",
|
| 358 |
+
tl.MessageEntityMention: "mention",
|
| 359 |
+
tl.MessageEntityMentionName: "text_mention",
|
| 360 |
+
tl.MessageEntityHashtag: "hashtag",
|
| 361 |
+
tl.MessageEntityBotCommand: "bot_command",
|
| 362 |
+
tl.MessageEntityBold: "bold",
|
| 363 |
+
tl.MessageEntityItalic: "italic",
|
| 364 |
+
tl.MessageEntityCode: "code",
|
| 365 |
+
tl.MessageEntityPre: "pre",
|
| 366 |
+
tl.MessageEntityUnderline: "underline",
|
| 367 |
+
tl.MessageEntityStrike: "strikethrough",
|
| 368 |
+
tl.MessageEntitySpoiler: "spoiler",
|
| 369 |
+
}
|
| 370 |
+
out = []
|
| 371 |
+
for e in raw_entities:
|
| 372 |
+
etype = mapping.get(type(e), type(e).__name__.lower())
|
| 373 |
+
out.append(SimpleNamespace(type=etype, offset=getattr(e, "offset", 0), length=getattr(e, "length", 0), url=getattr(e, "url", None)))
|
| 374 |
+
return out
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class Message:
|
| 378 |
+
def __init__(self, raw, chat, from_user, client, reply_to_message=None, new_chat_members=None, left_chat_member=None):
|
| 379 |
+
self._raw = raw
|
| 380 |
+
self._client = client
|
| 381 |
+
self.message_id = getattr(raw, "id", 0)
|
| 382 |
+
self.chat = chat
|
| 383 |
+
self.chat_id = chat.id if chat else 0
|
| 384 |
+
self.from_user = from_user
|
| 385 |
+
self.date = getattr(raw, "date", None)
|
| 386 |
+
self.reply_to_message = reply_to_message
|
| 387 |
+
self.new_chat_members = new_chat_members or []
|
| 388 |
+
self.left_chat_member = left_chat_member
|
| 389 |
+
|
| 390 |
+
has_media = bool(getattr(raw, "media", None))
|
| 391 |
+
raw_txt = getattr(raw, "raw_text", None) or getattr(raw, "message", "") or ""
|
| 392 |
+
ents = _convert_entities(getattr(raw, "entities", None))
|
| 393 |
+
if has_media and not isinstance(getattr(raw, "media", None), object.__class__):
|
| 394 |
+
from telethon.tl import types as tl
|
| 395 |
+
is_web_only = isinstance(getattr(raw, "media", None), tl.MessageMediaWebPage)
|
| 396 |
+
else:
|
| 397 |
+
is_web_only = True
|
| 398 |
+
|
| 399 |
+
if has_media and not is_web_only:
|
| 400 |
+
self.text = None
|
| 401 |
+
self.caption = raw_txt or None
|
| 402 |
+
self.entities = []
|
| 403 |
+
self.caption_entities = ents
|
| 404 |
+
else:
|
| 405 |
+
self.text = raw_txt or None
|
| 406 |
+
self.caption = None
|
| 407 |
+
self.entities = ents
|
| 408 |
+
self.caption_entities = []
|
| 409 |
+
|
| 410 |
+
self.photo = [PhotoSize(_pack_id(raw.photo), raw.photo)] if getattr(raw, "photo", None) else []
|
| 411 |
+
self.sticker = MediaFile(_pack_id(raw.sticker), raw.sticker) if getattr(raw, "sticker", None) else None
|
| 412 |
+
self.animation = MediaFile(_pack_id(raw.gif), raw.gif) if getattr(raw, "gif", None) else None
|
| 413 |
+
self.voice = MediaFile(_pack_id(raw.voice), raw.voice) if getattr(raw, "voice", None) else None
|
| 414 |
+
self.audio = MediaFile(_pack_id(raw.audio), raw.audio) if getattr(raw, "audio", None) else None
|
| 415 |
+
self.video_note = MediaFile(_pack_id(raw.video_note), raw.video_note) if getattr(raw, "video_note", None) else None
|
| 416 |
+
is_vid = bool(getattr(raw, "video", None) and not self.animation and not self.video_note)
|
| 417 |
+
self.video = MediaFile(_pack_id(raw.video), raw.video) if is_vid else None
|
| 418 |
+
is_doc = bool(getattr(raw, "document", None) and not (self.sticker or self.animation or self.voice or self.audio or self.video_note or self.video))
|
| 419 |
+
self.document = MediaFile(_pack_id(raw.document), raw.document) if is_doc else None
|
| 420 |
+
|
| 421 |
+
self.contact = getattr(raw, "contact", None)
|
| 422 |
+
self.location = getattr(raw, "geo", None)
|
| 423 |
+
self.venue = getattr(raw, "venue", None)
|
| 424 |
+
self.forward_origin = getattr(raw, "fwd_from", None)
|
| 425 |
+
self.via_bot = getattr(raw, "via_bot_id", None)
|
| 426 |
+
self.reply_markup = getattr(raw, "reply_markup", None)
|
| 427 |
+
|
| 428 |
+
from telethon.tl import types as tl
|
| 429 |
+
self.sender_chat = None
|
| 430 |
+
from_id = getattr(raw, "from_id", None)
|
| 431 |
+
if isinstance(from_id, tl.PeerChannel):
|
| 432 |
+
cid = int(f"-100{from_id.channel_id}")
|
| 433 |
+
self.sender_chat = Chat(id=cid, type="channel", _client=client)
|
| 434 |
+
|
| 435 |
+
async def reply_text(self, text, parse_mode=None, reply_markup=None, disable_web_page_preview=None, **kw):
|
| 436 |
+
sent = await self._client.send_message(
|
| 437 |
+
self.chat_id,
|
| 438 |
+
str(text),
|
| 439 |
+
reply_to=self.message_id or None,
|
| 440 |
+
parse_mode=_norm_parse_mode(parse_mode),
|
| 441 |
+
buttons=_convert_markup(reply_markup),
|
| 442 |
+
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
|
| 443 |
+
)
|
| 444 |
+
return Message(sent, self.chat, None, self._client)
|
| 445 |
+
|
| 446 |
+
async def _reply_file(self, file_ref, caption=None, parse_mode=None, reply_markup=None, **extra):
|
| 447 |
+
sent = await self._client.send_file(
|
| 448 |
+
self.chat_id,
|
| 449 |
+
_resolve_media(file_ref),
|
| 450 |
+
caption=str(caption) if caption else None,
|
| 451 |
+
reply_to=self.message_id or None,
|
| 452 |
+
parse_mode=_norm_parse_mode(parse_mode),
|
| 453 |
+
buttons=_convert_markup(reply_markup),
|
| 454 |
+
**extra,
|
| 455 |
+
)
|
| 456 |
+
return Message(sent, self.chat, None, self._client)
|
| 457 |
+
|
| 458 |
+
async def reply_photo(self, photo, caption=None, parse_mode=None, reply_markup=None, **kw):
|
| 459 |
+
return await self._reply_file(photo, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
|
| 460 |
+
|
| 461 |
+
async def reply_video(self, video, caption=None, parse_mode=None, reply_markup=None, **kw):
|
| 462 |
+
return await self._reply_file(video, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
|
| 463 |
+
|
| 464 |
+
async def reply_animation(self, animation, caption=None, parse_mode=None, reply_markup=None, **kw):
|
| 465 |
+
return await self._reply_file(animation, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
|
| 466 |
+
|
| 467 |
+
async def reply_voice(self, voice, caption=None, parse_mode=None, reply_markup=None, **kw):
|
| 468 |
+
return await self._reply_file(voice, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup, voice_note=True)
|
| 469 |
+
|
| 470 |
+
async def reply_audio(self, audio, caption=None, parse_mode=None, reply_markup=None, title=None, **kw):
|
| 471 |
+
return await self._reply_file(audio, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
|
| 472 |
+
|
| 473 |
+
async def reply_document(self, document, caption=None, parse_mode=None, reply_markup=None, filename=None, **kw):
|
| 474 |
+
return await self._reply_file(document, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup, force_document=True)
|
| 475 |
+
|
| 476 |
+
async def reply_sticker(self, sticker, **kw):
|
| 477 |
+
return await self._reply_file(sticker)
|
| 478 |
+
|
| 479 |
+
async def reply_poll(self, question, options, is_anonymous=True, allows_multiple_answers=False, **kw):
|
| 480 |
+
from telethon.tl import types as tl
|
| 481 |
+
answers = [
|
| 482 |
+
tl.PollAnswer(text=tl.TextWithEntities(text=str(opt), entities=[]), option=bytes([i]))
|
| 483 |
+
for i, opt in enumerate(options)
|
| 484 |
+
]
|
| 485 |
+
poll = tl.InputMediaPoll(
|
| 486 |
+
poll=tl.Poll(
|
| 487 |
+
id=random.randint(1, 2**62 - 1),
|
| 488 |
+
question=tl.TextWithEntities(text=str(question), entities=[]),
|
| 489 |
+
answers=answers,
|
| 490 |
+
public_voters=not is_anonymous,
|
| 491 |
+
multiple_choice=allows_multiple_answers,
|
| 492 |
+
)
|
| 493 |
+
)
|
| 494 |
+
sent = await self._client.send_file(self.chat_id, poll, reply_to=self.message_id or None)
|
| 495 |
+
return Message(sent, self.chat, None, self._client)
|
| 496 |
+
|
| 497 |
+
async def edit_text(self, text, parse_mode=None, reply_markup=None, disable_web_page_preview=None, **kw):
|
| 498 |
+
await self._client.edit_message(
|
| 499 |
+
self.chat_id,
|
| 500 |
+
self.message_id,
|
| 501 |
+
str(text),
|
| 502 |
+
parse_mode=_norm_parse_mode(parse_mode),
|
| 503 |
+
buttons=_convert_markup(reply_markup),
|
| 504 |
+
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
async def edit_reply_markup(self, reply_markup=None, **kw):
|
| 508 |
+
await self._client.edit_message(
|
| 509 |
+
self.chat_id,
|
| 510 |
+
self.message_id,
|
| 511 |
+
buttons=_convert_markup(reply_markup),
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
async def delete(self):
|
| 515 |
+
await self._client.delete_messages(self.chat_id, [self.message_id])
|
| 516 |
+
|
| 517 |
+
async def pin(self, disable_notification=True):
|
| 518 |
+
await self._client.pin_message(self.chat_id, self.message_id, notify=not disable_notification)
|
| 519 |
+
|
| 520 |
+
async def unpin(self):
|
| 521 |
+
await self._client.unpin_message(self.chat_id, self.message_id)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class CallbackQuery:
|
| 525 |
+
def __init__(self, event, from_user, message, client):
|
| 526 |
+
self._event = event
|
| 527 |
+
self._client = client
|
| 528 |
+
self.id = str(getattr(event, "id", ""))
|
| 529 |
+
self.from_user = from_user
|
| 530 |
+
self.message = message
|
| 531 |
+
raw_data = getattr(event, "data", b"")
|
| 532 |
+
self.data = raw_data.decode("utf-8", errors="ignore") if isinstance(raw_data, (bytes, bytearray)) else str(raw_data)
|
| 533 |
+
|
| 534 |
+
async def answer(self, text=None, show_alert=False, **kw):
|
| 535 |
+
try:
|
| 536 |
+
await self._event.answer(text or None, alert=bool(show_alert))
|
| 537 |
+
except Exception:
|
| 538 |
+
pass
|
| 539 |
+
|
| 540 |
+
async def edit_message_text(self, text, parse_mode=None, reply_markup=None, disable_web_page_preview=None, **kw):
|
| 541 |
+
await self._event.edit(
|
| 542 |
+
str(text),
|
| 543 |
+
parse_mode=_norm_parse_mode(parse_mode),
|
| 544 |
+
buttons=_convert_markup(reply_markup),
|
| 545 |
+
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
async def edit_message_reply_markup(self, reply_markup=None, **kw):
|
| 549 |
+
await self._event.edit(buttons=_convert_markup(reply_markup))
|
| 550 |
+
|
| 551 |
+
async def delete_message(self):
|
| 552 |
+
await self._event.delete()
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
class ChatMemberUpdated:
|
| 556 |
+
def __init__(self, chat, from_user, new_chat_member, old_chat_member=None):
|
| 557 |
+
self.chat = chat
|
| 558 |
+
self.from_user = from_user
|
| 559 |
+
self.new_chat_member = new_chat_member
|
| 560 |
+
self.old_chat_member = old_chat_member
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class ChatJoinRequest:
|
| 564 |
+
def __init__(self, chat, from_user, client):
|
| 565 |
+
self.chat = chat
|
| 566 |
+
self.from_user = from_user
|
| 567 |
+
self._client = client
|
| 568 |
+
|
| 569 |
+
async def approve(self):
|
| 570 |
+
from telethon import functions
|
| 571 |
+
await self._client(functions.messages.HideChatJoinRequestRequest(peer=self.chat.id, user_id=self.from_user.id, approved=True))
|
| 572 |
+
|
| 573 |
+
async def decline(self):
|
| 574 |
+
from telethon import functions
|
| 575 |
+
await self._client(functions.messages.HideChatJoinRequestRequest(peer=self.chat.id, user_id=self.from_user.id, approved=False))
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class Bot:
|
| 579 |
+
def __init__(self, client):
|
| 580 |
+
self._client = client
|
| 581 |
+
self._me = None
|
| 582 |
+
|
| 583 |
+
async def get_me(self):
|
| 584 |
+
if self._me is None:
|
| 585 |
+
me = await self._client.get_me()
|
| 586 |
+
self._me = User.from_telethon(me)
|
| 587 |
+
return self._me
|
| 588 |
+
|
| 589 |
+
async def send_message(self, chat_id, text, parse_mode=None, reply_markup=None, disable_web_page_preview=None, reply_to_message_id=None, **kw):
|
| 590 |
+
sent = await self._client.send_message(
|
| 591 |
+
int(chat_id),
|
| 592 |
+
str(text),
|
| 593 |
+
parse_mode=_norm_parse_mode(parse_mode),
|
| 594 |
+
buttons=_convert_markup(reply_markup),
|
| 595 |
+
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
|
| 596 |
+
reply_to=reply_to_message_id,
|
| 597 |
+
)
|
| 598 |
+
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
|
| 599 |
+
|
| 600 |
+
async def send_photo(self, chat_id, photo, caption=None, parse_mode=None, reply_markup=None, **kw):
|
| 601 |
+
sent = await self._client.send_file(
|
| 602 |
+
int(chat_id),
|
| 603 |
+
_resolve_media(photo),
|
| 604 |
+
caption=str(caption) if caption else None,
|
| 605 |
+
parse_mode=_norm_parse_mode(parse_mode),
|
| 606 |
+
buttons=_convert_markup(reply_markup),
|
| 607 |
+
)
|
| 608 |
+
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
|
| 609 |
+
|
| 610 |
+
async def send_audio(self, chat_id, audio, caption=None, parse_mode=None, reply_markup=None, title=None, **kw):
|
| 611 |
+
sent = await self._client.send_file(
|
| 612 |
+
int(chat_id),
|
| 613 |
+
_resolve_media(audio),
|
| 614 |
+
caption=str(caption) if caption else None,
|
| 615 |
+
parse_mode=_norm_parse_mode(parse_mode),
|
| 616 |
+
buttons=_convert_markup(reply_markup),
|
| 617 |
+
)
|
| 618 |
+
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
|
| 619 |
+
|
| 620 |
+
async def send_sticker(self, chat_id, sticker, **kw):
|
| 621 |
+
sent = await self._client.send_file(int(chat_id), _resolve_media(sticker))
|
| 622 |
+
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
|
| 623 |
+
|
| 624 |
+
async def delete_message(self, chat_id, message_id):
|
| 625 |
+
await self._client.delete_messages(int(chat_id), [int(message_id)])
|
| 626 |
+
|
| 627 |
+
async def get_chat(self, chat_id):
|
| 628 |
+
from telethon import functions
|
| 629 |
+
from telethon.tl import types as tl
|
| 630 |
+
ent = await self._client.get_entity(int(chat_id))
|
| 631 |
+
chat = Chat.from_telethon(ent, int(chat_id), self._client)
|
| 632 |
+
try:
|
| 633 |
+
if isinstance(ent, tl.User):
|
| 634 |
+
full = await self._client(functions.users.GetFullUserRequest(ent))
|
| 635 |
+
chat.bio = getattr(getattr(full, "full_user", None), "about", "") or ""
|
| 636 |
+
elif isinstance(ent, tl.Channel):
|
| 637 |
+
full = await self._client(functions.channels.GetFullChannelRequest(ent))
|
| 638 |
+
chat.description = getattr(getattr(full, "full_chat", None), "about", "") or ""
|
| 639 |
+
elif isinstance(ent, tl.Chat):
|
| 640 |
+
full = await self._client(functions.messages.GetFullChatRequest(ent.id))
|
| 641 |
+
chat.description = getattr(getattr(full, "full_chat", None), "about", "") or ""
|
| 642 |
+
except Exception:
|
| 643 |
+
pass
|
| 644 |
+
return chat
|
| 645 |
+
|
| 646 |
+
async def get_chat_member(self, chat_id, user_id):
|
| 647 |
+
return await Chat(int(chat_id), _client=self._client).get_member(user_id)
|
| 648 |
+
|
| 649 |
+
async def get_user_profile_photos(self, user_id, limit=1):
|
| 650 |
+
photos = await self._client.get_profile_photos(int(user_id), limit=limit)
|
| 651 |
+
groups = [[PhotoSize(_pack_id(p), p)] for p in photos]
|
| 652 |
+
return UserProfilePhotos(groups)
|
| 653 |
+
|
| 654 |
+
async def get_sticker_set(self, name):
|
| 655 |
+
from telethon import functions
|
| 656 |
+
from telethon.tl import types as tl
|
| 657 |
+
res = await self._client(
|
| 658 |
+
functions.messages.GetStickerSetRequest(
|
| 659 |
+
stickerset=tl.InputStickerSetShortName(short_name=str(name)),
|
| 660 |
+
hash=0,
|
| 661 |
+
)
|
| 662 |
+
)
|
| 663 |
+
stickers = [MediaFile(_pack_id(doc), doc) for doc in getattr(res, "documents", [])]
|
| 664 |
+
return StickerSet(stickers)
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
class Update:
|
| 668 |
+
ALL_TYPES = []
|
| 669 |
+
|
| 670 |
+
def __init__(
|
| 671 |
+
self,
|
| 672 |
+
message=None,
|
| 673 |
+
edited_message=None,
|
| 674 |
+
callback_query=None,
|
| 675 |
+
my_chat_member=None,
|
| 676 |
+
chat_join_request=None,
|
| 677 |
+
):
|
| 678 |
+
self.message = message
|
| 679 |
+
self.edited_message = edited_message
|
| 680 |
+
self.callback_query = callback_query
|
| 681 |
+
self.my_chat_member = my_chat_member
|
| 682 |
+
self.chat_join_request = chat_join_request
|
| 683 |
+
|
| 684 |
+
@property
|
| 685 |
+
def effective_message(self):
|
| 686 |
+
if self.message:
|
| 687 |
+
return self.message
|
| 688 |
+
if self.edited_message:
|
| 689 |
+
return self.edited_message
|
| 690 |
+
if self.callback_query:
|
| 691 |
+
return self.callback_query.message
|
| 692 |
+
return None
|
| 693 |
+
|
| 694 |
+
@property
|
| 695 |
+
def effective_chat(self):
|
| 696 |
+
if self.effective_message:
|
| 697 |
+
return self.effective_message.chat
|
| 698 |
+
if self.my_chat_member:
|
| 699 |
+
return self.my_chat_member.chat
|
| 700 |
+
if self.chat_join_request:
|
| 701 |
+
return self.chat_join_request.chat
|
| 702 |
+
return None
|
| 703 |
+
|
| 704 |
+
@property
|
| 705 |
+
def effective_user(self):
|
| 706 |
+
if self.callback_query:
|
| 707 |
+
return self.callback_query.from_user
|
| 708 |
+
if self.effective_message:
|
| 709 |
+
return self.effective_message.from_user
|
| 710 |
+
if self.my_chat_member:
|
| 711 |
+
return self.my_chat_member.from_user
|
| 712 |
+
if self.chat_join_request:
|
| 713 |
+
return self.chat_join_request.from_user
|
| 714 |
+
return None
|
telegram/constants.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ثوابت حالات الأعضاء متوافقة مع محرك Telethon MTProto."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ChatMemberStatus:
|
| 5 |
+
OWNER = "creator"
|
| 6 |
+
CREATOR = "creator"
|
| 7 |
+
ADMINISTRATOR = "administrator"
|
| 8 |
+
MEMBER = "member"
|
| 9 |
+
RESTRICTED = "restricted"
|
| 10 |
+
LEFT = "left"
|
| 11 |
+
BANNED = "kicked"
|
| 12 |
+
KICKED = "kicked"
|
telegram/ext/__init__.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""محرك التشغيل والـ Handlers المبني بالكامل على Telethon MTProto + Ping دائم + JobQueue."""
|
| 2 |
+
import asyncio
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
import re
|
| 7 |
+
from telegram import (
|
| 8 |
+
Bot,
|
| 9 |
+
CallbackQuery,
|
| 10 |
+
Chat,
|
| 11 |
+
ChatJoinRequest,
|
| 12 |
+
ChatMember,
|
| 13 |
+
ChatMemberUpdated,
|
| 14 |
+
Message,
|
| 15 |
+
Update,
|
| 16 |
+
User,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
log = logging.getLogger("telethon_engine")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class _Filter:
|
| 23 |
+
def __init__(self, fn):
|
| 24 |
+
self.fn = fn
|
| 25 |
+
|
| 26 |
+
def __call__(self, update):
|
| 27 |
+
return bool(self.fn(update))
|
| 28 |
+
|
| 29 |
+
def __and__(self, other):
|
| 30 |
+
return _Filter(lambda u: self(u) and other(u))
|
| 31 |
+
|
| 32 |
+
def __or__(self, other):
|
| 33 |
+
return _Filter(lambda u: self(u) or other(u))
|
| 34 |
+
|
| 35 |
+
def __invert__(self):
|
| 36 |
+
return _Filter(lambda u: not self(u))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class _StatusUpdate:
|
| 40 |
+
NEW_CHAT_MEMBERS = _Filter(lambda u: bool(u.message and u.message.new_chat_members))
|
| 41 |
+
LEFT_CHAT_MEMBER = _Filter(lambda u: bool(u.message and u.message.left_chat_member))
|
| 42 |
+
ALL = _Filter(lambda u: bool(u.message and (u.message.new_chat_members or u.message.left_chat_member)))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class _UpdateType:
|
| 46 |
+
EDITED = _Filter(lambda u: bool(u.edited_message))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class filters:
|
| 50 |
+
TEXT = _Filter(lambda u: bool(u.effective_message and u.effective_message.text))
|
| 51 |
+
COMMAND = _Filter(lambda u: bool(u.effective_message and (u.effective_message.text or "").startswith("/")))
|
| 52 |
+
StatusUpdate = _StatusUpdate
|
| 53 |
+
UpdateType = _UpdateType
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class CommandHandler:
|
| 57 |
+
def __init__(self, command, callback):
|
| 58 |
+
self.commands = [command.lower()] if isinstance(command, str) else [c.lower() for c in command]
|
| 59 |
+
self.callback = callback
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class MessageHandler:
|
| 63 |
+
def __init__(self, flt, callback):
|
| 64 |
+
self.filter = flt
|
| 65 |
+
self.callback = callback
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class CallbackQueryHandler:
|
| 69 |
+
def __init__(self, callback, pattern=None):
|
| 70 |
+
self.callback = callback
|
| 71 |
+
self.pattern = re.compile(pattern) if isinstance(pattern, str) else pattern
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class ChatMemberHandler:
|
| 75 |
+
MY_CHAT_MEMBER = "my_chat_member"
|
| 76 |
+
|
| 77 |
+
def __init__(self, callback, chat_member_types=None):
|
| 78 |
+
self.callback = callback
|
| 79 |
+
self.chat_member_types = chat_member_types
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ChatJoinRequestHandler:
|
| 83 |
+
def __init__(self, callback):
|
| 84 |
+
self.callback = callback
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Context:
|
| 88 |
+
def __init__(self, bot, args=None, chat_data=None):
|
| 89 |
+
self.bot = bot
|
| 90 |
+
self.args = list(args or [])
|
| 91 |
+
self.chat_data = chat_data if chat_data is not None else {}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class JobQueue:
|
| 95 |
+
def __init__(self):
|
| 96 |
+
self._jobs = []
|
| 97 |
+
self._tasks = []
|
| 98 |
+
|
| 99 |
+
def run_repeating(self, callback, interval, first=0):
|
| 100 |
+
self._jobs.append((callback, float(interval), float(first or 0)))
|
| 101 |
+
|
| 102 |
+
def start(self, bot):
|
| 103 |
+
for cb, interval, first in self._jobs:
|
| 104 |
+
async def _runner(fn=cb, iv=interval, fst=first):
|
| 105 |
+
if fst > 0:
|
| 106 |
+
await asyncio.sleep(fst)
|
| 107 |
+
while True:
|
| 108 |
+
try:
|
| 109 |
+
await fn(Context(bot))
|
| 110 |
+
except Exception as e:
|
| 111 |
+
log.warning("Job error: %s", e)
|
| 112 |
+
await asyncio.sleep(iv)
|
| 113 |
+
self._tasks.append(asyncio.create_task(_runner()))
|
| 114 |
+
|
| 115 |
+
def stop(self):
|
| 116 |
+
for t in self._tasks:
|
| 117 |
+
t.cancel()
|
| 118 |
+
self._tasks.clear()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class _AppBuilder:
|
| 122 |
+
def __init__(self):
|
| 123 |
+
self._token = ""
|
| 124 |
+
self._api_id = int(os.getenv("API_ID", "0") or 0)
|
| 125 |
+
self._api_hash = os.getenv("API_HASH", "").strip()
|
| 126 |
+
self._post_init = None
|
| 127 |
+
|
| 128 |
+
def token(self, tok):
|
| 129 |
+
self._token = str(tok or "").strip()
|
| 130 |
+
return self
|
| 131 |
+
|
| 132 |
+
def api_id(self, aid):
|
| 133 |
+
self._api_id = int(aid or 0)
|
| 134 |
+
return self
|
| 135 |
+
|
| 136 |
+
def api_hash(self, ah):
|
| 137 |
+
self._api_hash = str(ah or "").strip()
|
| 138 |
+
return self
|
| 139 |
+
|
| 140 |
+
def post_init(self, fn):
|
| 141 |
+
self._post_init = fn
|
| 142 |
+
return self
|
| 143 |
+
|
| 144 |
+
def request(self, *a, **kw):
|
| 145 |
+
return self
|
| 146 |
+
|
| 147 |
+
def get_updates_request(self, *a, **kw):
|
| 148 |
+
return self
|
| 149 |
+
|
| 150 |
+
def base_url(self, *a, **kw):
|
| 151 |
+
return self
|
| 152 |
+
|
| 153 |
+
def base_file_url(self, *a, **kw):
|
| 154 |
+
return self
|
| 155 |
+
|
| 156 |
+
def build(self):
|
| 157 |
+
return Application(self._token, self._api_id, self._api_hash, self._post_init)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class Application:
|
| 161 |
+
@classmethod
|
| 162 |
+
def builder(cls):
|
| 163 |
+
return _AppBuilder()
|
| 164 |
+
|
| 165 |
+
def __init__(self, token, api_id, api_hash, post_init=None):
|
| 166 |
+
self._token = token
|
| 167 |
+
self._api_id = api_id
|
| 168 |
+
self._api_hash = api_hash
|
| 169 |
+
self._post_init = post_init
|
| 170 |
+
self._handlers = []
|
| 171 |
+
self._chat_data = {}
|
| 172 |
+
self.job_queue = JobQueue()
|
| 173 |
+
self.bot = None
|
| 174 |
+
self.client = None
|
| 175 |
+
|
| 176 |
+
def add_handler(self, handler):
|
| 177 |
+
self._handlers.append(handler)
|
| 178 |
+
|
| 179 |
+
def _ctx(self, chat_id, args=None):
|
| 180 |
+
cd = self._chat_data.setdefault(chat_id, {})
|
| 181 |
+
return Context(self.bot, args=args, chat_data=cd)
|
| 182 |
+
|
| 183 |
+
async def _wrap_msg(self, event):
|
| 184 |
+
chat_ent = await event.get_chat()
|
| 185 |
+
chat = Chat.from_telethon(chat_ent, event.chat_id, self.client)
|
| 186 |
+
sender = await event.get_sender()
|
| 187 |
+
from_user = User.from_telethon(sender) if sender else None
|
| 188 |
+
reply_msg = None
|
| 189 |
+
if getattr(event, "is_reply", False):
|
| 190 |
+
try:
|
| 191 |
+
r = await event.get_reply_message()
|
| 192 |
+
if r:
|
| 193 |
+
r_sender = await r.get_sender()
|
| 194 |
+
reply_msg = Message(r, chat, User.from_telethon(r_sender) if r_sender else None, self.client)
|
| 195 |
+
except Exception:
|
| 196 |
+
pass
|
| 197 |
+
return Message(event.message, chat, from_user, self.client, reply_to_message=reply_msg)
|
| 198 |
+
|
| 199 |
+
async def _dispatch_message(self, update, is_edited=False):
|
| 200 |
+
m = update.effective_message
|
| 201 |
+
chat_id = update.effective_chat.id if update.effective_chat else 0
|
| 202 |
+
txt = (m.text or "").strip() if m else ""
|
| 203 |
+
|
| 204 |
+
if not is_edited and txt.startswith("/"):
|
| 205 |
+
parts = txt.split()
|
| 206 |
+
cmd = parts[0][1:].split("@")[0].lower()
|
| 207 |
+
args = parts[1:]
|
| 208 |
+
for h in self._handlers:
|
| 209 |
+
if isinstance(h, CommandHandler) and cmd in h.commands:
|
| 210 |
+
await h.callback(update, self._ctx(chat_id, args=args))
|
| 211 |
+
return
|
| 212 |
+
|
| 213 |
+
for h in self._handlers:
|
| 214 |
+
if isinstance(h, MessageHandler):
|
| 215 |
+
if h.filter(update):
|
| 216 |
+
await h.callback(update, self._ctx(chat_id))
|
| 217 |
+
return
|
| 218 |
+
|
| 219 |
+
async def _run_async(self):
|
| 220 |
+
from telethon import TelegramClient, events, functions
|
| 221 |
+
from telethon.tl import types as tl
|
| 222 |
+
|
| 223 |
+
if not self._api_id or not self._api_hash or not self._token:
|
| 224 |
+
raise SystemExit("يرجى ضبط API_ID و API_HASH و BOT_TOKEN في Hugging Face Secrets.")
|
| 225 |
+
|
| 226 |
+
self.client = TelegramClient(
|
| 227 |
+
"probot_mtproto_session",
|
| 228 |
+
self._api_id,
|
| 229 |
+
self._api_hash,
|
| 230 |
+
connection_retries=999999,
|
| 231 |
+
request_retries=10,
|
| 232 |
+
retry_delay=2,
|
| 233 |
+
auto_reconnect=True,
|
| 234 |
+
)
|
| 235 |
+
await self.client.start(bot_token=self._token)
|
| 236 |
+
self.bot = Bot(self.client)
|
| 237 |
+
me = await self.bot.get_me()
|
| 238 |
+
print(f"✅ ProBot MTProto Connected: @{me.username}")
|
| 239 |
+
|
| 240 |
+
if self._post_init:
|
| 241 |
+
await self._post_init(self)
|
| 242 |
+
self.job_queue.start(self.bot)
|
| 243 |
+
|
| 244 |
+
@self.client.on(events.NewMessage)
|
| 245 |
+
async def _on_new(event):
|
| 246 |
+
if event.out:
|
| 247 |
+
return
|
| 248 |
+
try:
|
| 249 |
+
msg = await self._wrap_msg(event)
|
| 250 |
+
await self._dispatch_message(Update(message=msg), is_edited=False)
|
| 251 |
+
except Exception as e:
|
| 252 |
+
log.warning("NewMessage error: %s", e)
|
| 253 |
+
|
| 254 |
+
@self.client.on(events.MessageEdited)
|
| 255 |
+
async def _on_edit(event):
|
| 256 |
+
if event.out:
|
| 257 |
+
return
|
| 258 |
+
try:
|
| 259 |
+
msg = await self._wrap_msg(event)
|
| 260 |
+
await self._dispatch_message(Update(edited_message=msg), is_edited=True)
|
| 261 |
+
except Exception as e:
|
| 262 |
+
log.warning("MessageEdited error: %s", e)
|
| 263 |
+
|
| 264 |
+
@self.client.on(events.CallbackQuery)
|
| 265 |
+
async def _on_cb(event):
|
| 266 |
+
try:
|
| 267 |
+
chat_ent = await event.get_chat()
|
| 268 |
+
chat = Chat.from_telethon(chat_ent, event.chat_id, self.client)
|
| 269 |
+
sender = await event.get_sender()
|
| 270 |
+
user = User.from_telethon(sender) if sender else User(event.sender_id)
|
| 271 |
+
raw_msg = await event.get_message()
|
| 272 |
+
msg = Message(raw_msg, chat, user, self.client) if raw_msg else Message(
|
| 273 |
+
type("_M", (), {"id": event.message_id})(), chat, user, self.client
|
| 274 |
+
)
|
| 275 |
+
cq = CallbackQuery(event, user, msg, self.client)
|
| 276 |
+
upd = Update(callback_query=cq)
|
| 277 |
+
for h in self._handlers:
|
| 278 |
+
if isinstance(h, CallbackQueryHandler):
|
| 279 |
+
if h.pattern is None or h.pattern.search(cq.data):
|
| 280 |
+
await h.callback(upd, self._ctx(chat.id))
|
| 281 |
+
return
|
| 282 |
+
await cq.answer()
|
| 283 |
+
except Exception as e:
|
| 284 |
+
log.warning("CallbackQuery error: %s", e)
|
| 285 |
+
|
| 286 |
+
@self.client.on(events.ChatAction)
|
| 287 |
+
async def _on_action(event):
|
| 288 |
+
try:
|
| 289 |
+
chat_ent = await event.get_chat()
|
| 290 |
+
chat = Chat.from_telethon(chat_ent, event.chat_id, self.client)
|
| 291 |
+
actor = await event.get_added_by()
|
| 292 |
+
actor_u = User.from_telethon(actor) if actor else None
|
| 293 |
+
|
| 294 |
+
if event.user_joined or event.user_added:
|
| 295 |
+
users = await event.get_users()
|
| 296 |
+
wrapped = [User.from_telethon(u) for u in (users or [])]
|
| 297 |
+
# إذا كان البوت نفسه ضمن المضافين
|
| 298 |
+
if any(u.id == me.id for u in wrapped):
|
| 299 |
+
upd = Update(
|
| 300 |
+
my_chat_member=ChatMemberUpdated(
|
| 301 |
+
chat=chat,
|
| 302 |
+
from_user=actor_u or User(0),
|
| 303 |
+
new_chat_member=ChatMember(me, "member"),
|
| 304 |
+
)
|
| 305 |
+
)
|
| 306 |
+
for h in self._handlers:
|
| 307 |
+
if isinstance(h, ChatMemberHandler):
|
| 308 |
+
await h.callback(upd, self._ctx(chat.id))
|
| 309 |
+
raw = getattr(event, "action_message", None) or type("_M", (), {"id": 0})()
|
| 310 |
+
msg = Message(raw, chat, actor_u, self.client, new_chat_members=wrapped)
|
| 311 |
+
await self._dispatch_message(Update(message=msg), is_edited=False)
|
| 312 |
+
|
| 313 |
+
elif event.user_left or event.user_kicked:
|
| 314 |
+
u = await event.get_user()
|
| 315 |
+
left_u = User.from_telethon(u) if u else None
|
| 316 |
+
raw = getattr(event, "action_message", None) or type("_M", (), {"id": 0})()
|
| 317 |
+
msg = Message(raw, chat, left_u, self.client, left_chat_member=left_u)
|
| 318 |
+
await self._dispatch_message(Update(message=msg), is_edited=False)
|
| 319 |
+
except Exception as e:
|
| 320 |
+
log.warning("ChatAction error: %s", e)
|
| 321 |
+
|
| 322 |
+
@self.client.on(events.Raw(tl.UpdateBotChatInviteRequester))
|
| 323 |
+
async def _on_join_req(event):
|
| 324 |
+
try:
|
| 325 |
+
peer = event.peer
|
| 326 |
+
if isinstance(peer, tl.PeerChannel):
|
| 327 |
+
cid = int(f"-100{peer.channel_id}")
|
| 328 |
+
elif isinstance(peer, tl.PeerChat):
|
| 329 |
+
cid = -int(peer.chat_id)
|
| 330 |
+
else:
|
| 331 |
+
return
|
| 332 |
+
chat_ent = await self.client.get_entity(cid)
|
| 333 |
+
chat = Chat.from_telethon(chat_ent, cid, self.client)
|
| 334 |
+
u_ent = await self.client.get_entity(event.user_id)
|
| 335 |
+
req = ChatJoinRequest(chat, User.from_telethon(u_ent), self.client)
|
| 336 |
+
upd = Update(chat_join_request=req)
|
| 337 |
+
for h in self._handlers:
|
| 338 |
+
if isinstance(h, ChatJoinRequestHandler):
|
| 339 |
+
await h.callback(upd, self._ctx(cid))
|
| 340 |
+
except Exception as e:
|
| 341 |
+
log.warning("JoinRequest error: %s", e)
|
| 342 |
+
|
| 343 |
+
async def _keep_alive_ping():
|
| 344 |
+
while True:
|
| 345 |
+
await asyncio.sleep(40)
|
| 346 |
+
try:
|
| 347 |
+
await self.client(functions.PingRequest(ping_id=random.randint(1, 2**31 - 1)))
|
| 348 |
+
except Exception:
|
| 349 |
+
pass
|
| 350 |
+
|
| 351 |
+
ping_task = asyncio.create_task(_keep_alive_ping())
|
| 352 |
+
try:
|
| 353 |
+
await self.client.run_until_disconnected()
|
| 354 |
+
finally:
|
| 355 |
+
ping_task.cancel()
|
| 356 |
+
self.job_queue.stop()
|
| 357 |
+
|
| 358 |
+
def run_polling(self, **kwargs):
|
| 359 |
+
loop = asyncio.get_event_loop()
|
| 360 |
+
loop.run_until_complete(self._run_async())
|