A RedBot cog for sending notifications when there are new founderless regions in NationStates.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

197 řádky
7.6 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 [canonicalize(region) for region in 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. region_name = canonicalize(region[0].text)
  39. endo_dict[region_name] = int(region[5].text) - 1
  40. return endo_dict
  41. class FounderlessNotify(commands.Cog):
  42. """Notifies when a region changes in founderless status."""
  43. def __init__(self, bot, *args, **kwargs):
  44. super().__init__(*args, **kwargs)
  45. self.bot = bot
  46. self.config = Config.get_conf(self, identifier=82732344, force_registration=True)
  47. default_global_settings = {'update_time': 0, 'previous_founderless': [], 'notify_channel': 0}
  48. self.config.register_global(**default_global_settings)
  49. def cog_unload(self):
  50. pass
  51. @commands.command()
  52. @checks.is_owner()
  53. async def is_task_running(self, ctx):
  54. """Check if the main loop is running."""
  55. if self.bg_loop_task:
  56. await ctx.send('True')
  57. else:
  58. await ctx.send('False')
  59. @commands.command()
  60. @checks.is_owner()
  61. async def start_task(self, ctx):
  62. """Start the main loop if it is not running."""
  63. if self.bg_loop_task:
  64. await ctx.send('Task is already running')
  65. else:
  66. self.bg_loop_task = asyncio.create_task(self.bg_loop())
  67. @commands.command()
  68. @checks.is_owner()
  69. async def force_check(self, ctx, update_type):
  70. """Force perform a check in the differences of founderless regions."""
  71. if update_type.lower() == 'major' or update_type.lower() == 'minor':
  72. await self.update_founderless(update_type)
  73. else:
  74. return
  75. async def update_founderless(self, update_type):
  76. """Check for the differences in the founderless regions and then output that to a channel."""
  77. channel_id = await self.config.notify_channel()
  78. channel = self.bot.get_channel(channel_id)
  79. await channel.send(f'Beginning {update_type} check...')
  80. new_founderless_regions = get_founderless_regions()
  81. previous_founderless_regions = await self.config.previous_founderless()
  82. # A region is now founderless if it is in the current list, but wasn't in the previous list
  83. now_founderless = list()
  84. for region in new_founderless_regions:
  85. if region in previous_founderless_regions:
  86. continue
  87. now_founderless.append(region)
  88. print(now_founderless)
  89. # Get the region endos for both lists
  90. now_founderless_endos = get_region_endos(now_founderless)
  91. # Create an ordered set with each region's name and delegate endorsement level
  92. out = list()
  93. for region in now_founderless:
  94. try:
  95. region_endos = now_founderless_endos[region]
  96. except KeyError:
  97. region_endos = -1
  98. out.append((region_endos, region))
  99. print(now_founderless_endos["the_north_pacific"])
  100. # Sort the output by delegate endos in descending order
  101. out.sort()
  102. out.reverse()
  103. # Prep output
  104. message_content = "The following regions are now **Founderless**:\n"
  105. for region in out:
  106. message_content += f"https://www.nationstates.net/region={region[1]} ({region[0]})\n"
  107. for page in pagify(message_content):
  108. await channel.send(page)
  109. await self.config.previous_founderless.set(new_founderless_regions)
  110. async def bg_loop(self):
  111. """Main background loop."""
  112. while True:
  113. # Only check once every 5 minutes
  114. await asyncio.sleep(300)
  115. current_time = datetime.datetime.utcnow()
  116. major_time = await self.config.update_time()
  117. minor_time = major_time + 12
  118. # Major Update
  119. if current_time.hour == (major_time + 2):
  120. download_region_dump()
  121. await self.update_founderless('major')
  122. await asyncio.sleep(3600)
  123. # Minor Update
  124. elif current_time.hour == (minor_time + 1):
  125. await self.update_founderless('minor')
  126. await asyncio.sleep(3600)
  127. @commands.command()
  128. @checks.is_owner()
  129. async def update_channel(self, ctx):
  130. """Set the notification channel."""
  131. await self.config.notify_channel.set(ctx.channel.id)
  132. await ctx.send(f'Founderless notify channel set to {ctx.channel.mention}')
  133. @commands.command()
  134. @checks.is_owner()
  135. async def update_time(self, ctx, update):
  136. """Set the update time."""
  137. update = int(update)
  138. await self.config.update_time.set(update)
  139. await ctx.send(f'Major update set to: {await self.config.update_time()}:00 UTC'
  140. f'\nMinor update set to: {await self.config.update_time() + 12}:00 UTC')
  141. @commands.command()
  142. @checks.is_owner()
  143. async def get_settings(self, ctx):
  144. """Get the current settings from config."""
  145. stored_channel = await self.config.notify_channel()
  146. major_time = await self.config.update_time()
  147. minor_time = major_time + 12
  148. founderless = await self.config.previous_founderless()
  149. channel = ctx.guild.get_channel(stored_channel)
  150. await ctx.send(f'Current Channel: {channel.mention}\nCurrent Major Update Time: {major_time}:00 UTC\n'
  151. f'Current Minor Update Time: {minor_time}:00 UTC\nCurrent # Founderless: {len(founderless)}')
  152. @commands.command()
  153. @checks.is_owner()
  154. async def force_update_founderless(self, ctx):
  155. """Manually update the founderless region list."""
  156. founderless_regions = get_founderless_regions()
  157. await self.config.previous_founderless.set(founderless_regions)
  158. await ctx.send(f'Manually updated founderless regions list. There are now '
  159. f'{len(founderless_regions)} founderless regions.')
  160. @commands.command()
  161. @checks.is_owner()
  162. async def clear_founderless(self, ctx):
  163. """Clear the cached founderless regions."""
  164. await self.config.previous_founderless.set([])
  165. await ctx.send("Cleared cached founderless regions.")
  166. @commands.command()
  167. @checks.is_owner()
  168. async def force_download_dump(self, ctx):
  169. """Manually download the region dump."""
  170. await ctx.send('Downloading region dump...')
  171. download_region_dump()
  172. await ctx.send('Region dump successfully updated.')