Advertisement
Guest User

Untitled

a guest
Jul 21st, 2018
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.82 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3.  
  4. import discord
  5. import asyncio
  6. from bs4 import BeautifulSoup as Soup
  7. import aiohttp
  8. import json
  9.  
  10.  
  11. # Creating Discord Client and grabbing token
  12. client = discord.Client()
  13. token = open('/home/pi/Desktop/token').read()
  14. age = {'birthtime': '283993201', 'mature_content': '1'}
  15.  
  16.  
  17. async def tryget(url, c):
  18.     async with aiohttp.ClientSession(cookies=c) as cs:
  19.         async with cs.get(url) as doc:
  20.             while True:
  21.                 if doc.status == 200:
  22.                     break
  23.                 await asyncio.sleep(5)
  24.             return await doc.text()
  25.  
  26.  
  27. class SteamApp:
  28.  
  29.     # Each game is represented by a SteamApp object
  30.     def __init__(self, url):
  31.         self.url = url
  32.         loop = asyncio.get_event_loop()
  33.         storepage = loop.create_task(tryget(url, age))
  34.         loop.run_until_complete(storepage)
  35.         storesoup = Soup(storepage, 'html.parser')
  36.         self.name = storesoup.find('div', {'class': 'apphub_AppName'}).text
  37.         self.id = url.split('/')[4]
  38.         self.nurl = 'https://store.steampowered.com/news/?appids=' + self.id
  39.         self.last = None
  40.         self.news = []
  41.         self.found = None
  42.         self.message = None
  43.  
  44.     def fetchjson(self):
  45.         with open('/home/pi/Desktop/Trig-Cake/updates.json') as updates:
  46.             updatesdict = json.load(updates)
  47.         self.last = (updatesdict[self.url])
  48.  
  49.     async def parse(self):
  50.         loop = asyncio.get_event_loop()
  51.         newspage = loop.create_task(tryget(self.nurl, age))
  52.         loop.run_until_complete(newspage)
  53.         newssoup = Soup(newspage, 'html.parser')
  54.         for block in newssoup('div', {'class': 'newsPostBlock'}):
  55.             if 'newsPostBlock' in block['class']:
  56.                 self.news.append(block)
  57.         self.found = self.news[0].find('a').text
  58.  
  59.     async def trigger(self):
  60.         if self.found != self.last:
  61.             line1 = "**New announcement from " + self.name + ":**\n"
  62.             line2 = "'" + self.found + "'" + "\n"
  63.             line3 = "<" + self.nurl + ">"
  64.             self.message = line1 + line2 + line3
  65.             with open('/home/pi/Desktop/Trig-Cake/updates.json') as updates:
  66.                 updatesdict = json.load(updates)
  67.             updatesdict[self.url] = self.found
  68.             with open('/home/pi/Desktop/Trig-Cake/updates.json', 'w') as newupdates:
  69.                 json.dump(updatesdict, newupdates)
  70.             with open('/home/pi/Desktop/Trig-Cake/steam.json') as steam:
  71.                 steamdict = json.load(steam)
  72.             for channel in steamdict[self.url]:
  73.                 await client.send_message(discord.Object(id=channel), self.message)
  74.  
  75.  
  76. @client.event
  77. async def on_message(message):
  78.  
  79.     if message.content.startswith('!cake'):
  80.         typocheck = message.content.replace("!cake", "")
  81.         if len(typocheck) == 0:
  82.             info = """**I'm tasked with checking Steam games for announcements.**
  83. The following commands are available for users with Administrator perms (minus brackets):
  84. **!cakesub <url of store page>** — Subscribes channel to a game.
  85. **!cakeunsub <url of store page>** — Unsubscribes channel to a game."""
  86.             await client.send_message(message.channel, info)
  87.  
  88.     if message.content.startswith('!cakesub'):
  89.         if message.author.server_permissions.administrator:
  90.             channelid = message.channel.id
  91.             url = message.content.replace('!cakesub ', "")
  92.             prefix = 'https://store.steampowered.com/app/'
  93.  
  94.             if prefix not in url:
  95.                 await client.send_message(message.channel, "Not a valid url.")
  96.  
  97.             else:
  98.                 loop = asyncio.get_event_loop()
  99.                 storepage = loop.create_task(tryget(url, age))
  100.                 loop.run_until_complete(storepage)
  101.                 storesoup = Soup(storepage, 'html.parser')
  102.                 metatag = storesoup.find('meta', {'property': 'og:url'})
  103.                 urlcheck = metatag['content']
  104.  
  105.                 if urlcheck == 'https://store.steampowered.com/':
  106.                     await client.send_message(message.channel, "Game does not exist.")
  107.  
  108.                 else:
  109.                     with open('/home/pi/Desktop/Trig-Cake/steam.json') as steam:
  110.                         steamdict = json.load(steam)
  111.  
  112.                     if url not in steamdict:
  113.                         steamdict[url] = []
  114.                         with open('/home/pi/Desktop/Trig-Cake/steam.json', 'w') as newsteam:
  115.                             json.dump(steamdict, newsteam)
  116.                         newgame = SteamApp(url)
  117.                         newgame.parse()
  118.                         with open('/home/pi/Desktop/Trig-Cake/updates.json') as updates:
  119.                             updatesdict = json.load(updates)
  120.                         updatesdict[newgame.url] = newgame.found
  121.                         with open('/home/pi/Desktop/Trig-Cake/updates.json', 'w') as newupdates:
  122.                             json.dump(updatesdict, newupdates)
  123.  
  124.                     if channelid in steamdict[url]:
  125.                         await client.send_message(message.channel, "Channel is already subscribed to game.")
  126.  
  127.                     else:
  128.                         steamdict[url].append(channelid)
  129.                         with open('/home/pi/Desktop/Trig-Cake/steam.json', 'w') as newsteam:
  130.                             json.dump(steamdict, newsteam)
  131.                         gamename = storesoup.find('div', {'class': 'apphub_AppName'}).text
  132.                         await client.send_message(message.channel, "Channel is now subscribed to " + gamename + "!")
  133.  
  134.     if message.content.startswith('!cakeunsub'):
  135.         if message.author.server_permissions.administrator:
  136.             url = message.content.replace('!cakeunsub ', "")
  137.             channelid = message.channel.id
  138.             with open('/home/pi/Desktop/Trig-Cake/steam.json') as steam:
  139.                 steamdict = json.load(steam)
  140.             if url in steamdict:
  141.                 if channelid in steamdict[url]:
  142.                     steamdict[url].remove(channelid)
  143.                     if len(steamdict[url]) == 0:
  144.                         del steamdict[url]
  145.                         with open('/home/pi/Desktop/Trig-Cake/updates.json') as updates:
  146.                             updatesdict = json.load(updates)
  147.                         del updatesdict[url]
  148.                         with open('/home/pi/Desktop/Trig-Cake/updates.json', 'w') as newupdates:
  149.                             json.dump(updatesdict, newupdates)
  150.                     with open('/home/pi/Desktop/Trig-Cake/steam.json', 'w') as newsteam:
  151.                         json.dump(steamdict, newsteam)
  152.  
  153.                     await client.send_message(message.channel, "Channel is now unsubscribed from that game.")
  154.                 else:
  155.                     await client.send_message(message.channel, "Channel is not subscribed to that game.")
  156.             else:
  157.                 await client.send_message(message.channel, "Channel is not subscribed to that game.")
  158.  
  159.  
  160. @client.event
  161. async def background_loop():
  162.     await client.wait_until_ready()
  163.     print('Logged in as')
  164.     print(client.user.name)
  165.     print(client.user.id)
  166.     print('------')
  167.  
  168.     currentgames = []
  169.  
  170.     while not client.is_closed:
  171.         with open('/home/pi/Desktop/Trig-Cake/steam.json') as steam:
  172.             steamdict = json.load(steam)
  173.         for keys in steamdict.keys():
  174.             if keys not in currentgames:
  175.                 currentgames.append(keys)
  176.         for url in currentgames:
  177.             splices = url.split('/')
  178.             appid = splices[3] + splices[4]
  179.             vars()[appid] = SteamApp(url)
  180.             vars()[appid].parse()
  181.             vars()[appid].fetchjson()
  182.             await vars()[appid].trigger()
  183.  
  184.         print("looped")
  185.         await asyncio.sleep(60*5)
  186.  
  187.  
  188. client.loop.create_task(background_loop())
  189. client.run(token)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement