Quellcode durchsuchen

Fixing iter issue. More linter cleanup

tags/2.0.0
Rocketsoup vor 2 Monaten
Ursprung
Commit
d32705d99d

+ 5
- 6
rocketbot/cogs/autokickcog.py Datei anzeigen

@@ -1,5 +1,4 @@
1 1
 from datetime import datetime, timedelta
2
-from typing import cast
3 2
 
4 3
 from discord import Guild, Member, Status
5 4
 from discord.ext import commands, tasks
@@ -59,7 +58,7 @@ class AutoKickCog(BaseCog, name='Auto Kick'):
59 58
 		self.add_setting(AutoKickCog.SETTING_BAN_COUNT)
60 59
 		self.add_setting(AutoKickCog.SETTING_OFFLINE_ONLY)
61 60
 		self.status_check_members = []
62
-		timer: Loop = cast(Loop, self.status_check_timer)
61
+		timer: Loop = self.status_check_timer
63 62
 		timer.start()
64 63
 
65 64
 	@commands.group(
@@ -68,13 +67,13 @@ class AutoKickCog(BaseCog, name='Auto Kick'):
68 67
 	@commands.has_permissions(ban_members=True)
69 68
 	@commands.guild_only()
70 69
 	async def autokick(self, context: commands.Context):
71
-		'Auto-kick'
70
+		"""Auto-kick"""
72 71
 		if context.invoked_subcommand is None:
73 72
 			await context.send_help()
74 73
 
75 74
 	@commands.Cog.listener()
76 75
 	async def on_member_join(self, member: Member) -> None:
77
-		'Event handler'
76
+		"""Event handler"""
78 77
 		guild: Guild = member.guild
79 78
 		if not self.get_guild_setting(guild, self.SETTING_ENABLED):
80 79
 			return
@@ -86,7 +85,7 @@ class AutoKickCog(BaseCog, name='Auto Kick'):
86 85
 
87 86
 	@tasks.loop(seconds=5.0)
88 87
 	async def status_check_timer(self):
89
-		'Checks status of new members shortly after joining to see if they go offline'
88
+		"""Checks status of new members shortly after joining to see if they go offline"""
90 89
 		contexts = self.status_check_members.copy()
91 90
 		self.status_check_members = []
92 91
 		now = datetime.now()
@@ -146,7 +145,7 @@ class AutoKickCog(BaseCog, name='Auto Kick'):
146 145
 
147 146
 	@staticmethod
148 147
 	def ordinal(val: int):
149
-		'Formats an integer with an ordinal suffix (English only)'
148
+		"""Formats an integer with an ordinal suffix (English only)"""
150 149
 		if val % 100 < 10 or val % 100 > 20:
151 150
 			if val % 10 == 1:
152 151
 				return f'{val}st'

+ 3
- 3
rocketbot/cogs/basecog.py Datei anzeigen

@@ -38,7 +38,7 @@ class BaseCog(commands.Cog):
38 38
 	def get_cog_default(cls, key: str):
39 39
 		"""
40 40
 		Convenience method for getting a cog configuration default from
41
-		`CONFIG['cogs'][<cogname>][<key>]`. These values are used for
41
+		`CONFIG['cogs'][<cog_name>][<key>]`. These values are used for
42 42
 		CogSettings when no guild-specific value is configured yet.
43 43
 		"""
44 44
 		cogs: dict = CONFIG['cog_defaults']
@@ -55,7 +55,7 @@ class BaseCog(commands.Cog):
55 55
 		commands will be created instead which set the setting to True/False.
56 56
 
57 57
 		If the cog has a command group it will be detected automatically and
58
-		the commands added to that. Otherwise the commands will be added at
58
+		the commands added to that. Otherwise, the commands will be added at
59 59
 		the top level.
60 60
 
61 61
 		Changes to settings can be detected by overriding `on_setting_updated`.
@@ -97,7 +97,7 @@ class BaseCog(commands.Cog):
97 97
 
98 98
 	@commands.Cog.listener()
99 99
 	async def on_ready(self):
100
-		'Event listener'
100
+		"""Event listener"""
101 101
 		if not self.are_settings_setup:
102 102
 			self.are_settings_setup = True
103 103
 			CogSetting.set_up_all(self, self.bot, self.settings)

+ 2
- 2
rocketbot/cogs/crosspostcog.py Datei anzeigen

@@ -233,7 +233,7 @@ class CrossPostCog(BaseCog, name='Crosspost Detection'):
233 233
 
234 234
 	@commands.Cog.listener()
235 235
 	async def on_message(self, message: Message):
236
-		'Event handler'
236
+		"""Event handler"""
237 237
 		if message.author is None or \
238 238
 				message.author.bot or \
239 239
 				message.channel is None or \
@@ -251,6 +251,6 @@ class CrossPostCog(BaseCog, name='Crosspost Detection'):
251 251
 	@commands.has_permissions(ban_members=True)
252 252
 	@commands.guild_only()
253 253
 	async def crosspost(self, context: commands.Context):
254
-		'Crosspost detection command group'
254
+		"""Crosspost detection command group"""
255 255
 		if context.invoked_subcommand is None:
256 256
 			await context.send_help()

+ 8
- 8
rocketbot/cogs/generalcog.py Datei anzeigen

@@ -28,7 +28,7 @@ class GeneralCog(BaseCog, name='General'):
28 28
 
29 29
 	@commands.Cog.listener()
30 30
 	async def on_connect(self):
31
-		'Event handler'
31
+		"""Event handler"""
32 32
 		if self.is_first_connect:
33 33
 			self.log(None, 'Connected')
34 34
 			self.is_first_connect = False
@@ -38,12 +38,12 @@ class GeneralCog(BaseCog, name='General'):
38 38
 
39 39
 	@commands.Cog.listener()
40 40
 	async def on_disconnect(self):
41
-		'Event handler'
41
+		"""Event handler"""
42 42
 		self.log(None, 'Disconnected')
43 43
 
44 44
 	@commands.Cog.listener()
45 45
 	async def on_ready(self):
46
-		'Event handler'
46
+		"""Event handler"""
47 47
 		self.log(None, 'Bot done initializing')
48 48
 		self.is_ready = True
49 49
 		if self.is_first_ready:
@@ -52,7 +52,7 @@ class GeneralCog(BaseCog, name='General'):
52 52
 
53 53
 	@commands.Cog.listener()
54 54
 	async def on_resumed(self):
55
-		'Event handler'
55
+		"""Event handler"""
56 56
 		self.log(None, 'Session resumed')
57 57
 
58 58
 	@commands.command(
@@ -64,7 +64,7 @@ class GeneralCog(BaseCog, name='General'):
64 64
 	@commands.has_permissions(ban_members=True)
65 65
 	@commands.guild_only()
66 66
 	async def testwarn(self, context):
67
-		'Command handler'
67
+		"""Command handler"""
68 68
 		if Storage.get_config_value(context.guild, ConfigKey.WARNING_CHANNEL_ID) is None:
69 69
 			await context.message.reply(
70 70
 				f'{CONFIG["warning_emoji"]} No warning channel set!',
@@ -82,7 +82,7 @@ class GeneralCog(BaseCog, name='General'):
82 82
 			'bot is working properly.',
83 83
 	)
84 84
 	async def hello(self, context):
85
-		'Command handler'
85
+		"""Command handler"""
86 86
 		await context.message.reply(
87 87
 			f'Hey, {context.author.name}!',
88 88
 		 	mention_author=False)
@@ -95,7 +95,7 @@ class GeneralCog(BaseCog, name='General'):
95 95
 	@commands.has_permissions(administrator=True)
96 96
 	@commands.guild_only()
97 97
 	async def shutdown(self, context: commands.Context):
98
-		'Command handler'
98
+		"""Command handler"""
99 99
 		await context.message.add_reaction('👋')
100 100
 		await self.bot.close()
101 101
 
@@ -110,7 +110,7 @@ class GeneralCog(BaseCog, name='General'):
110 110
 	@commands.has_permissions(manage_messages=True)
111 111
 	@commands.guild_only()
112 112
 	async def deletemessages(self, context, user: str, age: str) -> None:
113
-		'Command handler'
113
+		"""Command handler"""
114 114
 		member_id = self.__parse_member_id(user)
115 115
 		if member_id is None:
116 116
 			await context.message.reply(

+ 8
- 8
rocketbot/cogs/logcog.py Datei anzeigen

@@ -31,7 +31,7 @@ class LoggingCog(BaseCog, name='Logging'):
31 31
 	@commands.has_permissions(ban_members=True)
32 32
 	@commands.guild_only()
33 33
 	async def logging(self, context: commands.Context):
34
-		'Logging command group'
34
+		"""Logging command group"""
35 35
 		if context.invoked_subcommand is None:
36 36
 			await context.send_help()
37 37
 
@@ -125,7 +125,7 @@ class LoggingCog(BaseCog, name='Logging'):
125 125
 	@commands.Cog.listener()
126 126
 	async def on_invite_create(self, invite: Invite) -> None:
127 127
 		"""
128
-		Called when an Invite is created. You must have manage_channels to receive this.
128
+		Called when an `Invite` is created. You must have manage_channels to receive this.
129 129
 
130 130
 		https://discordpy.readthedocs.io/en/stable/api.html#discord.on_invite_create
131 131
 		"""
@@ -143,7 +143,7 @@ class LoggingCog(BaseCog, name='Logging'):
143 143
 	@commands.Cog.listener()
144 144
 	async def on_invite_delete(self, invite: Invite) -> None:
145 145
 		"""
146
-		Called when an Invite is deleted. You must have manage_channels to receive this.
146
+		Called when an `Invite` is deleted. You must have manage_channels to receive this.
147 147
 
148 148
 		https://discordpy.readthedocs.io/en/stable/api.html#discord.on_invite_delete
149 149
 		"""
@@ -305,8 +305,8 @@ class LoggingCog(BaseCog, name='Logging'):
305 305
 			changes.append(f'Guild avatar: <{before_guild_avatar}> -> <{after_guild_avatar}>')
306 306
 		if after.flags != before.flags:
307 307
 			flag_changes = []
308
-			for (name, after_value) in after.iter():
309
-				before_value = getattr(before, name)
308
+			for (name, after_value) in iter(after.flags):
309
+				before_value = getattr(before.flags, name)
310 310
 				if after_value != before_value:
311 311
 					flag_changes.append(f'`{name}` = `{before_value}` -> `{after_value}`')
312 312
 			if len(flag_changes) > 0:
@@ -315,7 +315,7 @@ class LoggingCog(BaseCog, name='Logging'):
315 315
 		if len(changes) == 0:
316 316
 			return
317 317
 		text = f'Details for member {self.__describe_user(before)} changed:\n'
318
-		text += '* ' + '\n* '.join(changes)
318
+		text += '* ' + ('\n* '.join(changes))
319 319
 		bot_message = BotMessage(guild, text, BotMessage.TYPE_LOG)
320 320
 		await bot_message.update()
321 321
 
@@ -713,7 +713,7 @@ class LoggingCog(BaseCog, name='Logging'):
713 713
 
714 714
 	def __describe_user(self, user: Union[User, Member]) -> str:
715 715
 		"""
716
-		Standardized markdown describing a user or member.
716
+		Standardized Markdown describing a user or member.
717 717
 		"""
718 718
 		return f'**{user.name}** ({user.display_name} {user.id})'
719 719
 
@@ -779,4 +779,4 @@ class LoggingCog(BaseCog, name='Logging'):
779 779
 		markdown_a = re.sub(r'[\ue000-\uefff]', unsub_token, markdown_a)
780 780
 		markdown_b = re.sub(r'[\ue000-\uefff]', unsub_token, markdown_b)
781 781
 
782
-		return (markdown_a, markdown_b)
782
+		return markdown_a, markdown_b

+ 7
- 7
rocketbot/cogs/patterncog.py Datei anzeigen

@@ -30,7 +30,7 @@ class PatternContext:
30 30
 class PatternCog(BaseCog, name='Pattern Matching'):
31 31
 	"""
32 32
 	Highly flexible cog for performing various actions on messages that match
33
-	various critera. Patterns can be defined by mods for each guild.
33
+	various criteria. Patterns can be defined by mods for each guild.
34 34
 	"""
35 35
 
36 36
 	SETTING_PATTERNS = CogSetting('patterns', None)
@@ -82,7 +82,7 @@ class PatternCog(BaseCog, name='Pattern Matching'):
82 82
 
83 83
 	@commands.Cog.listener()
84 84
 	async def on_message(self, message: Message) -> None:
85
-		'Event listener'
85
+		"""Event listener"""
86 86
 		if message.author is None or \
87 87
 				message.author.bot or \
88 88
 				message.channel is None or \
@@ -195,7 +195,7 @@ class PatternCog(BaseCog, name='Pattern Matching'):
195 195
 	@commands.has_permissions(ban_members=True)
196 196
 	@commands.guild_only()
197 197
 	async def pattern(self, context: commands.Context):
198
-		'Message pattern matching command group'
198
+		"""Message pattern matching command group"""
199 199
 		if context.invoked_subcommand is None:
200 200
 			await context.send_help()
201 201
 
@@ -209,7 +209,7 @@ class PatternCog(BaseCog, name='Pattern Matching'):
209 209
 		ignore_extra=True
210 210
 	)
211 211
 	async def add(self, context: commands.Context, name: str):
212
-		'Command handler'
212
+		"""Command handler"""
213 213
 		pattern_str = PatternCompiler.expression_str_from_context(context, name)
214 214
 		try:
215 215
 			statement = PatternCompiler.parse_statement(name, pattern_str)
@@ -230,7 +230,7 @@ class PatternCog(BaseCog, name='Pattern Matching'):
230 230
 		usage='<pattern_name>'
231 231
 	)
232 232
 	async def remove(self, context: commands.Context, name: str):
233
-		'Command handler'
233
+		"""Command handler"""
234 234
 		patterns = self.__get_patterns(context.guild)
235 235
 		if patterns.get(name) is not None:
236 236
 			del patterns[name]
@@ -247,7 +247,7 @@ class PatternCog(BaseCog, name='Pattern Matching'):
247 247
 		brief='Lists all patterns'
248 248
 	)
