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