File size: 28,870 Bytes
67d64de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 | """طبقة الكائنات المتوافقة بالكامل مع Telethon MTProto (بدون أي اتصال بـ api.telegram.org)."""
import html
import io
import random
from types import SimpleNamespace
def _norm_parse_mode(pm):
if not pm:
return None
low = str(pm).lower()
if low == "html":
return "html"
if low in ("markdown", "markdownv2", "md"):
return "md"
return None
def _convert_markup(reply_markup):
"""يحول InlineKeyboardMarkup / ReplyKeyboardMarkup / ReplyKeyboardRemove إلى أزرار Telethon."""
if reply_markup is None:
return None
from telethon import Button
if isinstance(reply_markup, ReplyKeyboardRemove):
return Button.clear()
if isinstance(reply_markup, InlineKeyboardMarkup):
rows = []
for row in reply_markup.inline_keyboard:
t_row = []
for b in row:
if b.url:
t_row.append(Button.url(str(b.text), str(b.url)))
elif b.callback_data is not None:
data = b.callback_data
if isinstance(data, str):
data = data.encode("utf-8")
t_row.append(Button.inline(str(b.text), data))
if t_row:
rows.append(t_row)
return rows if rows else None
if isinstance(reply_markup, ReplyKeyboardMarkup):
rows = []
for row in reply_markup.keyboard:
t_row = []
for item in row:
txt = item.text if hasattr(item, "text") else str(item)
t_row.append(Button.text(txt, resize=reply_markup.resize_keyboard))
if t_row:
rows.append(t_row)
return rows if rows else None
return reply_markup
def _resolve_media(file_ref):
"""يحول file_id النصي أو البايتات أو الرابط إلى كائن صالح لـ Telethon send_file."""
if isinstance(file_ref, (bytes, bytearray)):
buf = io.BytesIO(file_ref)
buf.name = "media.png"
return buf
if isinstance(file_ref, io.BytesIO):
if not getattr(file_ref, "name", None):
file_ref.name = "media.png"
try:
file_ref.seek(0)
except Exception:
pass
return file_ref
if isinstance(file_ref, str):
if file_ref.startswith(("http://", "https://")) or "/" in file_ref or "\\" in file_ref:
return file_ref
try:
from telethon.utils import resolve_bot_file_id
resolved = resolve_bot_file_id(file_ref)
if resolved is not None:
return resolved
except Exception:
pass
return file_ref
def _pack_id(media):
try:
from telethon.utils import pack_bot_file_id
fid = pack_bot_file_id(media)
if fid:
return fid
except Exception:
pass
return str(getattr(media, "id", ""))
class InlineKeyboardButton:
def __init__(self, text, callback_data=None, url=None, **kwargs):
self.text = str(text)
self.callback_data = callback_data
self.url = url
self.extra = kwargs
class InlineKeyboardMarkup:
def __init__(self, inline_keyboard):
self.inline_keyboard = list(inline_keyboard or [])
class ReplyKeyboardMarkup:
def __init__(self, keyboard, resize_keyboard=True, one_time_keyboard=False, **kwargs):
self.keyboard = list(keyboard or [])
self.resize_keyboard = resize_keyboard
self.one_time_keyboard = one_time_keyboard
class ReplyKeyboardRemove:
def __init__(self, **kwargs):
pass
class ChatPermissions:
def __init__(
self,
can_send_messages=None,
can_send_audios=None,
can_send_documents=None,
can_send_photos=None,
can_send_videos=None,
can_send_video_notes=None,
can_send_voice_notes=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
**kwargs,
):
self.can_send_messages = can_send_messages
self.can_send_audios = can_send_audios
self.can_send_documents = can_send_documents
self.can_send_photos = can_send_photos
self.can_send_videos = can_send_videos
self.can_send_video_notes = can_send_video_notes
self.can_send_voice_notes = can_send_voice_notes
self.can_send_polls = can_send_polls
self.can_send_other_messages = can_send_other_messages
self.can_add_web_page_previews = can_add_web_page_previews
self.can_change_info = can_change_info
self.can_invite_users = can_invite_users
self.can_pin_messages = can_pin_messages
class MediaFile:
def __init__(self, file_id="", raw=None):
self.file_id = file_id
self._raw = raw
class PhotoSize(MediaFile):
pass
class UserProfilePhotos:
def __init__(self, photos=None):
self.photos = photos or []
self.total_count = len(self.photos)
class StickerSet:
def __init__(self, stickers=None):
self.stickers = stickers or []
class User:
def __init__(self, id, first_name="", last_name="", username=None, is_bot=False, _raw=None):
self.id = int(id)
self.first_name = first_name or ""
self.last_name = last_name or ""
self.username = username or None
self.is_bot = bool(is_bot)
self._raw = _raw
@property
def full_name(self):
return f"{self.first_name} {self.last_name}".strip() or self.first_name or "مستخدم"
def mention_html(self, name=None):
label = html.escape(name or self.full_name)
return f'<a href="tg://user?id={self.id}">{label}</a>'
@classmethod
def from_telethon(cls, u):
if u is None:
return None
return cls(
id=getattr(u, "id", 0),
first_name=getattr(u, "first_name", "") or "",
last_name=getattr(u, "last_name", "") or "",
username=getattr(u, "username", None),
is_bot=bool(getattr(u, "bot", False)),
_raw=u,
)
class ChatMember:
def __init__(self, user, status="member", custom_title=None):
self.user = user
self.status = status
self.custom_title = custom_title
class Chat:
def __init__(self, id, type="private", title="", username=None, description="", bio="", _client=None, _raw=None):
self.id = int(id)
self.type = type
self.title = title or ""
self.username = username or None
self.description = description or ""
self.bio = bio or ""
self._client = _client
self._raw = _raw
@classmethod
def from_telethon(cls, entity, chat_id, client=None):
from telethon.tl import types as tl
ctype = "private"
title = ""
username = getattr(entity, "username", None)
if isinstance(entity, tl.Channel):
ctype = "supergroup" if getattr(entity, "megagroup", False) else "channel"
title = getattr(entity, "title", "") or ""
elif isinstance(entity, tl.Chat):
ctype = "group"
title = getattr(entity, "title", "") or ""
elif isinstance(entity, tl.User):
ctype = "private"
title = f"{getattr(entity, 'first_name', '') or ''} {getattr(entity, 'last_name', '') or ''}".strip()
else:
if int(chat_id) < 0:
ctype = "supergroup"
return cls(id=chat_id, type=ctype, title=title, username=username, _client=client, _raw=entity)
async def get_member(self, user_id):
if not self._client:
return ChatMember(User(user_id), "member")
perms = await self._client.get_permissions(self.id, int(user_id))
u_ent = None
try:
u_ent = await self._client.get_entity(int(user_id))
except Exception:
pass
user = User.from_telethon(u_ent) if u_ent else User(int(user_id))
if perms.is_creator:
st = "creator"
elif perms.is_admin:
st = "administrator"
elif getattr(perms, "is_banned", False):
st = "kicked"
elif hasattr(perms, "send_messages") and perms.send_messages is False:
st = "restricted"
else:
st = "member"
title = getattr(getattr(perms, "participant", None), "rank", None)
return ChatMember(user=user, status=st, custom_title=title)
async def get_administrators(self):
if not self._client:
return []
from telethon.tl import types as tl
admins = []
participants = await self._client.get_participants(self.id, filter=tl.ChannelParticipantsAdmins)
for u in participants:
part = getattr(u, "participant", None)
if isinstance(part, (tl.ChannelParticipantCreator, tl.ChatParticipantCreator)):
st = "creator"
else:
st = "administrator"
admins.append(ChatMember(user=User.from_telethon(u), status=st, custom_title=getattr(part, "rank", None)))
return admins
async def get_member_count(self):
if not self._client:
return 0
res = await self._client.get_participants(self.id, limit=0)
return getattr(res, "total", 0) or 0
async def ban_member(self, user_id, until_date=None):
await self._client.edit_permissions(self.id, int(user_id), view_messages=False, until_date=until_date)
async def unban_member(self, user_id):
await self._client.edit_permissions(self.id, int(user_id), view_messages=True, send_messages=True)
async def restrict_member(self, user_id, permissions, until_date=None):
kw = {}
if permissions.can_send_messages is not None:
kw["send_messages"] = permissions.can_send_messages
if permissions.can_send_other_messages is not None:
kw["send_stickers"] = permissions.can_send_other_messages
kw["send_gifs"] = permissions.can_send_other_messages
kw["send_inline"] = permissions.can_send_other_messages
if permissions.can_send_photos is not None or permissions.can_send_videos is not None:
kw["send_media"] = bool(permissions.can_send_photos or permissions.can_send_videos)
if permissions.can_add_web_page_previews is not None:
kw["embed_links"] = permissions.can_add_web_page_previews
await self._client.edit_permissions(self.id, int(user_id), until_date=until_date, **kw)
async def ban_sender_chat(self, sender_chat_id):
await self._client.edit_permissions(self.id, int(sender_chat_id), view_messages=False)
async def export_invite_link(self):
from telethon import functions
res = await self._client(functions.messages.ExportChatInviteRequest(peer=self.id))
return getattr(res, "link", "")
async def set_title(self, title):
from telethon import functions
from telethon.tl import types as tl
ent = await self._client.get_input_entity(self.id)
if isinstance(ent, tl.InputPeerChannel):
await self._client(functions.channels.EditTitleRequest(channel=ent, title=title))
else:
await self._client(functions.messages.EditChatTitleRequest(chat_id=abs(self.id), title=title))
async def set_description(self, description):
from telethon import functions
ent = await self._client.get_input_entity(self.id)
await self._client(functions.messages.EditChatAboutRequest(peer=ent, about=description or ""))
async def set_photo(self, photo):
from telethon import functions
from telethon.tl import types as tl
media = _resolve_media(photo)
data = await self._client.download_media(media, bytes)
uploaded = await self._client.upload_file(data, file_name="chat.jpg")
ent = await self._client.get_input_entity(self.id)
if isinstance(ent, tl.InputPeerChannel):
await self._client(functions.channels.EditPhotoRequest(channel=ent, photo=tl.InputChatUploadedPhoto(file=uploaded)))
else:
await self._client(functions.messages.EditChatPhotoRequest(chat_id=abs(self.id), photo=tl.InputChatUploadedPhoto(file=uploaded)))
async def set_administrator_custom_title(self, user_id, custom_title):
await self._client.edit_admin(self.id, int(user_id), title=custom_title[:16])
async def unpin_message(self, message_id=None):
await self._client.unpin_message(self.id, message_id)
async def unpin_all_messages(self):
await self._client.unpin_message(self.id)
async def leave(self):
await self._client.delete_dialog(self.id)
def _convert_entities(raw_entities):
if not raw_entities:
return []
from telethon.tl import types as tl
mapping = {
tl.MessageEntityUrl: "url",
tl.MessageEntityTextUrl: "text_link",
tl.MessageEntityMention: "mention",
tl.MessageEntityMentionName: "text_mention",
tl.MessageEntityHashtag: "hashtag",
tl.MessageEntityBotCommand: "bot_command",
tl.MessageEntityBold: "bold",
tl.MessageEntityItalic: "italic",
tl.MessageEntityCode: "code",
tl.MessageEntityPre: "pre",
tl.MessageEntityUnderline: "underline",
tl.MessageEntityStrike: "strikethrough",
tl.MessageEntitySpoiler: "spoiler",
}
out = []
for e in raw_entities:
etype = mapping.get(type(e), type(e).__name__.lower())
out.append(SimpleNamespace(type=etype, offset=getattr(e, "offset", 0), length=getattr(e, "length", 0), url=getattr(e, "url", None)))
return out
class Message:
def __init__(self, raw, chat, from_user, client, reply_to_message=None, new_chat_members=None, left_chat_member=None):
self._raw = raw
self._client = client
self.message_id = getattr(raw, "id", 0)
self.chat = chat
self.chat_id = chat.id if chat else 0
self.from_user = from_user
self.date = getattr(raw, "date", None)
self.reply_to_message = reply_to_message
self.new_chat_members = new_chat_members or []
self.left_chat_member = left_chat_member
has_media = bool(getattr(raw, "media", None))
raw_txt = getattr(raw, "raw_text", None) or getattr(raw, "message", "") or ""
ents = _convert_entities(getattr(raw, "entities", None))
if has_media and not isinstance(getattr(raw, "media", None), object.__class__):
from telethon.tl import types as tl
is_web_only = isinstance(getattr(raw, "media", None), tl.MessageMediaWebPage)
else:
is_web_only = True
if has_media and not is_web_only:
self.text = None
self.caption = raw_txt or None
self.entities = []
self.caption_entities = ents
else:
self.text = raw_txt or None
self.caption = None
self.entities = ents
self.caption_entities = []
self.photo = [PhotoSize(_pack_id(raw.photo), raw.photo)] if getattr(raw, "photo", None) else []
self.sticker = MediaFile(_pack_id(raw.sticker), raw.sticker) if getattr(raw, "sticker", None) else None
self.animation = MediaFile(_pack_id(raw.gif), raw.gif) if getattr(raw, "gif", None) else None
self.voice = MediaFile(_pack_id(raw.voice), raw.voice) if getattr(raw, "voice", None) else None
self.audio = MediaFile(_pack_id(raw.audio), raw.audio) if getattr(raw, "audio", None) else None
self.video_note = MediaFile(_pack_id(raw.video_note), raw.video_note) if getattr(raw, "video_note", None) else None
is_vid = bool(getattr(raw, "video", None) and not self.animation and not self.video_note)
self.video = MediaFile(_pack_id(raw.video), raw.video) if is_vid else None
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))
self.document = MediaFile(_pack_id(raw.document), raw.document) if is_doc else None
self.contact = getattr(raw, "contact", None)
self.location = getattr(raw, "geo", None)
self.venue = getattr(raw, "venue", None)
self.forward_origin = getattr(raw, "fwd_from", None)
self.via_bot = getattr(raw, "via_bot_id", None)
self.reply_markup = getattr(raw, "reply_markup", None)
from telethon.tl import types as tl
self.sender_chat = None
from_id = getattr(raw, "from_id", None)
if isinstance(from_id, tl.PeerChannel):
cid = int(f"-100{from_id.channel_id}")
self.sender_chat = Chat(id=cid, type="channel", _client=client)
async def reply_text(self, text, parse_mode=None, reply_markup=None, disable_web_page_preview=None, **kw):
sent = await self._client.send_message(
self.chat_id,
str(text),
reply_to=self.message_id or None,
parse_mode=_norm_parse_mode(parse_mode),
buttons=_convert_markup(reply_markup),
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
)
return Message(sent, self.chat, None, self._client)
async def _reply_file(self, file_ref, caption=None, parse_mode=None, reply_markup=None, **extra):
sent = await self._client.send_file(
self.chat_id,
_resolve_media(file_ref),
caption=str(caption) if caption else None,
reply_to=self.message_id or None,
parse_mode=_norm_parse_mode(parse_mode),
buttons=_convert_markup(reply_markup),
**extra,
)
return Message(sent, self.chat, None, self._client)
async def reply_photo(self, photo, caption=None, parse_mode=None, reply_markup=None, **kw):
return await self._reply_file(photo, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
async def reply_video(self, video, caption=None, parse_mode=None, reply_markup=None, **kw):
return await self._reply_file(video, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
async def reply_animation(self, animation, caption=None, parse_mode=None, reply_markup=None, **kw):
return await self._reply_file(animation, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
async def reply_voice(self, voice, caption=None, parse_mode=None, reply_markup=None, **kw):
return await self._reply_file(voice, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup, voice_note=True)
async def reply_audio(self, audio, caption=None, parse_mode=None, reply_markup=None, title=None, **kw):
return await self._reply_file(audio, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup)
async def reply_document(self, document, caption=None, parse_mode=None, reply_markup=None, filename=None, **kw):
return await self._reply_file(document, caption=caption, parse_mode=parse_mode, reply_markup=reply_markup, force_document=True)
async def reply_sticker(self, sticker, **kw):
return await self._reply_file(sticker)
async def reply_poll(self, question, options, is_anonymous=True, allows_multiple_answers=False, **kw):
from telethon.tl import types as tl
answers = [
tl.PollAnswer(text=tl.TextWithEntities(text=str(opt), entities=[]), option=bytes([i]))
for i, opt in enumerate(options)
]
poll = tl.InputMediaPoll(
poll=tl.Poll(
id=random.randint(1, 2**62 - 1),
question=tl.TextWithEntities(text=str(question), entities=[]),
answers=answers,
public_voters=not is_anonymous,
multiple_choice=allows_multiple_answers,
)
)
sent = await self._client.send_file(self.chat_id, poll, reply_to=self.message_id or None)
return Message(sent, self.chat, None, self._client)
async def edit_text(self, text, parse_mode=None, reply_markup=None, disable_web_page_preview=None, **kw):
await self._client.edit_message(
self.chat_id,
self.message_id,
str(text),
parse_mode=_norm_parse_mode(parse_mode),
buttons=_convert_markup(reply_markup),
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
)
async def edit_reply_markup(self, reply_markup=None, **kw):
await self._client.edit_message(
self.chat_id,
self.message_id,
buttons=_convert_markup(reply_markup),
)
async def delete(self):
await self._client.delete_messages(self.chat_id, [self.message_id])
async def pin(self, disable_notification=True):
await self._client.pin_message(self.chat_id, self.message_id, notify=not disable_notification)
async def unpin(self):
await self._client.unpin_message(self.chat_id, self.message_id)
class CallbackQuery:
def __init__(self, event, from_user, message, client):
self._event = event
self._client = client
self.id = str(getattr(event, "id", ""))
self.from_user = from_user
self.message = message
raw_data = getattr(event, "data", b"")
self.data = raw_data.decode("utf-8", errors="ignore") if isinstance(raw_data, (bytes, bytearray)) else str(raw_data)
async def answer(self, text=None, show_alert=False, **kw):
try:
await self._event.answer(text or None, alert=bool(show_alert))
except Exception:
pass
async def edit_message_text(self, text, parse_mode=None, reply_markup=None, disable_web_page_preview=None, **kw):
await self._event.edit(
str(text),
parse_mode=_norm_parse_mode(parse_mode),
buttons=_convert_markup(reply_markup),
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
)
async def edit_message_reply_markup(self, reply_markup=None, **kw):
await self._event.edit(buttons=_convert_markup(reply_markup))
async def delete_message(self):
await self._event.delete()
class ChatMemberUpdated:
def __init__(self, chat, from_user, new_chat_member, old_chat_member=None):
self.chat = chat
self.from_user = from_user
self.new_chat_member = new_chat_member
self.old_chat_member = old_chat_member
class ChatJoinRequest:
def __init__(self, chat, from_user, client):
self.chat = chat
self.from_user = from_user
self._client = client
async def approve(self):
from telethon import functions
await self._client(functions.messages.HideChatJoinRequestRequest(peer=self.chat.id, user_id=self.from_user.id, approved=True))
async def decline(self):
from telethon import functions
await self._client(functions.messages.HideChatJoinRequestRequest(peer=self.chat.id, user_id=self.from_user.id, approved=False))
class Bot:
def __init__(self, client):
self._client = client
self._me = None
async def get_me(self):
if self._me is None:
me = await self._client.get_me()
self._me = User.from_telethon(me)
return self._me
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):
sent = await self._client.send_message(
int(chat_id),
str(text),
parse_mode=_norm_parse_mode(parse_mode),
buttons=_convert_markup(reply_markup),
link_preview=not bool(disable_web_page_preview) if disable_web_page_preview is not None else False,
reply_to=reply_to_message_id,
)
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
async def send_photo(self, chat_id, photo, caption=None, parse_mode=None, reply_markup=None, **kw):
sent = await self._client.send_file(
int(chat_id),
_resolve_media(photo),
caption=str(caption) if caption else None,
parse_mode=_norm_parse_mode(parse_mode),
buttons=_convert_markup(reply_markup),
)
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
async def send_audio(self, chat_id, audio, caption=None, parse_mode=None, reply_markup=None, title=None, **kw):
sent = await self._client.send_file(
int(chat_id),
_resolve_media(audio),
caption=str(caption) if caption else None,
parse_mode=_norm_parse_mode(parse_mode),
buttons=_convert_markup(reply_markup),
)
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
async def send_sticker(self, chat_id, sticker, **kw):
sent = await self._client.send_file(int(chat_id), _resolve_media(sticker))
return Message(sent, Chat(int(chat_id), _client=self._client), None, self._client)
async def delete_message(self, chat_id, message_id):
await self._client.delete_messages(int(chat_id), [int(message_id)])
async def get_chat(self, chat_id):
from telethon import functions
from telethon.tl import types as tl
ent = await self._client.get_entity(int(chat_id))
chat = Chat.from_telethon(ent, int(chat_id), self._client)
try:
if isinstance(ent, tl.User):
full = await self._client(functions.users.GetFullUserRequest(ent))
chat.bio = getattr(getattr(full, "full_user", None), "about", "") or ""
elif isinstance(ent, tl.Channel):
full = await self._client(functions.channels.GetFullChannelRequest(ent))
chat.description = getattr(getattr(full, "full_chat", None), "about", "") or ""
elif isinstance(ent, tl.Chat):
full = await self._client(functions.messages.GetFullChatRequest(ent.id))
chat.description = getattr(getattr(full, "full_chat", None), "about", "") or ""
except Exception:
pass
return chat
async def get_chat_member(self, chat_id, user_id):
return await Chat(int(chat_id), _client=self._client).get_member(user_id)
async def get_user_profile_photos(self, user_id, limit=1):
photos = await self._client.get_profile_photos(int(user_id), limit=limit)
groups = [[PhotoSize(_pack_id(p), p)] for p in photos]
return UserProfilePhotos(groups)
async def get_sticker_set(self, name):
from telethon import functions
from telethon.tl import types as tl
res = await self._client(
functions.messages.GetStickerSetRequest(
stickerset=tl.InputStickerSetShortName(short_name=str(name)),
hash=0,
)
)
stickers = [MediaFile(_pack_id(doc), doc) for doc in getattr(res, "documents", [])]
return StickerSet(stickers)
class Update:
ALL_TYPES = []
def __init__(
self,
message=None,
edited_message=None,
callback_query=None,
my_chat_member=None,
chat_join_request=None,
):
self.message = message
self.edited_message = edited_message
self.callback_query = callback_query
self.my_chat_member = my_chat_member
self.chat_join_request = chat_join_request
@property
def effective_message(self):
if self.message:
return self.message
if self.edited_message:
return self.edited_message
if self.callback_query:
return self.callback_query.message
return None
@property
def effective_chat(self):
if self.effective_message:
return self.effective_message.chat
if self.my_chat_member:
return self.my_chat_member.chat
if self.chat_join_request:
return self.chat_join_request.chat
return None
@property
def effective_user(self):
if self.callback_query:
return self.callback_query.from_user
if self.effective_message:
return self.effective_message.from_user
if self.my_chat_member:
return self.my_chat_member.from_user
if self.chat_join_request:
return self.chat_join_request.from_user
return None
|