249 249
 	async def list(self, context: commands.Context) -> None:
250
-		'Command handler'
250
+		"""Command handler"""
251 251
 		patterns = self.__get_patterns(context.guild)
252 252
 		if len(patterns) == 0:
253 253
 			await context.message.reply('No patterns defined.', mention_author=False)
@@ -265,7 +265,7 @@ class PatternCog(BaseCog, name='Pattern Matching'):
265 265
 			'priority is 100.',
266 266
 	)
267 267
 	async def setpriority(self, context: commands.Context, name: str, priority: int) -> None:
268
-		'Command handler'
268
+		"""Command handler"""
269 269
 		patterns = self.__get_patterns(context.guild)
270 270
 		statement = patterns.get(name)
271 271
 		if statement is None:

+ 9
- 9
rocketbot/cogs/urlspamcog.py Datei anzeigen

@@ -64,13 +64,13 @@ class URLSpamCog(BaseCog, name='URL Spam'):
64 64
 	@commands.has_permissions(ban_members=True)
65 65
 	@commands.guild_only()
66 66
 	async def urlspam(self, context: commands.Context):
67
-		'URL spam command group'
67
+		"""URL spam command group"""
68 68
 		if context.invoked_subcommand is None:
69 69
 			await context.send_help()
70 70
 
