Skip to content

Commit 49b6cd6

Browse files
authored
move kang command to separate module from stickertools (#473)
1 parent 4073b44 commit 49b6cd6

File tree

7 files changed

+318
-248
lines changed

7 files changed

+318
-248
lines changed

assistant/inlinestuff.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,3 +621,20 @@ async def inline_tl(ult):
621621
"Tʟ Sᴇᴀʀᴄʜ": "tl",
622622
}
623623
)
624+
625+
# --------------- Handle users who haven't started the assistant bot ---------------
626+
@in_pattern("startbot")
627+
async def start_bot(event):
628+
result = await event.builder.article(
629+
title="Start Assistant Bot to Continue",
630+
text=(
631+
"To create or manage your sticker pack, you need to start the assistant bot first.\n\n"
632+
"Click the button below to start it."
633+
),
634+
buttons=[
635+
[Button.url("Start Bot", f"https://t.me/{asst.me.username}")]
636+
]
637+
)
638+
await event.answer([result], private=True, cache_time=0, gallery=False)
639+
640+

plugins/stickers.py

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
# Ultroid - UserBot
2+
# Copyright (C) 2021-2023 TeamUltroid
3+
#
4+
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5+
# PLease read the GNU Affero General Public License in
6+
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7+
8+
"""
9+
❍ Commands Available -
10+
11+
• `{i}kang <reply to image/sticker/text>`
12+
Kang the sticker (add to your pack).
13+
"""
14+
15+
import contextlib
16+
import os
17+
import random, string
18+
from secrets import token_hex
19+
20+
from telethon import errors
21+
from telethon.errors.rpcerrorlist import StickersetInvalidError
22+
from telethon.tl.functions.messages import GetStickerSetRequest as GetSticker
23+
from telethon.tl.functions.messages import UploadMediaRequest
24+
from telethon.tl.functions.stickers import AddStickerToSetRequest as AddSticker
25+
from telethon.tl.functions.stickers import CreateStickerSetRequest
26+
from telethon.tl.types import (
27+
DocumentAttributeSticker,
28+
InputPeerSelf,
29+
InputStickerSetEmpty,
30+
)
31+
from telethon.errors.rpcerrorlist import ChatSendInlineForbiddenError
32+
from telethon.tl.types import InputStickerSetItem as SetItem
33+
from telethon.tl.types import InputStickerSetShortName, User
34+
from telethon.utils import get_display_name, get_extension, get_input_document
35+
from telethon.errors import PeerIdInvalidError
36+
37+
from . import LOGS, asst, fetch, udB, ultroid_cmd, get_string,resize_photo_sticker,quotly
38+
39+
async def packExists(packId):
40+
source = await fetch(f"https://t.me/addstickers/{packId}")
41+
return (
42+
not b"""<div class="tgme_page_description">
43+
A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>.
44+
</div>"""
45+
in source
46+
)
47+
48+
async def GetUniquePackName():
49+
packName = f"{random.choice(string.ascii_lowercase)}{token_hex(random.randint(4, 8))}_by_{asst.me.username}"
50+
return await GetUniquePackName() if await packExists(packName) else packName
51+
52+
53+
# TODO: simplify if possible
54+
55+
def getName(sender, packType: str):
56+
title = f"{get_display_name(sender)}'s Kang Pack"
57+
if packType != "static":
58+
title += f" ({packType.capitalize()})"
59+
return title
60+
61+
async def AddToNewPack(file, emoji, sender_id, title: str):
62+
sn = await GetUniquePackName()
63+
return await asst(
64+
CreateStickerSetRequest(
65+
user_id=sender_id,
66+
title=title,
67+
short_name=sn,
68+
stickers=[SetItem(file, emoji=emoji)],
69+
software="@TeamUltroid",
70+
)
71+
)
72+
73+
async def inline_query_fallback(ult):
74+
try:
75+
result = await ult.client.inline_query(asst.me.username, "startbot")
76+
if result:
77+
await result[0].click(ult.chat_id, hide_via=True)
78+
except (ChatSendInlineForbiddenError):
79+
await ult.eor(
80+
f"Inline mode is disabled in this chat.\n\n"
81+
f"To create or manage your sticker pack, you need to start the assistant bot first.\n\n"
82+
f"Click the button below to start it:\n"
83+
f"[Start Bot](https://t.me/{asst.me.username})",
84+
parse_mode="md"
85+
)
86+
return
87+
88+
@ultroid_cmd(pattern="kang", manager=True)
89+
async def kang_func(ult):
90+
"""kang (reply message)
91+
Create sticker and add to pack"""
92+
sender = await ult.get_sender()
93+
if not isinstance(sender, User):
94+
return
95+
sender_id = sender.id
96+
if not ult.is_reply:
97+
return await ult.eor("`Reply to a message..`", time=5)
98+
try:
99+
emoji = ult.text.split(maxsplit=1)[1]
100+
except IndexError:
101+
emoji = None
102+
reply = await ult.get_reply_message()
103+
ult = await ult.eor(get_string("com_1"))
104+
type_, dl = "static", None
105+
if reply.sticker:
106+
file = get_input_document(reply.sticker)
107+
if not emoji:
108+
emoji = reply.file.emoji
109+
name = reply.file.name
110+
ext = get_extension(reply.media)
111+
attr = list(
112+
filter(
113+
lambda prop: isinstance(prop, DocumentAttributeSticker),
114+
reply.document.attributes,
115+
)
116+
)
117+
inPack = attr and not isinstance(attr[0].stickerset, InputStickerSetEmpty)
118+
with contextlib.suppress(KeyError):
119+
type_ = {".webm": "video", ".tgs": "animated"}[ext]
120+
if type_ or not inPack:
121+
dl = await reply.download_media()
122+
elif reply.photo:
123+
dl = await reply.download_media()
124+
name = "sticker.webp"
125+
image = resize_photo_sticker(dl)
126+
image.save(name, "WEBP")
127+
try:
128+
os.remove(dl)
129+
except:
130+
pass
131+
dl = name
132+
elif reply.text:
133+
try:
134+
reply = await ult.get_reply_message()
135+
replied_to = await reply.get_reply_message()
136+
sender_user = await ult.client.get_entity(reply.sender_id)
137+
quotly_file = await quotly.create_quotly(
138+
reply, bg="black", reply=replied_to, sender=sender_user)
139+
except Exception as er:
140+
return await ult.edit(f"Quotly error: {er}")
141+
message = await reply.reply("Quotly by Ultroid", file=quotly_file)
142+
dl = quotly_file
143+
else:
144+
return await ult.eor("`Reply to sticker or text to add it in your pack...`")
145+
if not emoji:
146+
emoji = "🏵"
147+
if dl:
148+
upl = await asst.upload_file(dl)
149+
file = get_input_document(await asst(UploadMediaRequest(InputPeerSelf(), upl)))
150+
try:
151+
os.remove(dl)
152+
except:
153+
pass
154+
get_ = udB.get_key("STICKERS") or {}
155+
title = getName(sender, type_)
156+
if not get_.get(sender_id) or not get_.get(sender_id, {}).get(type_):
157+
try:
158+
pack = await AddToNewPack(file, emoji, sender.id, title)
159+
except (ValueError, PeerIdInvalidError) as e:
160+
await inline_query_fallback(ult)
161+
return
162+
except Exception as er:
163+
return await ult.eor(str(er))
164+
sn = pack.set.short_name
165+
if not get_.get(sender_id):
166+
get_.update({sender_id: {type_: [sn]}})
167+
else:
168+
get_[sender_id].update({type_: [sn]})
169+
udB.set_key("STICKERS", get_)
170+
return await ult.edit(
171+
f"**Kanged Successfully!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})",
172+
link_preview=False
173+
)
174+
name = get_[sender_id][type_][-1]
175+
try:
176+
await asst(GetSticker(InputStickerSetShortName(name), hash=0))
177+
except StickersetInvalidError:
178+
get_[sender_id][type_].remove(name)
179+
try:
180+
await asst(
181+
AddSticker(InputStickerSetShortName(name), SetItem(file, emoji=emoji))
182+
)
183+
except (errors.StickerpackStickersTooMuchError, errors.StickersTooMuchError):
184+
try:
185+
pack = await AddToNewPack(file, emoji, sender.id, title)
186+
sn = pack.set.short_name
187+
except (ValueError, PeerIdInvalidError) as e:
188+
await inline_query_fallback(ult)
189+
return
190+
except Exception as er:
191+
return await ult.eor(str(er))
192+
get_[sender_id][type_].append(pack.set.short_name)
193+
udB.set_key("STICKERS", get_)
194+
return await ult.edit(
195+
f"**Created New Kang Pack!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})",
196+
link_preview=False
197+
)
198+
except Exception as er:
199+
LOGS.exception(er)
200+
return await ult.edit(str(er))
201+
await ult.edit(
202+
f"Sticker Added to Pack Successfully\n**Link :** [Click Here](https://t.me/addstickers/{name})",
203+
link_preview=False
204+
)
205+
206+
207+
@ultroid_cmd(pattern="listpack", manager=True)
208+
async def do_magic(ult):
209+
"""Get list of sticker packs."""
210+
ko = udB.get_key("STICKERS") or {}
211+
if not ko.get(ult.sender_id):
212+
return await ult.reply("No Sticker Pack Found!")
213+
al_ = []
214+
ul = ko[ult.sender_id]
215+
for _ in ul.keys():
216+
al_.extend(ul[_])
217+
msg = "• **Stickers Owned by You!**\n\n"
218+
for _ in al_:
219+
try:
220+
pack = await ult.client(GetSticker(InputStickerSetShortName(_), hash=0))
221+
msg += f"• [{pack.set.title}](https://t.me/addstickers/{_})\n"
222+
except StickersetInvalidError:
223+
for type_ in ["animated", "video", "static"]:
224+
if ul.get(type_) and _ in ul[type_]:
225+
ul[type_].remove(_)
226+
udB.set_key("STICKERS", ko)
227+
await ult.reply(msg)

0 commit comments

Comments
 (0)