Passed
Pull Request — main (#241)
by Yohann
01:44
created

tweet_generator.circular_avatar()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
import re
2
import textwrap
3
import os
4
import sys
5
from datetime import datetime
6
from PIL import Image, ImageFont, ImageDraw, ImageOps
7
from pincer import command, Client
8
from pincer.commands import CommandArg, Description
9
from pincer.objects import Message, Embed, MessageContext
10
11
12
# you need to manually download the font files and put them into the folder
13
# ./examples/tweet_generator/ to make the script works using this link:
14
# https://fonts.google.com/share?selection.family=Noto%20Sans:wght@400;700
15
if not all(
16
        font in os.listdir()
17
        for font in [
18
            "NotoSans-Regular.ttf",
19
            "NotoSans-Bold.ttf"
20
        ]
21
):
22
    sys.exit()
23
24
25
class Bot(Client):
26
    @Client.event
27
    async def on_ready(self):
28
        print(
29
            f"Started client on {self.bot}\n"
30
            f"Registered commands: {', '.join(self.chat_commands)}"
31
        )
32
33
    @command(description="to create fake tweets")
34
    async def twitter(
35
        self,
36
        ctx: MessageContext,
37
        content: CommandArg[str, Description["The content of the message"]]
38
    ):
39
        await ctx.interaction.ack()
40
41
        for text_match, user_id in re.findall(
42
            re.compile(r"(<@!(\d+)>)"), content
43
        ):
44
            content = content.replace(
45
                text_match, f"@{await self.get_user(user_id)}"
46
            )
47
48
        if len(content) > 280:
49
            return "A tweet can be at maximum 280 characters long"
50
51
        # download the profile picture and convert it into Image object
52
        avatar = (await ctx.author.user.get_avatar()).resize((128, 128))
53
        avatar = circular_avatar(avatar)
54
55
        # create the tweet by pasting the profile picture into a white image
56
        tweet = trans_paste(
57
            avatar,
58
            Image.new(
59
                "RGBA",
60
                (800, 250 + 50 * len(textwrap.wrap(content, 38))),
61
                (255, 255, 255)
62
            ),
63
            box=(15, 15),
64
        )
65
66
        # add the fonts
67
        font_normal = ImageFont.truetype("NotoSans-Regular.ttf", 40)
68
        font_small = ImageFont.truetype("NotoSans-Regular.ttf", 30)
69
        font_bold = ImageFont.truetype("NotoSans-Bold.ttf", 40)
70
71
        # write the name and username on the Image
72
        draw = ImageDraw.Draw(tweet)
73
        draw.text(
74
            (180, 20),
75
            str(ctx.author.user),
76
            fill=(0, 0, 0),
77
            font=font_bold
78
        )
79
        draw.text(
80
            (180, 70),
81
            f"@{ctx.author.user.username}",
82
            fill=(120, 120, 120),
83
            font=font_normal
84
        )
85
86
        content = add_color_to_mentions(content)
87
88
        # write the text
89
        tweet = draw_multicolored_text(tweet, content, font_normal)
90
91
        # write the footer
92
        draw.text(
93
            (30, tweet.size[1] - 60),
94
            datetime.now().strftime(
95
                "%I:%M %p · %d %b. %Y · Twitter for Discord"
96
            ),
97
            fill=(120, 120, 120),
98
            font=font_small,
99
        )
100
101
        return Message(
102
            embeds=[
103
                Embed(title="Twitter for Discord").set_image(
104
                    url="attachment://image0.png"
105
                )
106
            ],
107
            attachments=[tweet],
108
        )
109
110
111
def trans_paste(fg_img, bg_img, box=(0, 0)):
112
    """
113
    https://stackoverflow.com/a/53663233/15485584
114
    paste an image into one another
115
    """
116
    fg_img_trans = Image.new("RGBA", fg_img.size)
117
    fg_img_trans = Image.blend(fg_img_trans, fg_img, 1.0)
118
    bg_img.paste(fg_img_trans, box, fg_img_trans)
119
    return bg_img
120
121
122
def circular_avatar(avatar):
123
    mask = Image.new("L", (128, 128), 0)
124
    draw = ImageDraw.Draw(mask)
125
    draw.ellipse((0, 0, 128, 128), fill=255)
126
    avatar = ImageOps.fit(avatar, mask.size, centering=(0.5, 0.5))
127
    avatar.putalpha(mask)
128
    return avatar
129
130
131
def add_color_to_mentions(message):
132
    """
133
    generate a dict to set were the text need to be in different colors.
134
    if a word starts with '@' it will be write in blue.
135
136
    Parameters
137
    ----------
138
    message: the text
139
140
    Returns
141
    -------
142
    a list with all colors selected
143
    example:
144
        [
145
            {'color': (0, 0, 0), 'text': 'hello world '},
146
            {'color': (0, 154, 234), 'text': '@drawbu'}
147
        ]
148
149
    """
150
    message = textwrap.wrap(message, 38)
151
    message = "\n".join(message).split(" ")
152
    result = []
153
    for word in message:
154
        wordlines = word.splitlines()
155
        for index, text in enumerate(wordlines):
156
157
            text += "\n" if index != len(wordlines) - 1 else " "
158
159
            if not result:
160
                result.append({"color": (0, 0, 0), "text": text})
161
                continue
162
163
            if not text.startswith("@"):
164
                if result[-1]["color"] == (0, 0, 0):
165
                    result[-1]["text"] += text
166
                    continue
167
168
                result.append({"color": (0, 0, 0), "text": text})
169
                continue
170
171
            result.append({"color": (0, 154, 234), "text": text})
172
    return result
173
174
175
def draw_multicolored_text(image, message, font):
176
    draw = ImageDraw.Draw(image)
177
    x = 30
178
    y = 170
179
    y_fontsize = font.getsize(" ")[1]
180
    for text in message:
181
        y -= y_fontsize
182
        for l_index, line in enumerate(text["text"].splitlines()):
183
            if l_index:
184
                x = 30
185
            y += y_fontsize
186
            draw.text((x, y), line, fill=text["color"], font=font)
187
            x += font.getsize(line)[0]
188
    return image
189
190
191
if __name__ == "__main__":
192
    # Of course we have to run our client, you can replace the
193
    # XXXYOURBOTTOKENHEREXXX with your token, or dynamically get it
194
    # through a dotenv/env.
195
    Bot("XXXYOURBOTTOKENHEREXXX").run()
196