71 71
 	@commands.Cog.listener()
72 72
 	async def on_message(self, message: Message):
73
-		'Event listener'
73
+		"""Event listener"""
74 74
 		if message.author is None or \
75 75
 				message.author.bot or \
76 76
 				message.guild is None or \
@@ -83,7 +83,7 @@ class URLSpamCog(BaseCog, name='URL Spam'):
83 83
 		await self.check_deceptive_links(message)
84 84
 
85 85
 	async def check_message_recency(self, message: Message):
86
-		'Checks if the message was sent too recently by a new user'
86
+		"""Checks if the message was sent too recently by a new user"""
87 87
 		action = self.get_guild_setting(message.guild, self.SETTING_ACTION)
88 88
 		join_seconds = self.get_guild_setting(message.guild, self.SETTING_JOIN_AGE)
89 89
 		min_join_age = timedelta(seconds=join_seconds)
@@ -143,11 +143,11 @@ class URLSpamCog(BaseCog, name='URL Spam'):
143 143
 
144 144
 	async def check_deceptive_links(self, message: Message):
145 145
 		"""
146
-		Checks if the message contains deceptive URL markdown, e.g.
146
+		Checks if the message contains deceptive URL Markdown, e.g.
147 147
 		`[nicewebsite.com](https://evilwebsite.com)'`
148 148
 		"""
