Experimental Discord bot written in Python
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

generalcog.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """
  2. Cog for handling most ungrouped commands and basic behaviors.
  3. """
  4. import re
  5. from datetime import datetime, timedelta, timezone
  6. from typing import Optional, Union
  7. from discord import Interaction, Message, User, Permissions, AppCommandType
  8. from discord.app_commands import Command, Group, command, default_permissions, guild_only, Transform, Choice, \
  9. autocomplete
  10. from discord.errors import DiscordException
  11. from discord.ext.commands import Cog
  12. from config import CONFIG
  13. from rocketbot.bot import Rocketbot
  14. from rocketbot.cogs.basecog import BaseCog, BotMessage
  15. from rocketbot.utils import describe_timedelta, TimeDeltaTransformer, dump_stacktrace, MOD_PERMISSIONS
  16. from rocketbot.storage import ConfigKey, Storage
  17. class GeneralCog(BaseCog, name='General'):
  18. """
  19. Cog for handling high-level bot functionality and commands. Should be the
  20. first cog added to the bot.
  21. """
  22. shared: Optional['GeneralCog'] = None
  23. def __init__(self, bot: Rocketbot):
  24. super().__init__(
  25. bot,
  26. config_prefix=None,
  27. short_description='',
  28. )
  29. self.is_connected = False
  30. self.is_first_connect = True
  31. self.last_disconnect_time: Optional[datetime] = None
  32. self.noteworthy_disconnect_duration = timedelta(seconds=5)
  33. GeneralCog.shared = self
  34. @Cog.listener()
  35. async def on_connect(self):
  36. """Event handler"""
  37. if self.is_first_connect:
  38. self.log(None, 'Connected')
  39. self.is_first_connect = False
  40. else:
  41. disconnect_duration = datetime.now(
  42. timezone.utc) - self.last_disconnect_time if self.last_disconnect_time else None
  43. if disconnect_duration is not None and disconnect_duration > self.noteworthy_disconnect_duration:
  44. self.log(None, f'Reconnected after {disconnect_duration.total_seconds()} seconds')
  45. self.is_connected = True
  46. @Cog.listener()
  47. async def on_disconnect(self):
  48. """Event handler"""
  49. self.last_disconnect_time = datetime.now(timezone.utc)
  50. # self.log(None, 'Disconnected')
  51. @Cog.listener()
  52. async def on_resumed(self):
  53. """Event handler"""
  54. disconnect_duration = datetime.now(timezone.utc) - self.last_disconnect_time if self.last_disconnect_time else None
  55. if disconnect_duration is not None and disconnect_duration > self.noteworthy_disconnect_duration:
  56. self.log(None, f'Session resumed after {disconnect_duration.total_seconds()} seconds')
  57. @command(
  58. description='Posts a test warning',
  59. extras={
  60. 'long_description': 'Tests whether a warning channel is configured for this ' + \
  61. 'guild by posting a test warning. If a mod mention is ' + \
  62. 'configured, that user/role will be tagged in the test warning.',
  63. },
  64. )
  65. @guild_only()
  66. @default_permissions(ban_members=True)
  67. async def test_warn(self, interaction: Interaction):
  68. """Command handler"""
  69. if Storage.get_config_value(interaction.guild, ConfigKey.WARNING_CHANNEL_ID) is None:
  70. await interaction.response.send_message(
  71. f'{CONFIG["warning_emoji"]} No warning channel set!',
  72. ephemeral=True,
  73. )
  74. else:
  75. bm = BotMessage(
  76. interaction.guild,
  77. f'Test warning message (requested by {interaction.user.name})',
  78. type=BotMessage.TYPE_MOD_WARNING)
  79. await self.post_message(bm)
  80. await interaction.response.send_message(
  81. 'Warning issued',
  82. ephemeral=True,
  83. )
  84. @command(
  85. description='Greets the user',
  86. extras={
  87. 'long_description': 'Replies to the command message. Useful to ensure the ' + \
  88. 'bot is working properly.',
  89. },
  90. )
  91. async def hello(self, interaction: Interaction):
  92. """Command handler"""
  93. await interaction.response.send_message(
  94. f'Hey, {interaction.user.name}!',
  95. ephemeral=True,
  96. )
  97. @command(
  98. description='Shuts down the bot',
  99. extras={
  100. 'long_description': 'Causes the bot script to terminate. Only usable by a ' + \
  101. 'user with server admin permissions.',
  102. },
  103. )
  104. @guild_only()
  105. @default_permissions(administrator=True)
  106. async def shutdown(self, interaction: Interaction):
  107. """Command handler"""
  108. await interaction.response.send_message('👋', ephemeral=True)
  109. await self.bot.close()
  110. @command(
  111. description='Mass deletes messages',
  112. extras={
  113. 'long_description': 'Deletes recent messages by the given user. The user ' +
  114. 'can be either an @ mention or a numeric user ID. The age is ' +
  115. 'a duration, such as "30s", "5m", "1h30m". Only the most ' +
  116. 'recent 100 messages in each channel are searched.',
  117. 'usage': '<user:id|mention> <age:timespan>',
  118. },
  119. )
  120. @guild_only()
  121. @default_permissions(manage_messages=True)
  122. async def delete_messages(self, interaction: Interaction, user: User, age: Transform[timedelta, TimeDeltaTransformer]) -> None:
  123. """Command handler"""
  124. member_id = user.id
  125. cutoff: datetime = datetime.now(timezone.utc) - age
  126. def predicate(message: Message) -> bool:
  127. return str(message.author.id) == member_id and message.created_at >= cutoff
  128. deleted_messages = []
  129. for channel in interaction.guild.text_channels:
  130. try:
  131. deleted_messages += await channel.purge(limit=100, check=predicate)
  132. except DiscordException:
  133. # XXX: Sloppily glossing over access errors instead of checking access
  134. pass
  135. await interaction.response.send_message(
  136. f'{CONFIG["success_emoji"]} Deleted {len(deleted_messages)} ' + \
  137. f'messages by {user.mention}> from the past {describe_timedelta(age)}.',
  138. ephemeral=True,
  139. )