main.py (view raw)
1from PIL import Image
2from Api import get_random_image, rating_normal, rating_lewd
3from Effects import tt_bt_effect, splash_effect, wot_effect, text_effect
4from Constants import get_localized_string as l
5
6from dotenv import load_dotenv
7load_dotenv()
8import os, logging
9logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
10from io import BytesIO
11
12from telegram.error import TelegramError
13from telegram.ext import Updater, CallbackContext, CommandHandler, MessageHandler, Filters, PicklePersistence
14from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
15
16lang = 'us'
17
18def _get_args(context):
19
20 logging.info(context.args)
21 return ' '.join(context.args)
22
23def _img_to_bio(image):
24
25 bio = BytesIO()
26
27 if image.mode in ("RGBA", "P"):
28 image = image.convert("RGB")
29
30 image.save(bio, 'JPEG')
31 bio.seek(0)
32 return bio
33
34def _get_message_content(message):
35
36 image = None
37 if len(message.photo) > 0:
38 image = message.photo[-1].get_file()
39 image = Image.open(BytesIO(image.download_as_bytearray()))
40
41 content = ""
42 if message.text is not None:
43 content = message.text.strip()
44 elif message.caption is not None:
45 content = message.caption.strip()
46
47 lines = content.split("\n")
48 r = lines[0].split(" ")
49
50 try:
51 if r[0][0] == '/':
52 r.pop(0)
53 except IndexError:
54 pass
55
56 lines[0] = " ".join(r)
57 content = "\n".join(lines)
58
59 return image, content, _get_author(message)
60
61def _get_reply(message, fallback=""):
62
63 if message is None:
64 return None, fallback, None
65
66 image, content, author = _get_message_content(message)
67
68 return image, content, author
69
70def _get_lewd(context):
71
72 try:
73 return context.chat_data["lewd"]
74 except KeyError:
75 return False
76
77def _get_image(context, tag="", bio=True):
78
79 if context is not None:
80 if _get_lewd(context):
81 image, url = get_random_image(rating_lewd, tag)
82 else:
83 image, url = get_random_image(rating_normal, tag)
84
85 if image is None:
86 logging.warning("Getting Image failed")
87 raise TelegramError("bad image")
88
89 markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]])
90
91 if bio:
92 return _img_to_bio(image), markup
93 return image, markup
94
95def _get_all(update, check_fn, context):
96
97 image_reply, text_reply, author_reply = _get_reply(update.message.reply_to_message)
98 image_content, text_content, author_content = _get_message_content(update.message)
99
100 info_struct = {
101 "reply": {
102 "author": author_reply,
103 "text": text_reply,
104 "image": image_reply
105 },
106 "content": {
107 "author": author_content,
108 "text": text_content,
109 "image": image_content
110 }
111 }
112
113 logging.info(f"User {update.message.from_user.username} typed: {str(update.message.text)}")
114
115 content = check_fn(info_struct)
116
117 if content is None:
118 return None, None, None
119
120 markup = ""
121 image = None
122
123 if image_reply is not None:
124 image = image_reply
125
126 if image_content is not None:
127 image = image_content
128
129 if image is None:
130 image, markup = _get_image(context, bio=False)
131
132 return content, image, markup
133
134def start(update: Update, context: CallbackContext):
135 context.bot.send_message(chat_id=update.effective_chat.id, text=l("welcome", lang))
136
137def set_lewd(update: Update, context: CallbackContext):
138
139 try:
140 output = False if context.chat_data["lewd"] else True
141 except KeyError:
142 output = True
143
144 context.chat_data['lewd'] = output
145 message = l("lewd_toggle", lang).format(l("enabled", lang) if output else l("disabled", lang))
146
147 context.bot.send_message(chat_id=update.effective_chat.id, text=message)
148
149def pic(update: Update, context: CallbackContext):
150
151 try:
152 tag = " " + context.args[0]
153 except IndexError:
154 tag = ""
155
156 image, markup = _get_image(context, tag)
157 update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)
158
159def raw(update: Update, context: CallbackContext):
160
161 tag = ""
162 try:
163 tag += " " + context.args[0]
164 tag += " " + context.args[1]
165 except IndexError:
166 pass
167
168 image, url = get_random_image("", tag)
169
170 if image is None:
171 logging.warning("Getting Image failed")
172 raise TelegramError("bad image")
173
174 image = _img_to_bio(image)
175 markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]])
176
177 update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)
178
179def pilu(update: Update, context: CallbackContext):
180
181 logging.warning(f"User {update.message.from_user.username} requested an explicit pic.")
182 try:
183 tag = " " + context.args[0]
184 except IndexError:
185 tag = ""
186 image, url = get_random_image("rating:e" + tag)
187 if image is None:
188 logging.warning("Getting Image failed")
189 raise TelegramError("bad image")
190 return
191
192 image = _img_to_bio(image)
193 markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]])
194
195 update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)
196
197def _format_author(user):
198
199 if user.username is not None:
200 return user.full_name + f" ({user.username})"
201 return user.full_name
202
203def _get_author(message):
204
205 if message.forward_from is not None:
206 return _format_author(message.forward_from)
207
208 if message.forward_sender_name is not None:
209 return message.forward_sender_name
210
211 if message.forward_from_chat is not None:
212 return message.forward_from_chat.title + ("" if message.forward_from_chat.username is None else f" ({message.forward_from_chat.username})")
213
214 return _format_author(message.from_user)
215
216def tt_check(info):
217
218 reply = info['reply']['text']
219 content = info['content']['text']
220
221 input_text = f"{reply} {content}".replace("\n", " ")
222
223 if input_text.strip() == "":
224 return None
225
226 return input_text
227
228def ttbt_check(info):
229
230 reply = info['reply']['text']
231 content = info['content']['text']
232
233 input_text = f"{reply}\n{content}"
234
235 if input_text.strip() == "":
236 return None
237
238 return input_text
239
240def splash_check(info):
241
242 reply = info['reply']['text']
243 content = info['content']['text']
244
245 if content.strip() == "":
246 author = info['reply']['author']
247 else:
248 author = info['content']['author']
249
250 input_text = f"{author}\n{content}\n{reply}"
251
252 if len(input_text.strip().split("\n")) < 2:
253 return None
254
255 return input_text
256
257def wot_check(info):
258
259 reply = info['reply']['text']
260 content = info['content']['text']
261
262 input_text = f"{reply}\n{content}"
263
264 if input_text.strip() == "":
265 return None
266
267 return input_text
268
269def ttbt(update: Update, context: CallbackContext):
270
271 content, image, markup = _get_all(update, ttbt_check, context)
272
273 if image is None:
274 update.message.reply_text(l("no_caption", lang))
275 return
276
277 image = _img_to_bio(tt_bt_effect(content, image))
278 update.message.reply_photo(photo=image, reply_markup=markup)
279
280
281def tt(update: Update, context: CallbackContext):
282
283 content, image, markup = _get_all(update, tt_check, context)
284
285 if image is None:
286 update.message.reply_text(l("no_caption", lang))
287 return
288
289 image = _img_to_bio(tt_bt_effect(content, image))
290 update.message.reply_photo(photo=image, reply_markup=markup)
291
292def bt(update: Update, context: CallbackContext):
293
294 content, image, markup = _get_all(update, tt_check, context)
295
296 if image is None:
297 update.message.reply_text(l("no_caption", lang))
298 return
299
300 image = _img_to_bio(tt_bt_effect("\n" + content, image))
301 update.message.reply_photo(photo=image, reply_markup=markup)
302
303def splash(update: Update, context: CallbackContext):
304
305 content, image, markup = _get_all(update, splash_check, context)
306
307 if image is None:
308 update.message.reply_text(l("no_caption", lang))
309 return
310
311 image = _img_to_bio(splash_effect(content, image))
312 update.message.reply_photo(photo=image, reply_markup=markup)
313
314def wot(update: Update, context: CallbackContext):
315
316 content, image, markup = _get_all(update, wot_check, context)
317
318 if image is None:
319 update.message.reply_text(l("no_caption", lang))
320 return
321
322 image = _img_to_bio(wot_effect(content, image))
323 update.message.reply_photo(photo=image, reply_markup=markup)
324
325def text(update: Update, context: CallbackContext):
326
327 content, image, markup = _get_all(update, wot_check, context)
328
329 if image is None:
330 update.message.reply_text(l("no_caption", lang))
331 return
332
333 image = _img_to_bio(text_effect(content, image))
334 update.message.reply_photo(photo=image, reply_markup=markup)
335
336def caps(update: Update, context: CallbackContext):
337
338 _, reply, _ = _get_reply(update.message.reply_to_message, _get_args(context))
339 context.bot.send_message(chat_id=update.effective_chat.id, text=reply.upper())
340
341def unknown(update: Update, context: CallbackContext):
342 logging.info(f"User {update.message.from_user.username} sent {update.message.text_markdown_v2} and I don't know what that means.")
343
344def error_callback(update: Update, context: CallbackContext):
345 try:
346 raise context.error
347 except TelegramError:
348 logging.error("TelegramError!!")
349 context.bot.send_message(chat_id=update.effective_chat.id, text=l('error', lang))
350
351def _add_effect_handler(dispatcher, command: str, callback):
352 dispatcher.add_handler(CommandHandler(command, callback))
353 dispatcher.add_handler(MessageHandler(Filters.caption(update=[f"/{command}"]), callback))
354
355def main():
356
357 updater = Updater(token=os.getenv("token"),
358 persistence=PicklePersistence(filename='bot-data.pkl',
359 store_bot_data=False,
360 store_callback_data=False,
361 store_user_data=False))
362
363 dispatcher = updater.dispatcher
364 dispatcher.add_error_handler(error_callback)
365
366 dispatcher.add_handler(CommandHandler('start', start))
367 dispatcher.add_handler(CommandHandler('lewd', set_lewd))
368 dispatcher.add_handler(CommandHandler('caps', caps))
369 dispatcher.add_handler(CommandHandler('pic', pic))
370 dispatcher.add_handler(CommandHandler('raw', raw))
371 dispatcher.add_handler(CommandHandler('pilu', pilu))
372
373 _add_effect_handler(dispatcher, 'ttbt', ttbt)
374 _add_effect_handler(dispatcher, 'tt', tt)
375 _add_effect_handler(dispatcher, 'bt', bt)
376 _add_effect_handler(dispatcher, 'splash', splash)
377 _add_effect_handler(dispatcher, 'wot', wot)
378 _add_effect_handler(dispatcher, 'text', text)
379
380 dispatcher.add_handler(MessageHandler(Filters.command, unknown))
381 updater.start_polling()
382 updater.idle()
383
384if __name__ == "__main__":
385 main()