forked from friendly-telegram/modules-repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stickers.py
352 lines (331 loc) · 18.1 KB
/
stickers.py
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
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2019 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# requires: git+https://gitlab.com/mattia.basaglia/python-lottie@master cairosvg Pillow>=6.1.0
from .. import loader, utils
import logging
import warnings
import itertools
import asyncio
from io import BytesIO
from PIL import Image
logger = logging.getLogger(__name__)
try:
import lottie
except OSError:
logger.exception("Lottie not available")
warnings.simplefilter("error", Image.DecompressionBombWarning)
@loader.tds
class StickersMod(loader.Module):
"""Tasks with stickers"""
strings = {"name": "Stickers",
"stickers_username_cfg_doc": "Bot to use to create stickers",
"sticker_size_cfg_doc": "The size of one sticker",
"default_sticker_emoji_cfg_doc": "The emoji to use for stickers by default",
"what_pack": "<b>You must specify which pack you would like to add the sticker to</b>",
"what_photo": "<b>Reply to a sticker or photo to add it to your sticker pack</b>",
"not_animated_pack": "<b>Animated stickers can only be added to animated packs</b>",
"internal_error": "<b>Something went wrong while adding the sticker</b>",
"bad_emojis": "<b>The emoji(s) you gave are invalid</b>",
"animated_pack": "<b>Non-animated stickers cannot be added to animated packs</b>",
"new_pack": "<b>Create a sticker pack first</b>",
"pack_full": "<b>That pack is full. Delete some stickers or try making a new pack</b>",
"added": "<b>Sticker added to</b> <a href='{}'>pack</a><b>!</b>",
"bad_animated_sticker": "<b>Reply to an animated sticker to convert to a GIF</b>"}
def __init__(self):
self.config = loader.ModuleConfig("STICKERS_USERNAME", "Stickers",
lambda m: self.strings("stickers_username_cfg_doc", m),
"STICKER_SIZE", (512, 512), lambda m: self.strings("sticker_size_cfg_doc", m),
"DEFAULT_STICKER_EMOJI", u"🤔",
lambda m: self.strings("default_sticker_emoji_cfg_doc", m))
self._lock = asyncio.Lock()
async def kangcmd(self, message): # noqa: C901 # TODO: split this into helpers
"""Use in reply or with an attached media:
.kang <pack name> [emojis]
If pack is not matched the most recently created will be used instead"""
args = utils.get_args(message)
if len(args) not in (1, 2):
logger.debug("wrong args len(%s) or bad args(%s)", len(args), args)
await utils.answer(message, self.strings("what_pack", message))
return
if not message.is_reply:
if message.sticker or message.photo:
logger.debug("user sent photo/sticker directly not reply")
sticker = message
else:
logger.debug("user didnt send any sticker/photo or reply")
async for sticker in message.client.iter_messages(message.to_id, 10):
if sticker.sticker or sticker.photo:
break # Changes message into the right one
else:
sticker = await message.get_reply_message()
if not (sticker.sticker or sticker.photo):
await utils.answer(message, self.strings("what_photo", message))
return
logger.debug("user did send photo/sticker")
if len(args) > 1:
emojis = args[1]
elif sticker.sticker:
emojis = sticker.file.emoji
else:
emojis = None
if not emojis:
emojis = self.config["DEFAULT_STICKER_EMOJI"]
logger.debug(emojis)
animated = sticker.file.mime_type == "application/x-tgsticker"
try:
img = BytesIO()
await sticker.download_media(file=img)
img.seek(0)
logger.debug(img)
if animated:
async with self._lock:
conv = message.client.conversation("t.me/" + self.config["STICKERS_USERNAME"],
timeout=5, exclusive=True)
async with conv:
first = await conv.send_message("/cancel")
await conv.get_response()
await conv.send_message("/addsticker")
buttons = (await conv.get_response()).buttons
if buttons is not None:
logger.debug("there are buttons, good")
button = click_buttons(buttons, args[0])
await button.click()
else:
logger.warning("there's no buttons!")
await message.client.send_message("t.me/" + self.config["STICKERS_USERNAME"], "/cancel")
await utils.answer(message, "Something went wrong")
return
# We have sent the pack we wish to modify.
# Upload sticker
r0 = await conv.get_response()
if ".PSD" in r0.message:
logger.error("bad response from stickerbot 0")
logger.error(r0)
await utils.answer(message, self.strings("not_animated_pack", message))
msgs = []
async for msg in message.client.iter_messages(entity="t.me/"
+ self.config["STICKERS_USERNAME"],
min_id=first.id, reverse=True):
msgs += [msg.id]
logger.debug(msgs)
await message.client.delete_messages("t.me/" + self.config["STICKERS_USERNAME"],
msgs + [first])
return
uploaded = await message.client.upload_file(img, file_name="AnimatedSticker.tgs")
m1 = await conv.send_file(uploaded, force_document=True)
m2 = await conv.send_message(emojis)
await conv.send_message("/done")
# Block now so that we mark it all as read
await message.client.send_read_acknowledge(conv.chat_id)
r1 = await conv.get_response(m1)
r2 = await conv.get_response(m2)
if "/done" not in r2.message:
# That's an error
logger.error("Bad response from StickerBot 1")
logger.error(r0)
logger.error(r1)
logger.error(r2)
await utils.answer(message, self.strings("internal_error", message))
return
msgs = []
async for msg in message.client.iter_messages(entity="t.me/" + self.config["STICKERS_USERNAME"],
min_id=first.id,
reverse=True):
msgs += [msg.id]
logger.debug(msgs)
await message.client.delete_messages("t.me/" + self.config["STICKERS_USERNAME"], msgs + [first])
if "emoji" in r2.message:
# The emoji(s) are invalid.
logger.error("Bad response from StickerBot 2")
logger.error(r2)
await utils.answer(message, self.strings("bad_emojis", message))
return
else:
try:
thumb = BytesIO()
task = asyncio.ensure_future(utils.run_sync(resize_image, img, self.config["STICKER_SIZE"], thumb))
thumb.name = "sticker.png"
# The data is now in thumb.
# Lock access to @Stickers
async with self._lock:
# Without t.me/ there is ambiguity; Stickers could be a name,
# in which case the wrong entity could be returned
# TODO should this be translated?
conv = message.client.conversation("t.me/" + self.config["STICKERS_USERNAME"],
timeout=5, exclusive=True)
async with conv:
first = await conv.send_message("/cancel")
await conv.get_response()
await conv.send_message("/addsticker")
r0 = await conv.get_response()
buttons = r0.buttons
if buttons is not None:
logger.debug("there are buttons, good")
button = click_buttons(buttons, args[0])
m0 = await button.click()
elif "/newpack" in r0.message:
await utils.answer(message, self.strings("new_pack", message))
return
else:
logger.warning("there's no buttons!")
m0 = await message.client.send_message("t.me/" + self.config["STICKERS_USERNAME"],
"/cancel")
await utils.answer(message, self.strings("internal_error", message))
return
# We have sent the pack we wish to modify.
# Upload sticker
r0 = await conv.get_response()
if ".TGS" in r0.message:
logger.error("bad response from stickerbot 0")
logger.error(r0)
await utils.answer(message, self.strings("animated_pack", message))
msgs = []
async for msg in message.client.iter_messages(entity="t.me/"
+ self.config["STICKERS_USERNAME"],
min_id=first.id,
reverse=True):
msgs += [msg.id]
logger.debug(msgs)
await message.client.delete_messages("t.me/" + self.config["STICKERS_USERNAME"],
msgs + [first])
return
if "120" in r0.message:
logger.error("bad response from stickerbot 0")
logger.error(r0)
await utils.answer(message, self.strings("pack_full", message))
msgs = []
async for msg in message.client.iter_messages(entity="t.me/"
+ self.config["STICKERS_USERNAME"],
min_id=first.id,
reverse=True):
if msg.id != m0.id:
msgs += [msg.id]
logger.debug(msgs)
await message.client.delete_messages("t.me/" + self.config["STICKERS_USERNAME"],
msgs + [first])
return
await task # We can resize the thumbnail while the sticker bot is processing other data
thumb.seek(0)
m1 = await conv.send_file(thumb, allow_cache=False, force_document=True)
r1 = await conv.get_response(m1)
m2 = await conv.send_message(emojis)
r2 = await conv.get_response(m2)
if "/done" in r2.message:
await conv.send_message("/done")
else:
logger.error(r1)
logger.error(r2)
logger.error("Bad response from StickerBot 0")
await utils.answer(message, self.strings("internal_error", message))
await message.client.send_read_acknowledge(conv.chat_id)
if "/done" not in r2.message:
# That's an error
logger.error("Bad response from StickerBot 1")
logger.error(r1)
logger.error(r2)
await utils.answer(message, self.strings("internal_error", message))
return
msgs = []
async for msg in message.client.iter_messages(entity="t.me/"
+ self.config["STICKERS_USERNAME"],
min_id=first.id,
reverse=True):
msgs += [msg.id]
logger.debug(msgs)
await message.client.delete_messages("t.me/" + self.config["STICKERS_USERNAME"], msgs + [first])
if "emoji" in r2.message:
# The emoji(s) are invalid.
logger.error("Bad response from StickerBot 2")
logger.error(r2)
await utils.answer(message, self.strings("bad_emojis", message))
return
finally:
thumb.close()
finally:
img.close()
packurl = utils.escape_html("https://t.me/addstickers/{}".format(button.text))
await utils.answer(message, self.strings("added", message).format(packurl))
async def gififycmd(self, message):
"""Convert the replied animated sticker to a GIF"""
args = utils.get_args(message)
fps = 5
quality = 256
try:
if len(args) == 1:
fps = int(args[0])
elif len(args) == 2:
quality = int(args[0])
fps = int(args[1])
except ValueError:
logger.exception("Failed to parse quality/fps")
target = await message.get_reply_message()
if target is None or target.file is None or target.file.mime_type != "application/x-tgsticker":
await utils.answer(message, self.strings("bad_animated_sticker", message))
return
try:
file = BytesIO()
await target.download_media(file)
file.seek(0)
anim = await utils.run_sync(lottie.parsers.tgs.parse_tgs, file)
file.close()
result = BytesIO()
result.name = "animation.gif"
await utils.run_sync(lottie.exporters.gif.export_gif, anim, result, quality, fps)
result.seek(0)
await utils.answer(message, result)
finally:
try:
file.close()
except UnboundLocalError:
pass
try:
result.close()
except UnboundLocalError:
pass
def click_buttons(buttons, target_pack):
buttons = list(itertools.chain.from_iterable(buttons))
# Process in reverse order; most difficult to match first
try:
return buttons[int(target_pack)]
except (IndexError, ValueError):
pass
logger.debug(buttons)
for button in buttons:
logger.debug(button)
if button.text == target_pack:
return button
for button in buttons:
if target_pack in button.text:
return button
for button in buttons:
if target_pack.lower() in button.text.lower():
return button
return buttons[-1]
def resize_image(img, size, dest):
# Wrapper for asyncio purposes
try:
im = Image.open(img)
# We used to use thumbnail(size) here, but it returns with a *max* dimension of 512,512
# rather than making one side exactly 512 so we have to calculate dimensions manually :(
if im.width == im.height:
size = (512, 512)
elif im.width < im.height:
size = (int(512 * im.width / im.height), 512)
else:
size = (512, int(512 * im.height / im.width))
logger.debug("Resizing to %s", size)
im.resize(size).save(dest, "PNG")
finally:
im.close()
img.close()
del im