149 149
 		action = self.get_guild_setting(message.guild, self.SETTING_DECEPTIVE_ACTION)
150
-		if action == None or action == 'nothing':
150
+		if action is None or action == 'nothing':
151 151
 			return
152 152
 
153 153
 		if not self.contains_deceptive_links(message.content):
@@ -194,7 +194,7 @@ class URLSpamCog(BaseCog, name='URL Spam'):
194 194
 				delete_message_days=1)
195 195
 
196 196
 	def contains_deceptive_links(self, content: str) -> bool:
197
-		# Strip markdown that can safely contain URL sequences
197
+		# Strip Markdown that can safely contain URL sequences
198 198
 		content = re.sub(r'`[^`]+`', '', content)  # `inline code`
199 199
 		content = re.sub(r'```.+?```', '', content, re.DOTALL)  # ``` code block ```
200 200
 		matches = re.findall(r'\[([^]]+)]\(([^)]+)\)', content)
@@ -227,7 +227,7 @@ class URLSpamCog(BaseCog, name='URL Spam'):
227 227
 		return False
228 228
 
229 229
 	def is_url(self, s: str):
230
-		'Tests if a string is strictly a URL'
230
+		"""Tests if a string is strictly a URL"""
231 231
 		ipv6_host_pattern = r'\[[0-9a-fA-F:]+\]'
