-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
357 lines (240 loc) · 10.6 KB
/
main.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
353
354
355
356
357
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""
This Bot uses the Updater class to handle the bot.
First, a few callback functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Example of a bot-user conversation using ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)
import logging
from PIL import Image
import os
import json
ASPECT_RATIO, CANVAS_SIZE, SEND_PHOTO, CUSTOM_AR, CUSTOM_CS = range(5)
PREFIX = 'brd_'
JPEG_QUALITY = 100
ASPECT_KEYBOARD = [['1/1', '4/5', '16/9'],['9/16', '9/19', 'Custom']]
CANVAS_KEYBOARD = [['1', '1.02', '1.05'],['1.1', '1.2', 'Custom']]
ASPECT_QUESTION = 'What aspect ratio are you looking for? \nYou can always /cancel.'
CANVAS_QUESTION = 'How large do you want your canvas to be? \nYou can always /cancel.'
data = {}
# Lue JSON-tiedosto
def file_read(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
saved_data = json.load(file)
file.close()
return saved_data
except FileNotFoundError:
print("Oh dog file not found")
exit(1)
SETTINGS = file_read("settings.json")
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def start(bot, update):
bot.send_message(chat_id=update.message.chat_id,
text="Hello! Send me an uncompressed picture!")
def borderify(name, aspect_ratio=4/5, margin_ratio=1.1, background_color=(255, 255, 255)):
base = Image.open(name).convert('RGB')
base_aspect_ratio = base.size[0]/base.size[1]
# Onko kuva "pystykuvampi" kuin kohde kuvasuhde
vertical = base_aspect_ratio < aspect_ratio
side_with_margin = int(base.size[int(vertical)]*margin_ratio)
# Määritellään taustan koko
if vertical:
bg_size = (int(side_with_margin*aspect_ratio), side_with_margin)
else:
bg_size = (side_with_margin, int(side_with_margin/aspect_ratio))
# Taustaväri
bg = Image.new('RGB', bg_size, background_color)
# Keskelle
img_w, img_h = base.size
bg_w, bg_h = bg.size
offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
bg.paste(base, offset)
return bg
def photo(bot, update):
user = update.message.from_user
user_id = update.message.from_user.id
logger.info("%s sent a file", user.username)
no_data_text = "Use /settings to set your preferred values first, then resend the file. Tip: you can also forward the file to me again."
if user_id not in data:
bot.send_message(chat_id=update.message.chat_id, text=no_data_text)
return
if "cs" not in data[user_id] or "ar" not in data[user_id]:
bot.send_message(chat_id=update.message.chat_id, text=no_data_text)
return
valid_file_types = ["image/png", "image/jpeg"]
if update.message.document.mime_type not in valid_file_types:
logger.info("%s's file was not a picture", user.username)
bot.send_message(chat_id=update.message.chat_id, text="The picture must be in .png or .jpeg format!")
return ConversationHandler.END
if update.message.document.file_size > 5100000:
logger.info("%s's picture was over 5 MB", user.username)
bot.send_message(chat_id=update.message.chat_id, text="The picture must be 5 MB or less!")
return ConversationHandler.END
photo_file = bot.get_file(update.message.document.file_id)
photo_file.download(str(user_id) + '.jpeg')
send_photo(bot, update)
def aspect_ratio(bot, update):
if update.message.text == "Custom":
bot.send_message(chat_id=update.message.chat_id, text='Give me an aspect ratio in this from: "a/b". '
'The value must be between 1/5 and 5/1. \n'
'You can always /cancel.')
return CUSTOM_AR
user_id = update.message.from_user.id
text = update.message.text
global data
a, b = text.split("/")
ar = float(int(a)/int(b))
data[user_id] = {"ar": ar}
move_to_canvas(bot, update)
return CANVAS_SIZE
def custom_ar(bot, update):
user_id = update.message.from_user.id
try:
text = update.message.text
a, b = text.split("/")
ar = float(int(a)/int(b))
if 0.2 <= ar <= 5:
data[user_id] = {"ar": ar}
else:
raise ValueError
except (ValueError, TypeError):
bot.send_message(chat_id=update.message.chat_id, text='Incorrect value. You have to pick a value between 1/5 and 5/1.')
return CUSTOM_AR
move_to_canvas(bot, update)
return CANVAS_SIZE
def move_to_canvas(bot, update):
user = update.message.from_user
logger.info("Aspect ratio for %s: %s", user.username, update.message.text)
update.message.reply_text(CANVAS_QUESTION, reply_markup=ReplyKeyboardMarkup(CANVAS_KEYBOARD, one_time_keyboard=True))
def canvas_size(bot, update):
user = update.message.from_user
user_id = update.message.from_user.id
logger.info("Canvas size for %s: %s", user.username, update.message.text)
if update.message.text == "Custom":
bot.send_message(chat_id=update.message.chat_id, text='Give me your desired canvas size. '
'The value must be between 0 and 3. \n'
'You can always /cancel.')
return CUSTOM_CS
global data
data[user_id]["cs"] = update.message.text
return ConversationHandler.END
def custom_cs(bot, update):
user_id = update.message.from_user.id
text = update.message.text
global data
try:
cs = float(text)
if 0 <= cs <= 3:
data[user_id]["cs"] = text
else:
raise ValueError
except (ValueError, TypeError):
bot.send_message(chat_id=update.message.chat_id, text='Incorrect value. You have to pick a value between 0 and 3.')
return CUSTOM_CS
return ConversationHandler.END
def send_photo(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
sent_message = bot.send_message(chat_id=chat_id, text='Working on your file...', reply_markup=ReplyKeyboardRemove())
ar = float(data[user_id]["ar"])
cs = float(data[user_id]["cs"])
filename = str(user_id) + '.jpeg'
pic = borderify(filename, ar, cs, (255, 255, 255))
pic.save(os.path.join(PREFIX+filename), 'JPEG', quality=JPEG_QUALITY, optimize=True)
bot.send_document(chat_id=chat_id, document=open((PREFIX + filename), 'rb'))
bot.delete_message(chat_id, sent_message.message_id)
delete_data(update)
def cancel(bot, update):
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.username)
update.message.reply_text("See you later! I've deleted everything you've sent me. :)", reply_markup=ReplyKeyboardRemove())
delete_data(update)
return ConversationHandler.END
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def delete_data(update):
chat_id = update.message.chat.id
filename = str(chat_id) + '.jpeg'
os.remove(filename)
try:
os.remove((PREFIX + filename))
except FileNotFoundError:
pass
def compressed_photo(bot, update):
chat_id = update.message.chat.id
user = update.message.from_user
logger.info("User %s sent a compressed image.", user.username)
reply = "Please send me the photo uncompressed.\n" \
"(Attach -> file -> gallery)"
bot.send_message(chat_id=chat_id, text=reply)
def settings(bot, update):
logger.info("%s settings", update.message.from_user.username)
reply_keyboard = ASPECT_KEYBOARD
update.message.reply_text(ASPECT_QUESTION, reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
return ASPECT_RATIO
def current_settings(bot, update):
user_id = update.message.from_user.id
global data
if user_id in data:
ar = str(data[user_id]["ar"])
cs = str(data[user_id]["cs"])
txt = "Aspect ratio = {}, Canvas size = {}".format(ar, cs)
else:
txt = "No values set, use /settings to set them."
bot.send_message(chat_id=update.message.chat.id, text=txt)
def help(bot, update):
txt = "1. Set values using /settings\n" \
"2. Send an uncompressed image\n" \
"3. ???\n" \
"4. Profit"
bot.send_message(chat_id=update.message.chat.id, text=txt)
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater(SETTINGS["tg_token"])
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Add conversation handler with the states ASPECT_RATIO, CANVAS_SIZE, LOCATION and BIO
conv_handler = ConversationHandler(
entry_points=[CommandHandler('settings', settings)],
states={
ASPECT_RATIO: [RegexHandler('^(1/1|4/5|16/9|9/16|9/19|Custom)$', aspect_ratio)],
CUSTOM_AR: [MessageHandler(Filters.text, custom_ar)],
CANVAS_SIZE: [RegexHandler('^(1|1.02|1.05|1.1|1.2|Custom)$', canvas_size)],
CUSTOM_CS: [MessageHandler(Filters.text, custom_cs)],
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dp.add_handler(conv_handler)
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('help', help))
dp.add_handler(CommandHandler('settings', settings))
dp.add_handler(CommandHandler('current', current_settings))
dp.add_handler(MessageHandler(Filters.photo, compressed_photo))
dp.add_handler(MessageHandler(Filters.document, photo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
# updater.idle()
if __name__ == '__main__':
main()