-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbot.py
More file actions
230 lines (170 loc) · 6.96 KB
/
bot.py
File metadata and controls
230 lines (170 loc) · 6.96 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import User
from dotenv import load_dotenv
from validator_collection import checkers
from io import BytesIO, TextIOWrapper
import logging
import os
import requests
import make_image
load_dotenv()
TOKEN = os.getenv("CITADOR_TOKEN")
FAKE_MARK = "Esta é uma falsa citação gerada com /fake_quote"
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
def start(bot, update):
"""Send a message when the command /start is issued."""
update.message.reply_text(
"Olá! Use o comando /quote em resposta a uma mensagem ou /fake_quote para criar uma citação fake"
)
def format_name(name):
return name[1].upper() + ", " + name[0] if len(name) > 1 else name[0]
def get_user_pic(user: User):
name = user.first_name + " " + user.last_name if user.last_name else user.first_name
name = name.split(" ")
formatted_name = format_name(name)
photos = user.get_profile_photos().photos
if not photos or not photos[0]:
return formatted_name
# first photo, last version (better quality)
photo_size = photos[0][-1]
photo = photo_size.get_file().download_as_bytearray()
return (photo, (photo_size.width, photo_size.height), formatted_name)
def get_pic_from_url(url, update):
if not checkers.is_url(url):
update.message.reply_text("Use um URL válido")
return None
response = requests.get(url)
valid_content_types = ["image/jpeg", "image/png"]
if not response.headers["content-type"] in valid_content_types:
update.message.reply_text("O URL deve ser de uma imagem jpeg ou png.")
return None
image = response.content
return (image, (500, 500))
def apply_overlay(photo, quote, name, context, fake_quote=False):
if photo:
return make_image_quote(photo, quote, name, context, fake_quote)
else:
return make_image_noprofile_quote(quote, name, context)
def make_fake_quote(bot, update):
print("fake_quote " + update.effective_user.username)
splitted_text = update["message"]["text"].split()
if len(splitted_text) < 5:
update.message.reply_text(
"Use /fake_quote <url da imagem> <nome> <sobrenome> <frase>"
)
return
url = splitted_text[1]
photo = get_pic_from_url(url, update)
if photo is None:
return
fake_quote = True
name = [splitted_text[2], splitted_text[3]]
quote = splitted_text[4:]
joined_quote = " ".join(quote)
formatted_name = format_name(name)
result = apply_overlay(photo[0], joined_quote, formatted_name, None, fake_quote)
fp = image_to_object_file(result)
update.message.reply_photo(photo=fp)
def make_quote(bot, update):
print("quote " + update.effective_user.username)
if (
len(result := update["message"]["text"].split(" ", 1)) > 1
and update["message"]["forward_from"] is None
):
context = result[-1]
else:
context = None
if update["message"]["forward_from"] is not None:
if update["message"]["chat"]["type"] == "group":
return
user_pic = get_user_pic(update.message.forward_from)
quote = update["message"]["text"]
else:
if update["message"]["reply_to_message"] is None:
update.message.reply_text("Use /quote em reposta a uma mensagem.")
return
if update["message"]["reply_to_message"]["forward_from"] is not None:
user_pic = get_user_pic(update.message.reply_to_message.forward_from)
else:
user_pic = get_user_pic(update.message.reply_to_message.from_user)
quote = update["message"]["reply_to_message"]["text"]
if len(user_pic) == 3:
name = user_pic[2]
else:
name = user_pic
result = apply_overlay(user_pic[0], quote, name, context)
fp = image_to_object_file(result)
update.message.reply_photo(photo=fp)
def make_image_quote(
photo: bytearray,
quote: str,
name: str,
context: str,
fake_quote: bool=False
):
with make_image.Image.open(BytesIO(photo)) as user_pic:
user_pic = user_pic.convert("L")
quote = "“{}”".format(quote)
img_caption = make_image.text_image(quote, padding=25)
img_author = make_image.text_image(
name, font_size=int(make_image.FONT_SIZE), padding=25
)
img_text = make_image.get_concat_vertical(
img_caption, img_author, align="right"
)
if fake_quote:
img_fake = make_image.text_image(
FAKE_MARK, font_size=int(make_image.FONT_SIZE * 0.4), padding=25
)
img_text = make_image.get_concat_vertical(img_text, img_fake, align="right")
if context is not None:
img_context = make_image.text_image(context, font_size=int(make_image.FONT_SIZE * 0.5), padding=25)
img_text = make_image.get_concat_vertical(img_text, img_context, align="left")
img_quote = make_image.get_concat_horizontal(img_text, user_pic, resize=user_pic.height < img_text.height)
return img_quote
def make_image_noprofile_quote(quote: str, name: str, context: str):
quote = '“{}”'.format(quote)
img_caption = make_image.text_image(quote, padding=25)
img_author = make_image.text_image(
name, font_size=int(make_image.FONT_SIZE * 0.5), padding=25
)
img_text = make_image.get_concat_vertical(img_caption, img_author, align="right")
if context is not None:
img_context = make_image.text_image(context, font_size=int(make_image.FONT_SIZE * 0.5), padding=25)
img_text = make_image.get_concat_vertical(img_text, img_context, align="left")
return img_text
def image_to_object_file(image: make_image.Image.Image):
file_object = BytesIO()
image.save(file_object, "JPEG")
file_object.seek(0)
return file_object
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("quote", make_quote))
dp.add_handler(CommandHandler("fake_quote", make_fake_quote))
dp.add_handler(MessageHandler(Filters.forwarded, make_quote))
# 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()