A RedBot cog for sending notifications when there are new founderless regions in NationStates.
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.

177 regels
7.1 KiB

  1. from redbot.core import commands, checks, Config
  2. from redbot.core.utils.chat_formatting import pagify
  3. import discord
  4. import asyncio
  5. import requests
  6. import xml.etree.cElementTree as et
  7. import time
  8. import datetime
  9. import gzip
  10. R_HEADERS = {'User-Agent': '<Nation: Haku>'}
  11. RATE_LIMIT = 0.7
  12. def canonicalize(in_str):
  13. return in_str.lower().replace(' ', '_')
  14. def get_founderless_regions():
  15. """Return the list of founderless regions."""
  16. time.sleep(RATE_LIMIT)
  17. r = requests.get('https://www.nationstates.net/cgi-bin/api.cgi?q=regionsbytag;tags=founderless',
  18. headers=R_HEADERS)
  19. tree = et.fromstring(r.text)
  20. return tree[0].text.split(',')
  21. def download_region_dump():
  22. """Download the latest region dump from the NS API."""
  23. time.sleep(RATE_LIMIT)
  24. r = requests.get('https://www.nationstates.net/pages/regions.xml.gz',
  25. headers=R_HEADERS)
  26. with open('regions.xml.gz', 'wb') as f:
  27. f.write(r.content)
  28. with gzip.open('regions.xml.gz', 'rb') as f_in:
  29. with open('regions.xml', 'wb') as f_out:
  30. f_out.write(f_in.read())
  31. def get_region_endos(regions):
  32. """Using the region dump, return a Dict with the number of endos for each region."""
  33. tree = et.parse('regions.xml')
  34. endo_dict = dict()
  35. root = tree.getroot()
  36. for region in root:
  37. if region[0].text in regions:
  38. endo_dict[region[0].text] = int(region[5].text) - 1
  39. return endo_dict
  40. class FounderlessNotify(commands.Cog):
  41. """Notifies when a region changes in founderless status."""
  42. def __init__(self, bot, *args, **kwargs):
  43. super().__init__(*args, **kwargs)
  44. self.bot = bot
  45. self.config = Config.get_conf(self, identifier=82732344, force_registration=True)
  46. default_global_settings = {'update_time': 0, 'previous_founderless': [], 'notify_channel': 0}
  47. self.config.register_global(**default_global_settings)
  48. self.bg_loop_task = asyncio.create_task(self.bg_loop())
  49. def cog_unload(self):
  50. if self.bg_loop_task:
  51. self.bg_loop_task.cancel()
  52. @commands.command()
  53. @checks.is_owner()
  54. async def is_task_running(self, ctx):
  55. """Check if the main loop is running."""
  56. if self.bg_loop_task:
  57. await ctx.send('True')
  58. else:
  59. await ctx.send('False')
  60. @commands.command()
  61. @checks.is_owner()
  62. async def start_task(self, ctx):
  63. """Start the main loop if it is not running."""
  64. if self.bg_loop_task:
  65. await ctx.send('Task is already running')
  66. else:
  67. self.bg_loop_task = asyncio.create_task(self.bg_loop())
  68. @commands.command()
  69. @checks.is_owner()
  70. async def force_check(self, ctx, update_type):
  71. """Force perform a check in the differences of founderless regions."""
  72. if update_type.lower() == 'major' or update_type.lower() == 'minor':
  73. await self.update_founderless(update_type)
  74. else:
  75. return
  76. async def update_founderless(self, update_type):
  77. """Check for the differences in the founderless regions and then output that to a channel."""
  78. channel_id = await self.config.notify_channel()
  79. channel = self.bot.get_channel(channel_id)
  80. await channel.send(f'Beginning {update_type} check...')
  81. new_founderless_regions = get_founderless_regions()
  82. previous_founderless_regions = await self.config.previous_founderless()
  83. # A region is now foundered if it was in the previous list, but isn't in the current list
  84. # now_foundered = [region for region in previous_founderless_regions if (region not in new_founderless_regions)]
  85. # A region is now founderless if it is in the current list, but wasn't in the previous list
  86. now_founderless = [region for region in new_founderless_regions if (region not in previous_founderless_regions)]
  87. # Get the region endos for both lists
  88. # now_foundered_endos = get_region_endos(now_foundered)
  89. now_founderless_endos = get_region_endos(now_founderless)
  90. message_content = "The following regions are now **Founderless**:\n"
  91. for region in now_founderless:
  92. message_content += f"https://www.nationstates.net/region={canonicalize(region)} " \
  93. f"({now_founderless_endos[region]})\n"
  94. for page in pagify(message_content):
  95. await channel.send(page)
  96. await self.config.previous_founderless.set(new_founderless_regions)
  97. async def bg_loop(self):
  98. """Main background loop."""
  99. while True:
  100. # Only check once every 5 minutes
  101. await asyncio.sleep(300)
  102. current_time = datetime.datetime.utcnow()
  103. major_time = await self.config.update_time()
  104. minor_time = major_time + 12
  105. # Major Update
  106. if current_time.hour == (major_time + 2):
  107. download_region_dump()
  108. await self.update_founderless('major')
  109. await asyncio.sleep(3600)
  110. # Minor Update
  111. elif current_time.hour == (minor_time + 1):
  112. await self.update_founderless('minor')
  113. await asyncio.sleep(3600)
  114. @commands.command()
  115. @checks.is_owner()
  116. async def update_channel(self, ctx):
  117. """Set the notification channel."""
  118. await self.config.notify_channel.set(ctx.channel.id)
  119. await ctx.send(f'Founderless notify channel set to {ctx.channel.mention}')
  120. @commands.command()
  121. @checks.is_owner()
  122. async def update_time(self, ctx, update):
  123. """Set the update time."""
  124. update = int(update)
  125. await self.config.update_time.set(update)
  126. await ctx.send(f'Major update set to: {await self.config.update_time()}:00 UTC'
  127. f'\nMinor update set to: {await self.config.update_time() + 12}:00 UTC')
  128. @commands.command()
  129. @checks.is_owner()
  130. async def get_settings(self, ctx):
  131. """Get the current settings from config."""
  132. stored_channel = await self.config.notify_channel()
  133. major_time = await self.config.update_time()
  134. minor_time = major_time + 12
  135. founderless = await self.config.previous_founderless()
  136. channel = ctx.guild.get_channel(stored_channel)
  137. await ctx.send(f'Current Channel: {channel.mention}\nCurrent Major Update Time: {major_time}:00 UTC\n'
  138. f'Current Minor Update Time: {minor_time}:00 UTC\nCurrent # Founderless: {len(founderless)}')
  139. @commands.command()
  140. @checks.is_owner()
  141. async def force_update_founderless(self, ctx):
  142. """Manually update the founderless region list."""
  143. founderless_regions = get_founderless_regions()
  144. await self.config.previous_founderless.set(founderless_regions)
  145. await ctx.send(f'Manually updated founderless regions list. There are now '
  146. f'{len(founderless_regions)} founderless regions.')
  147. @commands.command()
  148. @checks.is_owner()
  149. async def force_download_dump(self, ctx):
  150. """Manually download the region dump."""
  151. await ctx.send('Downloading region dump...')
  152. download_region_dump()
  153. await ctx.send('Region dump successfully updated.')