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