Conditions | 3 |
Total Lines | 68 |
Code Lines | 42 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | import re |
||
27 | @command(description="to create fake tweets") |
||
28 | async def twitter( |
||
29 | self, |
||
30 | ctx: MessageContext, |
||
31 | content: CommandArg[str, Description["The content of the message"]] |
||
32 | ): |
||
33 | await ctx.interaction.ack() |
||
34 | |||
35 | for text_match, user_id in re.findall( |
||
36 | re.compile(r"(<@!(\d+)>)"), content |
||
37 | ): |
||
38 | content = content.replace( |
||
39 | text_match, f"@{await self.get_user(user_id)}" |
||
40 | ) |
||
41 | |||
42 | if len(content) > 280: |
||
43 | return "A tweet can be at maximum 280 characters long" |
||
44 | |||
45 | # download the profile picture and convert it into Image object |
||
46 | avatar = (await ctx.author.user.get_avatar()).resize((128, 128)) |
||
47 | avatar = circular_avatar(avatar) |
||
48 | |||
49 | # create the tweet by pasting the profile picture into a white image |
||
50 | tweet = trans_paste( |
||
51 | avatar, |
||
52 | Image.new("RGBA", (800, 250 + 50 * len(textwrap.wrap(content, 38))), (255, 255, 255)), |
||
53 | box=(15, 15), |
||
54 | ) |
||
55 | |||
56 | # add the fonts |
||
57 | font_normal = ImageFont.truetype("NotoSans-Regular.ttf", 40) |
||
58 | font_small = ImageFont.truetype("NotoSans-Regular.ttf", 30) |
||
59 | font_bold = ImageFont.truetype("NotoSans-Bold.ttf", 40) |
||
60 | |||
61 | # write the name and username on the Image |
||
62 | draw = ImageDraw.Draw(tweet) |
||
63 | draw.text( |
||
64 | (180, 20), str(ctx.author.user), |
||
65 | fill=(0, 0, 0), font=font_bold |
||
66 | ) |
||
67 | draw.text( |
||
68 | (180, 70), |
||
69 | f"@{ctx.author.user.username}", |
||
70 | fill=(120, 120, 120), font=font_normal, |
||
71 | ) |
||
72 | |||
73 | content = add_color_to_mentions(content) |
||
74 | |||
75 | # write the text |
||
76 | tweet = draw_multicolored_text(tweet, content, font_normal) |
||
77 | |||
78 | # write the footer |
||
79 | draw.text( |
||
80 | (30, tweet.size[1] - 60), |
||
81 | datetime.now().strftime( |
||
82 | "%I:%M %p · %d %b. %Y · Twitter for Discord" |
||
83 | ), |
||
84 | fill=(120, 120, 120), |
||
85 | font=font_small, |
||
86 | ) |
||
87 | |||
88 | return Message( |
||
89 | embeds=[ |
||
90 | Embed(title="Twitter for Discord").set_image( |
||
91 | url="attachment://image0.png" |
||
92 | ) |
||
93 | ], |
||
94 | attachments=[tweet], |
||
95 | ) |
||
183 |