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.

167 lines
6.9KB

  1. from cogs.utils.dataIO import dataIO
  2. from discord.ext import commands
  3. import aiohttp
  4. import discord
  5. import difflib
  6. import os
  7. import re
  8. class Steam:
  9. def __init__(self, bot):
  10. self.bot = bot
  11. self.games = dataIO.load_json('data/steam/games.json')['applist']['apps']['app']
  12. async def _update_apps(self):
  13. payload = {}
  14. url = 'http://api.steampowered.com/ISteamApps/GetAppList/v0001/'
  15. headers = {'user-agent': 'KiTTY/1.0'}
  16. conn = aiohttp.TCPConnector(verify_ssl=False)
  17. session = aiohttp.ClientSession(connector=conn)
  18. async with session.get(url, params=payload, headers=headers) as r:
  19. data = await r.json()
  20. session.close()
  21. self.games = data['applist']['apps']['app']
  22. dataIO.save_json('data/steam/games.json', data)
  23. async def _app_info(self, gid):
  24. url = 'http://store.steampowered.com/api/appdetails?'
  25. payload = {}
  26. payload['appids'] = gid
  27. headers = {'user-agent': 'KiTTY/1.0'}
  28. conn = aiohttp.TCPConnector(verify_ssl=False)
  29. session = aiohttp.ClientSession(connector=conn)
  30. async with session.get(url, params=payload, headers=headers) as r:
  31. data = await r.json()
  32. session.close()
  33. if data[str(gid)]['success']:
  34. data = data[str(gid)]['data']
  35. info = {}
  36. info['name'] = data['name']
  37. info['developers'] = data['developers']
  38. info['publishers'] = data['publishers']
  39. if data['is_free']:
  40. info['price'] = 'Free to Play'
  41. elif 'price_overview' not in data:
  42. info['price'] = 'Not available'
  43. else:
  44. info['price'] = '{} {}'.format(str(data['price_overview']['final'] / 100), (data['price_overview']['currency']))
  45. if data['price_overview']['discount_percent'] > 0:
  46. info['price'] = '{} {} ({} -{}%)'.format(str(data['price_overview']['final'] / 100), data['price_overview']['currency'], str(data['price_overview']['initial'] / 100), str(data['price_overview']['discount_percent']))
  47. if data['release_date']['coming_soon']:
  48. info['release_date'] = 'Coming Soon'
  49. else:
  50. info['release_date'] = data['release_date']['date']
  51. info['genres'] = data['genres']
  52. info['recommendations'] = ''
  53. if 'recommendations' in data:
  54. info['recommendations'] = 'Recommendations: {}\n\n'.format(str(data['recommendations']['total']))
  55. info['about_the_game'] = re.sub("<.*?>", " ", data['about_the_game'].replace(' ', '').replace('\r', '').replace('<br>', '\n').replace('\t', ''))
  56. if len(info['about_the_game']) > 500:
  57. info['about_the_game'] = '{}...'.format(info['about_the_game'][:500-3])
  58. return info
  59. return False
  60. async def _app_type(self, gid):
  61. url = 'http://store.steampowered.com/api/appdetails?'
  62. payload = {}
  63. payload['appids'] = gid
  64. headers = {'user-agent': 'KiTTY/1.0'}
  65. conn = aiohttp.TCPConnector(verify_ssl=False)
  66. session = aiohttp.ClientSession(connector=conn)
  67. async with session.get(url, params=payload, headers=headers) as r:
  68. data = await r.json()
  69. session.close()
  70. if data[str(gid)]['success']:
  71. data = data[str(gid)]['data']
  72. app_type = data['type']
  73. return app_type
  74. return False
  75. async def _game_search(self, game):
  76. games = []
  77. match = False
  78. for app in self.games:
  79. name = app['name']
  80. appid = app['appid']
  81. x = difflib.SequenceMatcher(None, name.lower(), game.lower()).ratio()
  82. if x > 0.92:
  83. app_type = await self._app_type(appid)
  84. if app_type == 'game':
  85. match = app
  86. elif game.lower() in name.lower():
  87. if len(games) > 10:
  88. break
  89. games.append(app)
  90. if game.lower() == name.lower():
  91. match = app
  92. break
  93. return match, games
  94. @commands.command(pass_context=True, no_pm=True, name='steam', aliases=['st', 'Steam'])
  95. async def _steam(self, context, *game: str):
  96. game = " ".join(game)
  97. game_match = await self._game_search(game)
  98. match = game_match[0]
  99. games = game_match[1]
  100. if match:
  101. info = await self._app_info(match['appid'])
  102. if info:
  103. em = discord.Embed(title='{}'.format(match['name']), color=discord.Color.blue(), url='http://store.steampowered.com/app/{}'.format(match['appid']))
  104. em.add_field(name='\a', value='\a', inline=False)
  105. em.add_field(name='**Price**', value=info['price'])
  106. em.add_field(name='**Genre**', value=', '.join([genre['description'] for genre in info['genres']]))
  107. em.add_field(name='\a', value='\a')
  108. em.add_field(name='**Release date**', value=info['release_date'])
  109. em.add_field(name='**Developed by**', value=', '.join([developer for developer in info['developers']]))
  110. em.add_field(name='**Published by**', value=', '.join([publisher for publisher in info['publishers']]))
  111. em.add_field(name='\a', value=info['about_the_game'], inline=False)
  112. em.set_footer(text='Information provided by Steam', icon_url='http://store.akamai.steamstatic.com/public/shared/images/header/globalheader_logo.png')
  113. await self.bot.say(embed=em)
  114. else:
  115. message = '`Game was found, but could not retrieve relevant information`'
  116. await self.bot.say(message)
  117. elif games:
  118. message = '```This game was not found. But I found this:\n\n'
  119. for game in games:
  120. message += '{}\n'.format(game['name'])
  121. message += '```'
  122. await self.bot.say(message)
  123. else:
  124. message = '`This game could not be found`'
  125. await self.bot.say(message)
  126. @commands.command(pass_context=True, no_pm=True, name='steamupdate', aliases=['stupdate'])
  127. async def _update(self, context):
  128. try:
  129. await self._update_apps()
  130. message = 'Game list updated.'
  131. except Exception as error:
  132. message = 'Could not update. Check console for more information.'
  133. print(error)
  134. await self.bot.say(message)
  135. def check_folder():
  136. if not os.path.exists('data/steam'):
  137. print('Creating data/steam folder...')
  138. os.makedirs('data/steam')
  139. def check_file():
  140. data = {}
  141. data['applist'] = {}
  142. data['applist']['apps'] = {}
  143. data['applist']['apps']['app'] = []
  144. f = 'data/steam/games.json'
  145. if not dataIO.is_valid_json(f):
  146. print('Creating default games.json...')
  147. dataIO.save_json(f, data)
  148. def setup(bot):
  149. check_folder()
  150. check_file()
  151. cog = Steam(bot)
  152. bot.add_cog(cog)