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.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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
  7. from discord import Message
  8. from discord.errors import DiscordException
  9. from discord.ext import commands
  10. from config import CONFIG
  11. from rocketbot.cogs.basecog import BaseCog, BotMessage
  12. from rocketbot.utils import timedelta_from_str, describe_timedelta, dump_stacktrace
  13. from rocketbot.storage import ConfigKey, Storage
  14. class GeneralCog(BaseCog, name='General'):
  15. """
  16. Cog for handling high-level bot functionality and commands. Should be the
  17. first cog added to the bot.
  18. """
  19. def __init__(self, bot: commands.Bot):
  20. super().__init__(bot)
  21. self.is_connected = False
  22. self.is_ready = False
  23. self.is_first_ready = True
  24. self.is_first_connect = True
  25. self.last_disconnect_time: Optional[datetime] = None
  26. self.noteworthy_disconnect_duration = timedelta(seconds=5)
  27. @commands.Cog.listener()
  28. async def on_connect(self):
  29. """Event handler"""
  30. if self.is_first_connect:
  31. self.log(None, 'Connected')
  32. self.is_first_connect = False
  33. else:
  34. disconnect_duration = datetime.now(
  35. timezone.utc) - self.last_disconnect_time if self.last_disconnect_time else None
  36. if disconnect_duration is not None and disconnect_duration > self.noteworthy_disconnect_duration:
  37. self.log(None, f'Reconnected after {disconnect_duration.total_seconds()} seconds')
  38. self.is_connected = True
  39. @commands.Cog.listener()
  40. async def on_disconnect(self):
  41. """Event handler"""
  42. self.last_disconnect_time = datetime.now(timezone.utc)
  43. # self.log(None, 'Disconnected')
  44. @commands.Cog.listener()
  45. async def on_ready(self):
  46. """Event handler"""
  47. self.log(None, 'Bot done initializing')
  48. self.is_ready = True
  49. try:
  50. synced_commands = await self.bot.tree.sync()
  51. for command in synced_commands:
  52. self.log(None, f'Synced command: {command.name}')
  53. except Exception as e:
  54. dump_stacktrace(e)
  55. if self.is_first_ready:
  56. print('----------------------------------------------------------')
  57. self.is_first_ready = False
  58. @commands.Cog.listener()
  59. async def on_resumed(self):
  60. """Event handler"""
  61. disconnect_duration = datetime.now(timezone.utc) - self.last_disconnect_time if self.last_disconnect_time else None
  62. if disconnect_duration is not None and disconnect_duration > self.noteworthy_disconnect_duration:
  63. self.log(None, f'Session resumed after {disconnect_duration.total_seconds()} seconds')
  64. @commands.command(
  65. brief='Posts a test warning',
  66. description='Tests whether a warning channel is configured for this ' + \
  67. 'guild by posting a test warning. If a mod mention is ' + \
  68. 'configured, that user/role will be tagged in the test warning.',
  69. )
  70. @commands.has_permissions(ban_members=True)
  71. @commands.guild_only()
  72. async def testwarn(self, context):
  73. """Command handler"""
  74. if Storage.get_config_value(context.guild, ConfigKey.WARNING_CHANNEL_ID) is None:
  75. await context.message.reply(
  76. f'{CONFIG["warning_emoji"]} No warning channel set!',
  77. mention_author=False)
  78. else:
  79. bm = BotMessage(
  80. context.guild,
  81. f'Test warning message (requested by {context.author.name})',
  82. type=BotMessage.TYPE_MOD_WARNING)
  83. await self.post_message(bm)
  84. @commands.command(
  85. brief='Simple test reply',
  86. description='Replies to the command message. Useful to ensure the ' + \
  87. 'bot is working properly.',
  88. )
  89. async def hello(self, context):
  90. """Command handler"""
  91. await context.message.reply(
  92. f'Hey, {context.author.name}!',
  93. mention_author=False)
  94. @commands.command(
  95. brief='Shuts down the bot',
  96. description='Causes the bot script to terminate. Only usable by a ' + \
  97. 'user with server admin permissions.',
  98. )
  99. @commands.has_permissions(administrator=True)
  100. @commands.guild_only()
  101. async def shutdown(self, context: commands.Context):
  102. """Command handler"""
  103. await context.message.add_reaction('👋')
  104. await self.bot.close()
  105. @commands.command(
  106. brief='Mass deletes messages',
  107. description='Deletes recent messages by the given user. The user ' +
  108. 'can be either an @ mention or a numeric user ID. The age is ' +
  109. 'a duration, such as "30s", "5m", "1h30m". Only the most ' +
  110. 'recent 100 messages in each channel are searched.',
  111. usage='<user:id|mention> <age:timespan>'
  112. )
  113. @commands.has_permissions(manage_messages=True)
  114. @commands.guild_only()
  115. async def deletemessages(self, context, user: str, age: str) -> None:
  116. """Command handler"""
  117. member_id = self.__parse_member_id(user)
  118. if member_id is None:
  119. await context.message.reply(
  120. f'{CONFIG["failure_emoji"]} user must be a mention or numeric user id',
  121. mention_author=False)
  122. return
  123. try:
  124. age_delta: timedelta = timedelta_from_str(age)
  125. except ValueError:
  126. await context.message.reply(
  127. f'{CONFIG["failure_emoji"]} age must be a timespan, like "30s", "10m", "1h30m"',
  128. mention_author=False)
  129. return
  130. cutoff: datetime = datetime.now(timezone.utc) - age_delta
  131. def predicate(message: Message) -> bool:
  132. return str(message.author.id) == member_id and message.created_at >= cutoff
  133. deleted_messages = []
  134. for channel in context.guild.text_channels:
  135. try:
  136. deleted_messages += await channel.purge(limit=100, check=predicate)
  137. except DiscordException:
  138. # XXX: Sloppily glossing over access errors instead of checking access
  139. pass
  140. await context.message.reply(
  141. f'{CONFIG["success_emoji"]} Deleted {len(deleted_messages)} ' + \
  142. f'messages by <@!{member_id}> from the past {describe_timedelta(age_delta)}.',
  143. mention_author=False)
  144. def __parse_member_id(self, arg: str) -> Optional[str]:
  145. p = re.compile('^<@!?([0-9]+)>$')
  146. m = p.match(arg)
  147. if m:
  148. return m.group(1)
  149. p = re.compile('^([0-9]+)$')
  150. m = p.match(arg)
  151. if m:
  152. return m.group(1)
  153. return None