232 232
 		ipv4_host_pattern = r'[0-9\.]+'
233 233
 		hostname_pattern = r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+'
@@ -235,10 +235,10 @@ class URLSpamCog(BaseCog, name='URL Spam'):
235 235
 		port_pattern = '(?::[0-9]+)?'
236 236
 		path_pattern = r'(?:/[^ \]\)]*)?'
237 237
 		pattern = r'^http[s]?://' + host_pattern + port_pattern + path_pattern + '$'
238
-		return re.match(pattern, s, re.IGNORECASE) != None
238
+		return re.match(pattern, s, re.IGNORECASE) is not None
239 239
 
240 240
 	def is_casual_url(self, s: str):
241
-		'Tests if a string is a "casual URL" with no scheme included'
241
+		"""Tests if a string is a "casual URL" with no scheme included"""
242 242
 		ipv6_host_pattern = r'\[[0-9a-fA-F:]+\]'
243 243
 		ipv4_host_pattern = r'[0-9\.]+'
244 244
 		hostname_pattern = r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+'

+ 6
- 6
rocketbot/cogs/usernamecog.py Datei anzeigen

@@ -79,7 +79,7 @@ class UsernamePatternCog(BaseCog, name='Username Pattern'):
79 79
 	@commands.has_permissions(ban_members=True)
80 80
 	@commands.guild_only()
81 81
 	async def username(self, context: commands.Context):
82
-		'Username pattern command group'
82
+		"""Username pattern command group"""
83 83
 		if context.invoked_subcommand is None:
84 84
 			await context.send_help()
85 85
 
@@ -89,7 +89,7 @@ class UsernamePatternCog(BaseCog, name='Username Pattern'):
89 89
 		usage='<pattern>'
90 90
 	)
91 91
 	async def add(self, context: commands.Context, pattern: str) -> None:
92
-		'Command handler'
92
+		"""Command handler"""
93 93
 		norm_pattern = pattern.lower()
94 94
 		patterns: list[str] = self.__get_patterns(context.guild)
95 95
 		if norm_pattern in patterns:
@@ -105,7 +105,7 @@ class UsernamePatternCog(BaseCog, name='Username Pattern'):
105 105
 		usage='<pattern>'
106 106
 	)
107 107
 	async def remove(self, context: commands.Context, pattern: str) -> None:
108
-		'Command handler'
108
+		"""Command handler"""
109 109
 		norm_pattern = pattern.lower()
110 110
 		guild: Guild = context.guild
111 111
 		patterns: list[str] = self.__get_patterns(guild)
