Experimental Discord bot written in Python
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

generalcog.py 4.7KB

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