Experimental Discord bot written in Python
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

generalcog.py 4.3KB

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