main.py (view raw)
1from PIL import Image
2from Api import get_random_image, rating_normal, rating_lewd
3from Effects import tt_bt_effect
4import Constants as C
5from Constants import get_localized_string as l
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, BadRequest
14from telegram.ext import Updater, CallbackContext, CommandHandler, MessageHandler, Filters
15from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
16
17lang = 'us'
18
19def _get_args(context):
20 logging.info(context.args)
21 return ' '.join(context.args)
22
23def _img_to_bio(image):
24 bio = BytesIO()
25 #bio.name = 'image.jpeg'
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 _ttbt_general(context, text, image=None):
35 if text.strip() == "":
36 return None, l("no_caption", lang)
37
38 markup = ""
39 if image is None:
40 image, markup = _get_image(context, bio=False)
41 image = tt_bt_effect(text, image)
42 return _img_to_bio(image), markup
43
44def _get_reply(input, context, fallback=""):
45
46 if input is None:
47 return None, fallback
48
49 if input.photo is not None:
50 image = input.photo[-1].get_file()
51 #image = context.bot.get_file(input.photo[-1].file_id)
52 image = Image.open(BytesIO(image.download_as_bytearray()))
53
54 if input.caption is not None:
55 return image, input.caption
56
57 if input.text is not None:
58 return image, input.text
59
60 return image, fallback
61
62def _get_lewd(context):
63 try:
64 return context.chat_data["lewd"]
65 except KeyError:
66 return False
67
68def _get_image(context, bio=True):
69 if context is not None:
70 if _get_lewd(context):
71 image, url = get_random_image(rating_lewd)
72 else:
73 image, url = get_random_image(rating_normal)
74
75 if image is None:
76 logging.warning("Getting Image failed")
77 raise TelegramError("bad image")
78
79 markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]])
80
81 if bio:
82 return _img_to_bio(image), markup
83 return image, markup
84
85
86def start(update: Update, context: CallbackContext):
87 context.bot.send_message(chat_id=update.effective_chat.id, text=l("welcome", lang))
88
89def set_lewd(update: Update, context: CallbackContext):
90 try:
91 output = False if context.chat_data["lewd"] else True
92 except KeyError:
93 output = True
94
95 context.chat_data['lewd'] = output
96 message = l("lewd_toggle", lang).format(l("enabled", lang) if output else l("disabled", lang))
97
98 context.bot.send_message(chat_id=update.effective_chat.id, text=message)
99
100def pic(update: Update, context: CallbackContext):
101 image, markup = _get_image(context)
102 update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)
103
104def pilu(update: Update, context: CallbackContext):
105 logging.warning(f"User {update.message.from_user.username} requested an explicit pic.")
106 try:
107 tag = " " + context.args[0]
108 except IndexError:
109 tag = ""
110 image, url = get_random_image("e" + tag)
111 if image is None:
112 logging.warning("Getting Image failed")
113 raise TelegramError("bad image")
114 return
115
116 image = _img_to_bio(image)
117 markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]])
118
119 update.message.reply_photo(photo=image, caption=url, parse_mode="markdown", reply_markup=markup)
120
121def tt(update: Update, context: CallbackContext):
122 image, reply = _get_reply(update.message.reply_to_message, context)
123 content = _get_args(context)
124 input_text = f"{reply} {content}".replace("\n", " ")
125
126 image, markup = _ttbt_general(context, input_text, image)
127
128 if image is None:
129 update.message.reply_text(markup)
130 return
131 update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)
132
133def bt(update: Update, context: CallbackContext):
134 image, reply = _get_reply(update.message.reply_to_message, context)
135 content = _get_args(context)
136 input_text = f"{reply} {content}".replace("\n", " ")
137
138 image, markup =_ttbt_general(context, " \n" + input_text, image)
139
140 if image is None:
141 update.message.reply_text(markup)
142 return
143 update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)
144
145def ttbt(update: Update, context: CallbackContext):
146 message = update.message
147
148 image, reply = _get_reply(message.reply_to_message, context)
149 content = message.text[6:] # /ttbt[space]
150 input_text = f"{reply}\n{content}"
151
152 image, markup =_ttbt_general(context, input_text, image)
153
154 if image is None:
155 message.reply_text(markup)
156 return
157 message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)
158
159def caps(update: Update, context: CallbackContext):
160 _, reply = _get_reply(update.message.reply_to_message, context, _get_args(context))
161 context.bot.send_message(chat_id=update.effective_chat.id, text=reply.upper())
162
163def unknown(update: Update, context: CallbackContext):
164 logging.info(f"User {update.message.from_user.username} sent {update.message.text_markdown_v2} and I don't know what that means.")
165
166def error_callback(update: Update, context: CallbackContext):
167 try:
168 raise context.error
169 #except BadRequest:
170 # logging.error("BadRequest!!")
171 except TelegramError:
172 logging.error("TelegramError!!")
173 context.bot.send_message(chat_id=update.effective_chat.id, text=l('error', lang))
174def main():
175
176 updater = Updater(token=os.getenv("token"))
177 dispatcher = updater.dispatcher
178 dispatcher.add_error_handler(error_callback)
179
180 dispatcher.add_handler(CommandHandler('start', start))
181 dispatcher.add_handler(CommandHandler('lewd', set_lewd))
182 dispatcher.add_handler(CommandHandler('caps', caps))
183 dispatcher.add_handler(CommandHandler('pic', pic))
184 dispatcher.add_handler(CommandHandler('pilu', pilu))
185 dispatcher.add_handler(CommandHandler('ttbt', ttbt))
186 dispatcher.add_handler(CommandHandler('tt', tt))
187 dispatcher.add_handler(CommandHandler('bt', bt))
188
189 dispatcher.add_handler(MessageHandler(Filters.command, unknown))
190 updater.start_polling()
191 updater.idle()
192
193if __name__ == "__main__":
194 main()