@@ -121,7 +121,7 @@ class UsernamePatternCog(BaseCog, name='Username Pattern'):
121 121
 		brief='Lists username patterns'
122 122
 	)
123 123
 	async def list(self, context: commands.Context) -> None:
124
-		'Command handler'
124
+		"""Command handler"""
125 125
 		guild: Guild = context.guild
126 126
 		patterns: list[str] = self.__get_patterns(guild)
127 127
 		if len(patterns) == 0:
@@ -132,7 +132,7 @@ class UsernamePatternCog(BaseCog, name='Username Pattern'):
132 132
 
133 133
 	@commands.Cog.listener()
134 134
 	async def on_member_join(self, member: Member) -> None:
135
-		'Event handler'
135
+		"""Event handler"""
136 136
 		for pattern in self.__get_patterns(member.guild):
137 137
 			if self.matches(pattern, member.name):
138 138
 				await self.handle_match(member, pattern)
@@ -140,7 +140,7 @@ class UsernamePatternCog(BaseCog, name='Username Pattern'):
140 140
 				await self.handle_match(member, pattern)
141 141
 
142 142
 	def matches(self, pattern: str, subject: str) -> bool:
143
-		'Checks if a username matches a given pattern'
143
+		"""Checks if a username matches a given pattern"""
144 144
 		if pattern is None:
145 145
 			return False
146 146
 		if subject is None:

+ 7
- 9
rocketbot/pattern.py Datei anzeigen

@@ -326,7 +326,6 @@ class PatternCompiler:
326 326
 				if ch in cls.STRING_QUOTE_CHARS:
327 327
 					if len(current_token) > 0:
328 328
 						tokens.append(current_token)
329
-						current_token = ''
330 329
 						possible_token_types |= all_token_types
331 330
 					in_quote = ch
332 331
 					current_token = ch
@@ -403,7 +402,7 @@ class PatternCompiler:
403 402
 					cls.__validate_action(a)
404 403
 					actions.append(a)
405 404
 				token_index += 1
406
-				return (actions, token_index)
405
+				return actions, token_index
407 406
 			elif token == ',':
408 407
 				if len(current_action_tokens) < 1:
409 408
 					raise PatternError('Unexpected ,')
@@ -449,15 +448,14 @@ class PatternCompiler:
449 448
 		while token_index < len(tokens):
450 449
 			if one_subexpression:
451 450
 				if len(subexpressions) == 1:
452
-					return (subexpressions[0], token_index)
451
+					return subexpressions[0], token_index
453 452
 				if len(subexpressions) > 1:
454 453
 					raise PatternError('Too many subexpressions')
455
-			compound_operator = None
456 454
 			if tokens[token_index] == ')':
457 455
 				if len(subexpressions) == 0:
458 456
 					raise PatternError('No subexpressions')
459 457
 				if len(subexpressions) == 1:
460
-					return (subexpressions[0], token_index)
458
+					return subexpressions[0], token_index
461 459
 				return (PatternCompoundExpression(last_compound_operator,
462 460
 					subexpressions), token_index)
463 461
 			if tokens[token_index] in { "and", "or" }:
@@ -490,10 +488,10 @@ class PatternCompiler:
490 488
 		if len(subexpressions) == 0:
491 489
 			raise PatternError('No subexpressions')
492 490
 		elif len(subexpressions) == 1:
493
-			return (subexpressions[0], token_index)
491
+			return subexpressions[0], token_index
494 492
 		else:
495
-			return (PatternCompoundExpression(last_compound_operator,
496
-				subexpressions), token_index)
493
+			return PatternCompoundExpression(last_compound_operator,
494
+				subexpressions), token_index
497 495
 
498 496
 	@classmethod
499 497
 	def __read_simple_expression(cls,
@@ -546,7 +544,7 @@ class PatternCompiler:
546 544
 
547 545
 		token_index += 1
548 546
 		exp = PatternSimpleExpression(field, op, value)
549
-		return (exp, token_index)
547
+		return exp, token_index
550 548
 
551 549
 	@classmethod
552 550
 	def __parse_value(cls, value: str, datatype: str, op: str = None) -> Any:

Laden…
Abbrechen
Speichern