Advertisement
Guest User

Cog

a guest
Jul 24th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.06 KB | None | 0 0
  1. import requests
  2. import sqlite3
  3. import discord
  4. from discord.ext import tasks, commands
  5. from bs4 import BeautifulSoup
  6. from prettytable import from_db_cursor
  7. from os import system
  8.  
  9.  
  10.  
  11. ALLKEYSHOPURL = 'allkeyshop.com/blog/'
  12. STEAMURL = 'store.steampowered.com/app/'
  13.  
  14. conn = sqlite3.connect('gamehunter.db')
  15. c = conn.cursor()
  16.  
  17.  
  18.  
  19. class Hunter(commands.Cog):
  20.     def __init__(self, bot):
  21.         self.bot = bot
  22.  
  23.  
  24.     def get_game_record(self, url):
  25.         if ALLKEYSHOPURL.lower() in url.lower():
  26.             r = requests.get(url)
  27.             soup = BeautifulSoup(r.content, 'lxml')
  28.             title = soup.find('span', {'itemprop': 'name'}).text.strip()
  29.             cheapest_row = soup.find('div', {'class': 'offers-table-row'})
  30.             merchant = cheapest_row.find('span', {'class': 'offers-merchant-name'}).text
  31.             price = cheapest_row.find('span', {'itemprop': 'price'})['content']
  32.             return {'title': title, 'merchant': merchant, 'price': price, 'url': url}
  33.         elif STEAMURL.lower() in url.lower():
  34.             currency_payload = {'cc': 'de'}
  35.             r = requests.get(url, params=currency_payload)
  36.             soup = BeautifulSoup(r.content, 'lxml')
  37.             title = soup.find('span', {'itemprop': 'name'}).text.strip()
  38.             price = soup.find('div', {'data-price-final': True})['data-price-final']
  39.             price = price[:-2] + '.' + price[-2:]
  40.             return {'title': title, 'merchant': 'steam', 'price': price, 'url': url}
  41.  
  42.         return None
  43.  
  44.     def db_add_user(self, user_id, username):
  45.         try:
  46.             with conn:
  47.                 c.execute("INSERT INTO users VALUES (:user_id, :username)", {'user_id': user_id, 'username': username})
  48.         except sqlite3.IntegrityError:
  49.             pass
  50.  
  51.     def db_add_game(self, game_record):
  52.         try:
  53.             with conn:
  54.                 c.execute("INSERT INTO games VALUES (:title, :merchant, :price, :url)", game_record)
  55.         except sqlite3.IntegrityError:
  56.             pass
  57.         except ValueError:
  58.             pass
  59.  
  60.     def db_add_wish(self, user_id, wished_price, url):
  61.         try:
  62.             with conn:
  63.                 c.execute("INSERT INTO wishlist VALUES (:user_id, :wished_price, :url, 0)",
  64.                           {'user_id': user_id, 'wished_price': wished_price, 'url': url})
  65.         except sqlite3.IntegrityError:
  66.             print('You already have that on your wishlist!')
  67.  
  68.     def db_get_user_wish_table(self, user_id):
  69.         with conn:
  70.             return c.execute("""SELECT title, wished_price, price, merchant
  71.            FROM wishlist, games
  72.            WHERE user_id = :user_id AND wishlist.url = games.url""",
  73.                              {'user_id': user_id})
  74.  
  75.  
  76.     def db_get_user_wish_list(self, user_id):
  77.         with conn:
  78.             c.execute("""SELECT * FROM wishlist WHERE user_id = :user_id""",
  79.                              {'user_id': user_id})
  80.  
  81.             return c.fetchall()
  82.  
  83.     def db_update_game(self, game_record):
  84.         with conn:
  85.             c.execute("""UPDATE games
  86.            SET title = :title, price = :price, merchant = :merchant
  87.            WHERE url = :url""", game_record)
  88.  
  89.     def db_get_game_record(self, url=None, title=None):
  90.         with conn:
  91.             if url is not None:
  92.                 c.execute("""SELECT * FROM games WHERE url = :url""", {'url': url})
  93.                 record = c.fetchone()
  94.             elif title is not None:
  95.                 c.execute("""SELECT * FROM games WHERE LOWER(title) = LOWER(:title) ORDER BY url DESC""",
  96.                           {'title': title})
  97.                 record = c.fetchone()
  98.             else:
  99.                 record = None
  100.  
  101.             if record is None:
  102.                 return None
  103.  
  104.             game_record = dict(zip(('title', 'merchant', 'price', 'url'), record))
  105.             return game_record
  106.  
  107.  
  108.     def db_get_all_game_urls(self):
  109.         with conn:
  110.             c.execute("""SELECT url FROM games""")
  111.             urls = c.fetchall()
  112.             gameUrlList = []
  113.             for url in urls:
  114.                 gameUrlList.append(url[0])
  115.  
  116.             return gameUrlList
  117.  
  118.     def db_update_all_games(self, gameUrlList):
  119.         for url in gameUrlList:
  120.             game_record = self.get_game_record(url)
  121.             self.db_update_game(game_record)
  122.  
  123.     def db_get_all_user_id(self):
  124.         with conn:
  125.             c.execute("""SELECT user_id FROM users""")
  126.             users = c.fetchall()
  127.             user_id_list = []
  128.             for user in users:
  129.                 user_id_list.append(user[0])
  130.  
  131.             return user_id_list
  132.  
  133.     def db_set_notified(self, user_id, url, notified=False):
  134.         with conn:
  135.             c.execute("""UPDATE wishlist
  136.            SET notified = :notified
  137.            WHERE user_id = :user_id AND url = :url""",
  138.                       {'notified': notified, 'user_id': user_id, 'url': url})
  139.  
  140.     def db_del_wish_command(self, user_id, title):
  141.         with conn:
  142.             c.execute("""DELETE FROM wishlist
  143.            WHERE wishlist.url IN (SELECT games.url FROM games WHERE LOWER(games.title) = LOWER(:title))
  144.            AND user_id = :user_id""",
  145.                       {'title': title, 'user_id': user_id})
  146.  
  147.     def db_update_wish_command(self, user_id, wished_price, title):
  148.         with conn:
  149.             c.execute("""UPDATE wishlist
  150.            SET wished_price = :wished_price
  151.            WHERE user_id = :user_id
  152.            AND wishlist.url IN (SELECT games.url FROM games WHERE LOWER(games.title) = LOWER(:title))""",
  153.                       {'user_id': user_id, 'wished_price': wished_price, 'title': title})
  154.  
  155.     @commands.command()
  156.     async def ping(self, ctx):
  157.         await ctx.send(f'Pong! {round(self.bot.latency * 1000)}ms')
  158.  
  159.  
  160.     @commands.command(aliases=['w'])
  161.     async def wish(self, ctx, wished_price, *, url_or_title):
  162.         # When the input is not an url, search database for a given title
  163.         if url_or_title.lower().startswith('http') is False:
  164.             record = self.db_get_game_record(title=url_or_title.strip())
  165.  
  166.             # If the game is not in the database, tell that to the user and quit
  167.             if record is None:
  168.                 await ctx.send('Game not found')
  169.                 return
  170.             url_or_title = record['url']
  171.  
  172.         # If the game is not in the database games table, add it
  173.         if self.db_get_game_record(url_or_title) is None:
  174.             game_record = self.get_game_record(url_or_title)
  175.  
  176.             if game_record is None:
  177.                 await ctx.send('Invalid URL.')
  178.                 return
  179.  
  180.             self.db_add_game(game_record)
  181.  
  182.         username = f'{ctx.author.name}#{ctx.author.discriminator}'
  183.         self.db_add_user(ctx.author.id, username)
  184.         self.db_add_wish(ctx.author.id, wished_price, url_or_title)
  185.         await ctx.send('Game added to wishlist!')
  186.  
  187.     @commands.command(aliases=['wl'])
  188.     async def wishlist(self, ctx, member: discord.Member = None):
  189.         if member is None:
  190.             wishlist = self.db_get_user_wish_table(ctx.author.id)
  191.         else:
  192.             wishlist = self.db_get_user_wish_table(member.id)
  193.         data = from_db_cursor(wishlist)
  194.         await ctx.send(f"```{data}```")
  195.  
  196.     @commands.command(aliases=['d', 'del'])
  197.     async def delete(self, ctx, *, title):
  198.         self.db_del_wish_command(ctx.author.id, title)
  199.         await ctx.send('Wish deleted!')
  200.  
  201.     @commands.command()
  202.     async def prank(self, ctx, member: discord.Member):
  203.         if member.id == 304658956750422019:
  204.             await ctx.send('A bana chcesz?')
  205.             return
  206.         await member.move_to(None)
  207.  
  208.     @commands.command(aliases=['u'])
  209.     async def update(self, ctx, wished_price, *, title):
  210.         self.db_update_wish_command(ctx.author.id, wished_price, title)
  211.         await ctx.send('Wish updated!')
  212.  
  213.     @commands.Cog.listener()
  214.     async def on_command_error(self, ctx, error):
  215.         if isinstance(error, commands.MissingRequiredArgument):
  216.             await ctx.send('An argument is missing.')
  217.  
  218.  
  219.  
  220. def setup(bot):
  221.     bot.add_cog(Hunter(bot))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement