Просмотр исходного кода

Prettier startup logs. Removing command prefix references.

pull/13/head
Rocketsoup 2 месяцев назад
Родитель
Сommit
2c7e8115c8
5 измененных файлов: 47 добавлений и 27 удалений
  1. 0
    2
      config.sample.py
  2. 19
    11
      rocketbot/bot.py
  3. 2
    3
      rocketbot/cogs/autokickcog.py
  4. 4
    4
      rocketbot/cogs/helpcog.py
  5. 22
    7
      rocketbot/cogsetting.py

+ 0
- 2
config.sample.py Просмотреть файл

7
 
7
 
8
 	# Client token obtained from the Discord application dashboard. See setup documentation.
8
 	# Client token obtained from the Discord application dashboard. See setup documentation.
9
 	'client_token': '<REQUIRED>',
9
 	'client_token': '<REQUIRED>',
10
-    # Bot commands will be invoked by posting a message with this prefix.
11
-	'command_prefix': '$rb_',
12
     # Path to a directory where guild-specific preferences will be stored.
10
     # Path to a directory where guild-specific preferences will be stored.
13
     # Each guild's settings will be saved as a JSON file. Path should end with a slash.
11
     # Each guild's settings will be saved as a JSON file. Path should end with a slash.
14
 	'config_path': 'config/',
12
 	'config_path': 'config/',

+ 19
- 11
rocketbot/bot.py Просмотреть файл

13
 	"""
13
 	"""
14
 	Bot subclass
14
 	Bot subclass
15
 	"""
15
 	"""
16
-	def __init__(self, command_prefix, **kwargs):
17
-		super().__init__(command_prefix, **kwargs)
16
+	def __init__(self, **kwargs):
17
+		# Bot requires command_prefix, even though we're only using slash commands,
18
+		# not commands in message content. Giving an unlikely prefix of private-use
19
+		# Unicode characters. This isn't a security thing, just avoiding showing a
20
+		# "command not found" error if someone happens to start a message with
21
+		# something more common.
22
+		super().__init__(command_prefix='\uED1E\uEA75\uF00D', **kwargs)
18
 		self.__commands_set_up = False
23
 		self.__commands_set_up = False
24
+		self.__first_ready = True
19
 
25
 
20
 	async def on_command_error(self, context: commands.Context, exception: BaseException) -> None:
26
 	async def on_command_error(self, context: commands.Context, exception: BaseException) -> None:
21
 		bot_log(None, None, f'Command error')
27
 		bot_log(None, None, f'Command error')
43
 			traceback.format_exc())
49
 			traceback.format_exc())
44
 
50
 
45
 	async def on_ready(self):
51
 	async def on_ready(self):
46
-		if not self.__commands_set_up:
47
-			await self.__set_up_commands()
48
-		bot_log(None, None, 'Bot done initializing')
49
-		print('----------------------------------------------------------')
52
+		if self.__first_ready:
53
+			self.__first_ready = False
54
+			if not self.__commands_set_up:
55
+				await self.__set_up_commands()
56
+			bot_log(None, None, 'Bot done initializing')
57
+			bot_log(None, None, f"Type /help in Discord for available commands.")
58
+			print('----------------------------------------------------------')
50
 
59
 
51
 	async def __set_up_commands(self):
60
 	async def __set_up_commands(self):
52
 		if self.__commands_set_up:
61
 		if self.__commands_set_up:
74
 		return
83
 		return
75
 	bot_log(None, None, 'Creating bot...')
84
 	bot_log(None, None, 'Creating bot...')
76
 	intents = Intents.default()
85
 	intents = Intents.default()
77
-	intents.messages = True  # pylint: disable=assigning-non-slot
78
-	intents.message_content = True  # pylint: disable=assigning-non-slot
79
-	intents.members = True  # pylint: disable=assigning-non-slot
86
+	intents.messages = True
87
+	intents.message_content = True
88
+	intents.members = True
80
 	intents.presences = True
89
 	intents.presences = True
81
-	rocketbot = Rocketbot(command_prefix=CONFIG['command_prefix'], intents=intents)
90
+	rocketbot = Rocketbot(intents=intents)
82
 __create_bot()
91
 __create_bot()
83
 
92
 
84
 from rocketbot.cogs.autokickcog import AutoKickCog
93
 from rocketbot.cogs.autokickcog import AutoKickCog
94
 
103
 
95
 async def start_bot():
104
 async def start_bot():
96
 	bot_log(None, None, 'Bot initializing...')
105
 	bot_log(None, None, 'Bot initializing...')
97
-	bot_log(None, None, f"Type {CONFIG['command_prefix']}help in Discord for available commands.")
98
 
106
 
99
 	# Core
107
 	# Core
100
 	await rocketbot.add_cog(GeneralCog(rocketbot))
108
 	await rocketbot.add_cog(GeneralCog(rocketbot))

+ 2
- 3
rocketbot/cogs/autokickcog.py Просмотреть файл

123
 		else:
123
 		else:
124
 			context.record_kick(datetime.now())
124
 			context.record_kick(datetime.now())
125
 		max_kick_count: int = self.get_guild_setting(guild, self.SETTING_BAN_COUNT)
125
 		max_kick_count: int = self.get_guild_setting(guild, self.SETTING_BAN_COUNT)
126
-		disable_help = f'To disable this feature: `{CONFIG["command_prefix"]}autokick disable`.'
127
-		ban_help = f'To configure ban threshold: `{CONFIG["command_prefix"]}autokick ' + \
128
-			'setbancount #` (0 to disable).'
126
+		disable_help = f'To disable this feature: `/disable autokick`.'
127
+		ban_help = f'To configure ban threshold: `/set autokick_bancount #` (0 to disable)'
129
 		if max_kick_count > 0 and context.kick_count > max_kick_count:
128
 		if max_kick_count > 0 and context.kick_count > max_kick_count:
130
 			await member.ban(reason=f'Rocketbot: Ban after {context.kick_count} joins',
129
 			await member.ban(reason=f'Rocketbot: Ban after {context.kick_count} joins',
131
 				delete_message_days=0)
130
 				delete_message_days=0)

+ 4
- 4
rocketbot/cogs/helpcog.py Просмотреть файл

146
 
146
 
147
 		cmds = self.all_commands()
147
 		cmds = self.all_commands()
148
 		for cmd in cmds:
148
 		for cmd in cmds:
149
-			key = f'cmd:{cmd.name}'
150
-			self.obj_index[key] = cmd
149
+			self.obj_index[f'cmd:{cmd.name}'] = cmd
150
+			self.obj_index[f'/{cmd.name}'] = cmd
151
 			add_text_to_index(cmd, cmd.name)
151
 			add_text_to_index(cmd, cmd.name)
152
 			if cmd.description:
152
 			if cmd.description:
153
 				add_text_to_index(cmd, cmd.description)
153
 				add_text_to_index(cmd, cmd.description)
154
 			if isinstance(cmd, Group):
154
 			if isinstance(cmd, Group):
155
 				for subcmd in cmd.commands:
155
 				for subcmd in cmd.commands:
156
-					key = f'subcmd:{cmd.name}.{subcmd.name}'
157
-					self.obj_index[key] = subcmd
156
+					self.obj_index[f'subcmd:{cmd.name}.{subcmd.name}'] = subcmd
157
+					self.obj_index[f'/{cmd.name} {subcmd.name}'] = subcmd
158
 					add_text_to_index(subcmd, cmd.name)
158
 					add_text_to_index(subcmd, cmd.name)
159
 					add_text_to_index(subcmd, subcmd.name)
159
 					add_text_to_index(subcmd, subcmd.name)
160
 					if subcmd.description:
160
 					if subcmd.description:

+ 22
- 7
rocketbot/cogsetting.py Просмотреть файл

2
 A guild configuration setting available for editing via bot commands.
2
 A guild configuration setting available for editing via bot commands.
3
 """
3
 """
4
 from datetime import timedelta
4
 from datetime import timedelta
5
-from typing import Any, Optional, Type, Literal
5
+from typing import Any, Optional, Type, Literal, Union
6
 
6
 
7
 from discord import Interaction, Permissions
7
 from discord import Interaction, Permissions
8
 from discord.app_commands import Range, Transform, describe
8
 from discord.app_commands import Range, Transform, describe
14
 from rocketbot.utils import bot_log, TimeDeltaTransformer, MOD_PERMISSIONS, dump_stacktrace, str_from_timedelta
14
 from rocketbot.utils import bot_log, TimeDeltaTransformer, MOD_PERMISSIONS, dump_stacktrace, str_from_timedelta
15
 
15
 
16
 
16
 
17
+def describe_type(datatype: Type) -> str:
18
+	if datatype is int:
19
+		return 'integer'
20
+	if datatype is float:
21
+		return 'float'
22
+	if datatype is str:
23
+		return 'string'
24
+	if datatype is bool:
25
+		return 'boolean'
26
+	if datatype is timedelta:
27
+		return 'timespan'
28
+	if getattr(datatype, '__origin__', None) is Union:
29
+		return '|'.join([ describe_type(a) for a in datatype.__args__ ])
30
+	if getattr(datatype, '__origin__', None) is Literal:
31
+		return '"' + ('"|"'.join(datatype.__args__)) + '"'
32
+	return datatype.__class__.__name__
33
+
17
 class CogSetting:
34
 class CogSetting:
18
 	"""
35
 	"""
19
 	Describes a configuration setting for a guild that can be edited by the
36
 	Describes a configuration setting for a guild that can be edited by the
142
 					ephemeral=True
159
 					ephemeral=True
143
 				)
160
 				)
144
 
161
 
145
-		bot_log(None, cog.__class__, f"Creating /get {setting_name}")
162
+		bot_log(None, cog.__class__, f"Creating command: /get {setting_name}")
146
 		command = Command(
163
 		command = Command(
147
 			name=setting_name,
164
 			name=setting_name,
148
 			description=f'Shows {self.brief}.',
165
 			description=f'Shows {self.brief}.',
232
 		elif self.datatype is not None:
249
 		elif self.datatype is not None:
233
 			raise ValueError(f'Invalid type {self.datatype}')
250
 			raise ValueError(f'Invalid type {self.datatype}')
234
 
251
 
235
-		bot_log(None, cog.__class__, f"Creating /set {setting_name} {self.datatype}")
252
+		bot_log(None, cog.__class__, f"Creating command: /set {setting_name} <{describe_type(self.datatype)}>")
236
 		command = Command(
253
 		command = Command(
237
 			name=setting_name,
254
 			name=setting_name,
238
 			description=f'Sets {self.brief}.',
255
 			description=f'Sets {self.brief}.',
258
 			await cog.on_setting_updated(interaction.guild, setting)
275
 			await cog.on_setting_updated(interaction.guild, setting)
259
 			cog.log(interaction.guild, f'{interaction.user.name} enabled {cog.__class__.__name__}')
276
 			cog.log(interaction.guild, f'{interaction.user.name} enabled {cog.__class__.__name__}')
260
 
277
 
261
-		bot_log(None, cog.__class__, f"Creating /enable {cog.config_prefix}")
278
+		bot_log(None, cog.__class__, f"Creating command: /enable {cog.config_prefix}")
262
 		command = Command(
279
 		command = Command(
263
 			name=cog.config_prefix,
280
 			name=cog.config_prefix,
264
 			description=f'Enables {cog.qualified_name} functionality.',
281
 			description=f'Enables {cog.qualified_name} functionality.',
284
 			await cog.on_setting_updated(interaction.guild, setting)
301
 			await cog.on_setting_updated(interaction.guild, setting)
285
 			cog.log(interaction.guild, f'{interaction.user.name} disabled {cog.__class__.__name__}')
302
 			cog.log(interaction.guild, f'{interaction.user.name} disabled {cog.__class__.__name__}')
286
 
303
 
287
-		bot_log(None, cog.__class__, f"Creating /disable {cog.config_prefix}")
304
+		bot_log(None, cog.__class__, f"Creating command: /disable {cog.config_prefix}")
288
 		command = Command(
305
 		command = Command(
289
 			name=cog.config_prefix,
306
 			name=cog.config_prefix,
290
 			description=f'Disables {cog.config_prefix} functionality',
307
 			description=f'Disables {cog.config_prefix} functionality',
313
 		cls.__set_up_base_commands(bot)
330
 		cls.__set_up_base_commands(bot)
314
 		if len(settings) == 0:
331
 		if len(settings) == 0:
315
 			return
332
 			return
316
-		bot_log(None, cog.__class__, f"Setting up slash commands for {cog.__class__.__name__}")
317
 		for setting in settings:
333
 		for setting in settings:
318
 			setting.set_up(cog)
334
 			setting.set_up(cog)
319
-		bot_log(None, cog.__class__, f"Done setting up slash commands for {cog.__class__.__name__}")
320
 
335
 
321
 	@classmethod
336
 	@classmethod
322
 	def __set_up_base_commands(cls, bot: Bot) -> None:
337
 	def __set_up_base_commands(cls, bot: Bot) -> None:

Загрузка…
Отмена
Сохранить