Experimental Discord bot written in Python
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

generalcog.py 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. @commands.Cog.listener()
  23. async def on_connect(self):
  24. 'Event handler'
  25. print('on_connect')
  26. self.is_connected = True
  27. @commands.Cog.listener()
  28. async def on_ready(self):
  29. 'Event handler'
  30. print('on_ready')
  31. self.is_ready = True
  32. @commands.command(
  33. brief='Posts a test warning',
  34. description='Tests whether a warning channel is configured for this ' + \
  35. 'guild by posting a test warning. If a mod mention is ' + \
  36. 'configured, that user/role will be tagged in the test warning.',
  37. )
  38. @commands.has_permissions(ban_members=True)
  39. @commands.guild_only()
  40. async def testwarn(self, context):
  41. 'Command handler'
  42. if Storage.get_config_value(context.guild, ConfigKey.WARNING_CHANNEL_ID) is None:
  43. await context.message.reply(
  44. f'{CONFIG["warning_emoji"]} No warning channel set!',
  45. mention_author=False)
  46. else:
  47. bm = BotMessage(
  48. context.guild,
  49. f'Test warning message (requested by {context.author.name})',
  50. type=BotMessage.TYPE_MOD_WARNING)
  51. await self.post_message(bm)
  52. @commands.command(
  53. brief='Simple test reply',
  54. description='Replies to the command message. Useful to ensure the ' + \
  55. 'bot is working properly.',
  56. )
  57. async def hello(self, context):
  58. 'Command handler'
  59. await context.message.reply(
  60. f'Hey, {context.author.name}!',
  61. mention_author=False)
  62. @commands.command(
  63. brief='Shuts down the bot',
  64. description='Causes the bot script to terminate. Only usable by a ' + \
  65. 'user with server admin permissions.',
  66. )
  67. @commands.has_permissions(administrator=True)
  68. @commands.guild_only()
  69. async def shutdown(self, context: commands.Context):
  70. 'Command handler'
  71. await context.message.add_reaction('👋')
  72. await self.bot.close()
  73. @commands.command(
  74. brief='Mass deletes messages',
  75. description='Deletes recent messages by the given user. The user ' +
  76. 'can be either an @ mention or a numeric user ID. The age is ' +
  77. 'a duration, such as "30s", "5m", "1h30m". Only the most ' +
  78. 'recent 100 messages in each channel are searched.',
  79. usage='<user:id|mention> <age:timespan>'
  80. )
  81. @commands.has_permissions(manage_messages=True)
  82. @commands.guild_only()
  83. async def deletemessages(self, context, user: str, age: str) -> None:
  84. 'Command handler'
  85. member_id = self.__parse_member_id(user)
  86. if member_id is None:
  87. await context.message.reply(
  88. f'{CONFIG["failure_emoji"]} user must be a mention or numeric user id',
  89. mention_author=False)
  90. return
  91. try:
  92. age_delta: timedelta = timedelta_from_str(age)
  93. except ValueError:
  94. await context.message.reply(
  95. f'{CONFIG["failure_emoji"]} age must be a timespan, like "30s", "10m", "1h30m"',
  96. mention_author=False)
  97. return
  98. cutoff: datetime = datetime.utcnow() - age_delta
  99. def predicate(message: Message) -> bool:
  100. return str(message.author.id) == member_id and message.created_at >= cutoff
  101. deleted_messages = []
  102. for channel in context.guild.text_channels:
  103. try:
  104. deleted_messages += await channel.purge(limit=100, check=predicate)
  105. except DiscordException:
  106. # XXX: Sloppily glossing over access errors instead of checking access
  107. pass
  108. await context.message.reply(
  109. f'{CONFIG["success_emoji"]} Deleted {len(deleted_messages)} ' + \
  110. f'messages by <@!{member_id}> from the past {describe_timedelta(age_delta)}.',
  111. mention_author=False)
  112. def __parse_member_id(self, arg: str) -> str:
  113. p = re.compile('^<@!?([0-9]+)>$')
  114. m = p.match(arg)
  115. if m:
  116. return m.group(1)
  117. p = re.compile('^([0-9]+)$')
  118. m = p.match(arg)
  119. if m:
  120. return m.group(1)
  121. return None