KiTTY, un bot Discord qui est un petit chat :) Il est basé sur une ancienne version du bot Red, sous Python 3.6 et qui a des fonctionnalités bien sympatiques !
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

107 lines
4.1 KiB

  1. import discord
  2. from discord.ext import commands
  3. from .utils.dataIO import fileIO
  4. import os
  5. import asyncio
  6. import time
  7. import logging
  8. class RemindMe:
  9. """Never forget anything anymore."""
  10. def __init__(self, bot):
  11. self.bot = bot
  12. self.reminders = fileIO("data/remindme/reminders.json", "load")
  13. self.units = {"minute" : 60, "hour" : 3600, "day" : 86400, "week": 604800, "month": 2592000}
  14. @commands.command(pass_context=True)
  15. async def remindme(self, ctx, quantity : int, time_unit : str, *, text : str):
  16. """Sends you <text> when the time is up
  17. Accepts: minutes, hours, days, weeks, month
  18. Example:
  19. [p]remindme 3 days Have sushi with Asu and JennJenn"""
  20. time_unit = time_unit.lower()
  21. author = ctx.message.author
  22. s = ""
  23. if time_unit.endswith("s"):
  24. time_unit = time_unit[:-1]
  25. s = "s"
  26. if not time_unit in self.units:
  27. await self.bot.say("Invalid time unit. Choose minutes/hours/days/weeks/month")
  28. return
  29. if quantity < 1:
  30. await self.bot.say("Quantity must not be 0 or negative.")
  31. return
  32. if len(text) > 1960:
  33. await self.bot.say("Text is too long.")
  34. return
  35. seconds = self.units[time_unit] * quantity
  36. future = int(time.time()+seconds)
  37. self.reminders.append({"ID" : author.id, "FUTURE" : future, "TEXT" : text})
  38. logger.info("{} ({}) set a reminder.".format(author.name, author.id))
  39. await self.bot.say("I will remind you that in {} {}.".format(str(quantity), time_unit + s))
  40. fileIO("data/remindme/reminders.json", "save", self.reminders)
  41. @commands.command(pass_context=True)
  42. async def forgetme(self, ctx):
  43. """Removes all your upcoming notifications"""
  44. author = ctx.message.author
  45. to_remove = []
  46. for reminder in self.reminders:
  47. if reminder["ID"] == author.id:
  48. to_remove.append(reminder)
  49. if not to_remove == []:
  50. for reminder in to_remove:
  51. self.reminders.remove(reminder)
  52. fileIO("data/remindme/reminders.json", "save", self.reminders)
  53. await self.bot.say("All your notifications have been removed.")
  54. else:
  55. await self.bot.say("You don't have any upcoming notification.")
  56. async def check_reminders(self):
  57. while self is self.bot.get_cog("RemindMe"):
  58. to_remove = []
  59. for reminder in self.reminders:
  60. if reminder["FUTURE"] <= int(time.time()):
  61. try:
  62. await self.bot.send_message(discord.User(id=reminder["ID"]), "You asked me to remind you this:\n{}".format(reminder["TEXT"]))
  63. except (discord.errors.Forbidden, discord.errors.NotFound):
  64. to_remove.append(reminder)
  65. except discord.errors.HTTPException:
  66. pass
  67. else:
  68. to_remove.append(reminder)
  69. for reminder in to_remove:
  70. self.reminders.remove(reminder)
  71. if to_remove:
  72. fileIO("data/remindme/reminders.json", "save", self.reminders)
  73. await asyncio.sleep(5)
  74. def check_folders():
  75. if not os.path.exists("data/remindme"):
  76. print("Creating data/remindme folder...")
  77. os.makedirs("data/remindme")
  78. def check_files():
  79. f = "data/remindme/reminders.json"
  80. if not fileIO(f, "check"):
  81. print("Creating empty reminders.json...")
  82. fileIO(f, "save", [])
  83. def setup(bot):
  84. global logger
  85. check_folders()
  86. check_files()
  87. logger = logging.getLogger("remindme")
  88. if logger.level == 0: # Prevents the logger from being loaded again in case of module reload
  89. logger.setLevel(logging.INFO)
  90. handler = logging.FileHandler(filename='data/remindme/reminders.log', encoding='utf-8', mode='a')
  91. handler.setFormatter(logging.Formatter('%(asctime)s %(message)s', datefmt="[%d/%m/%Y %H:%M]"))
  92. logger.addHandler(handler)
  93. n = RemindMe(bot)
  94. loop = asyncio.get_event_loop()
  95. loop.create_task(n.check_reminders())
  96. bot.add_cog(n)