Guest User

bingo bot

a guest
May 1st, 2017
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.68 KB | None | 0 0
  1. import os
  2. import re
  3. import sys
  4. import time
  5. import praw
  6. import ctypes
  7. import random
  8. import win32ui
  9. import asyncio
  10. import discord
  11. import pyimgur
  12. import requests
  13. import subprocess
  14.  
  15. from time import sleep
  16. from bs4 import BeautifulSoup
  17. from selenium import webdriver
  18. from datetime import datetime, time
  19. from praw.exceptions import ClientException
  20.  
  21. # channels
  22. memes = ''
  23. megalinks = ''
  24. bots = ''
  25.  
  26. channel_id = bots
  27. owner = ''
  28.  
  29. client_id = ''
  30.  
  31. # emoji control
  32. white_skin = ':skin-tone-1:'
  33. black_skin = ':skin-tone-5:'
  34.  
  35. skin_tone = white_skin
  36.  
  37. peace_emoji = ':v:' + skin_tone
  38. ok_emoji = ':ok_hand:' + skin_tone
  39.  
  40. def WindowExists(classname):
  41.     try:
  42.         win32ui.FindWindow(None, classname)
  43.     except win32ui.error:
  44.         return False
  45.     else:
  46.         return True
  47.  
  48. CACHE = {}
  49.  
  50.  
  51. # on start events
  52. print ("\nStatus: Connecting.")
  53.  
  54. client = discord.Client()
  55. channel = discord.Object(id=channel_id)
  56. bot_token = ''
  57. bot_name = 'Bingo-Bot'
  58. slave_bot_name = 'Bungo-Bot'
  59.  
  60. bot_version = '1.5.0'
  61.  
  62. ctypes.windll.kernel32.SetConsoleTitleW(bot_name)
  63.  
  64. # on message events
  65. @client.event
  66. async def on_message(message):
  67.  
  68.     if message.author == client.user:
  69.         return
  70.  
  71.     if message.content.startswith('!view'):
  72.         cmd = str(message.content).split()
  73.         im = pyimgur.Imgur(client_id)
  74.  
  75.         scrape_url = cmd[1]
  76.  
  77.         if scrape_url.startswith('http'):
  78.             scrape_url = scrape_url
  79.         else:
  80.             scrape_url = 'http://' + scrape_url
  81.  
  82.         fetching = 'Scraping %s. This takes a little while.' % (scrape_url)
  83.         await client.send_message(client.get_channel(channel_id), fetching)
  84.  
  85.         filename = 'k.png'
  86.  
  87.         download_location = 'E:/screenshots/%s' % (filename)
  88.         title = 'screenshot of %s' % (scrape_url)
  89.  
  90.         driver = webdriver.Firefox()
  91.         driver.maximize_window()
  92.         driver.set_window_position(2000, 2000)
  93.  
  94.         driver.get(scrape_url)
  95.         driver.save_screenshot(download_location)
  96.  
  97.         driver.quit()
  98.  
  99.         saving = "Saving screenshot... We're halfway there."
  100.         await client.send_message(client.get_channel(channel_id), saving)
  101.         await client.purge_from(client.get_channel(channel_id), limit=100, check=lambda m: m.content == fetching)
  102.  
  103.         uploaded_image = im.upload_image(download_location, title=title)
  104.  
  105.         uploading = 'Uploading screenshot... Almost done.'
  106.         await client.send_message(client.get_channel(channel_id), uploading)
  107.         await client.purge_from(client.get_channel(channel_id), limit=100, check=lambda m: m.content == saving)
  108.  
  109.         img_url = uploaded_image.link
  110.         msg = img_url
  111.  
  112.         await asyncio.sleep(2)
  113.         await client.purge_from(client.get_channel(channel_id), limit=100, check=lambda m: m.content == uploading)
  114.         await client.send_typing(client.get_channel(channel_id))
  115.         await asyncio.sleep(.3)
  116.         await client.send_message(client.get_channel(channel_id), msg)
  117.  
  118.         os.system("taskkill /im firefox.exe")
  119.  
  120.     if message.content.startswith('!reddit'):
  121.         cmd = str(message.content).split()
  122.  
  123.         subreddit = cmd[2]
  124.  
  125.         try:
  126.             post_limit = int(cmd[3])
  127.         except IndexError:
  128.             post_limit = 3
  129.  
  130.         reddit = praw.Reddit(
  131.             client_id='',
  132.             client_secret='',
  133.             password='',
  134.             user_agent='',
  135.             username='')
  136.  
  137.         if cmd[1] == 'top':
  138.  
  139.             for submission in reddit.subreddit(subreddit).top(limit=post_limit):
  140.                 msg = submission.url
  141.                 await client.send_typing(client.get_channel(channel_id))
  142.                 await asyncio.sleep(.3)
  143.                 await client.send_message(client.get_channel(channel_id), msg)
  144.  
  145.         if cmd[1] == 'new':
  146.  
  147.             for submission in reddit.subreddit(subreddit).new(limit=post_limit):
  148.                 msg = submission.url
  149.                 await client.send_typing(client.get_channel(channel_id))
  150.                 await asyncio.sleep(.3)
  151.                 await client.send_message(client.get_channel(channel_id), msg)
  152.  
  153.         if cmd[1] == 'random':
  154.  
  155.             try:
  156.                 random_post = reddit.subreddit(subreddit).random()
  157.                 msg = random_post.url
  158.  
  159.             except ClientException as ce:
  160.                 if ce.args[0].lower().endswith(subreddit.lower() + '/'):
  161.                     msg_error = 'Reddit bug, getting random post client-side...'
  162.  
  163.                     await client.send_typing(client.get_channel(channel_id))
  164.                     await asyncio.sleep(.3)
  165.                     await client.send_message(client.get_channel(channel_id), msg_error)
  166.  
  167.                     sort = random.choice(('new', 'hot'))
  168.                     method = getattr(reddit.subreddit(subreddit), sort)
  169.                     now = time()
  170.  
  171.                     last = CACHE[sub][sort + '_time']
  172.  
  173.                     if CACHE[subreddit][sort] is None or last is None or (last + cache_time) < now:
  174.                         pool = CACHE[subreddit][sort] = tuple(method(limit=250))
  175.                         CACHE[subreddit][sort + '_time'] = now
  176.                     else:
  177.                         pool = CACHE[subreddit][sort]
  178.  
  179.                     random_post = random.choice(pool)
  180.  
  181.                     await client.purge_from(client.get_channel(channel_id), limit=100, check=lambda m: m.content == msg_error)
  182.  
  183.             msg = random_post.url
  184.             await client.send_typing(client.get_channel(channel_id))
  185.             await asyncio.sleep(.3)
  186.             await client.send_message(client.get_channel(channel_id), msg)
  187.  
  188.     if message.content.startswith('!xbox'):
  189.         gamertag = message.content.strip('!xbox ')
  190.  
  191.         gamertag_url = 'https://www.xboxgamertag.com/search/' + gamertag
  192.         gamertag_url_request = requests.get(gamertag_url)
  193.         soup = BeautifulSoup(gamertag_url_request.text, 'html.parser')
  194.  
  195.         if 'An error occured...' in gamertag_url_request.text:
  196.             msg = 'That is not a valid Gamertag.'
  197.             await client.send_typing(client.get_channel(channel_id))
  198.             await asyncio.sleep(.3)
  199.             await client.send_message(client.get_channel(channel_id), msg)
  200.  
  201.         if 'An error occured...' not in gamertag_url_request.text:
  202.  
  203.             status = soup.find('p', attrs={'class' : 'topc'}).get_text(strip=True)
  204.  
  205.             if ' playing Xbox Live' in status:
  206.                 status = status.replace(' playing Xbox Live', '')
  207.             if 'Online now' in status:
  208.                 status = 'Online'
  209.             if 'over 30 days ago' in status:
  210.                 status = 'Offline for over 1 month.'
  211.             if 'Last seen' in status:
  212.                 status = 'Offline **//** ' + status[:-9]
  213.  
  214.             gamerscore = soup.findAll(attrs={"name":"description"})
  215.             gamerscore = gamerscore[0]['content']
  216.             gamerscore = re.sub("\D", "", gamerscore)
  217.             gamerscore = format(int(gamerscore), ',d')
  218.  
  219.             msg = (
  220.                 "**%s's** Status: **%s**\n"
  221.                 "**%s's** Gamerscore: **%s**"
  222.                 ) % (
  223.                 gamertag.title(), status.title(), gamertag.title(), gamerscore
  224.                 )
  225.  
  226.             await client.send_typing(client.get_channel(channel_id))
  227.             await asyncio.sleep(.3)
  228.             await client.send_message(client.get_channel(channel_id), msg)
  229.  
  230.     if message.content.startswith('!countdown'):
  231.  
  232.         def dateDiffInSeconds(date1, date2):
  233.           timedelta = date2 - date1
  234.           return timedelta.days * 24 * 3600 + timedelta.seconds
  235.  
  236.         def daysHoursMinutesSecondsFromSeconds(seconds):
  237.             minutes, seconds = divmod(seconds, 60)
  238.             hours, minutes = divmod(minutes, 60)
  239.             days, hours = divmod(hours, 24)
  240.             return (days, hours, minutes, seconds)
  241.  
  242.         injustice2 = datetime.strptime('2017-05-15 23:01:00', '%Y-%m-%d %H:%M:%S')
  243.         fridaythe13th = datetime.strptime('2017-05-25 23:01:00', '%Y-%m-%d %H:%M:%S')
  244.         shadowofwar = datetime.strptime('2017-08-21 23:01:00', '%Y-%m-%d %H:%M:%S')
  245.  
  246.         now = datetime.now()
  247.  
  248.         msg = (
  249.         '**%d** days, **%d** hours, **%d** minutes, and **%d** seconds until the release of **Injustice 2**.\n'
  250.         '**%d** days, **%d** hours, **%d** minutes, and **%d** seconds until the release of **Friday the 13th: The Game**.\n'
  251.         '**%d** days, **%d** hours, **%d** minutes, and **%d** seconds until the release of **Middle-earth: Shadow of War**.'
  252.         ) % (
  253.         daysHoursMinutesSecondsFromSeconds(dateDiffInSeconds(now, injustice2)) +
  254.         daysHoursMinutesSecondsFromSeconds(dateDiffInSeconds(now, fridaythe13th)) +
  255.         daysHoursMinutesSecondsFromSeconds(dateDiffInSeconds(now, shadowofwar))
  256.         )
  257.  
  258.         await client.send_typing(client.get_channel(channel_id))
  259.         await asyncio.sleep(.2)
  260.         await client.send_message(client.get_channel(channel_id), msg)
  261.  
  262.     if message.content.startswith('!launch') and message.author.name == owner:
  263.         process = message.content.strip('!launch ')
  264.         msg = "Starting **%s**." % (process)
  265.  
  266.         print('%s: %s' %(message.author.name, message.content))
  267.         print ('Status: Launching %s' % (process))
  268.  
  269.         await client.send_typing(client.get_channel(channel_id))
  270.         await asyncio.sleep(.3)
  271.         await client.send_message(client.get_channel(channel_id), msg)
  272.  
  273.         subprocess.Popen(process, creationflags=subprocess.CREATE_NEW_CONSOLE)
  274.  
  275.     if message.content.startswith('!purge') and message.author.name == owner:
  276.         text_channel = message.content.strip('!purge ')
  277.  
  278.         if text_channel == 'memes':
  279.             text_channel_id = memes
  280.         if text_channel == 'megalinks':
  281.             text_channel_id = megalinks
  282.         if text_channel == 'bots':
  283.             text_channel_id = bots
  284.  
  285.         await client.purge_from(client.get_channel(text_channel_id), limit=100, check=None)
  286.         await client.send_typing(client.get_channel(channel_id))
  287.         await asyncio.sleep(.3)
  288.  
  289.         if text_channel_id == memes:
  290.             await client.send_message(client.get_channel(channel_id), 'Successfully purged **#memes**. %s' % (ok_emoji))
  291.             print('%s: %s' %(message.author.name, message.content))
  292.             print ('Status: Cleaned contents of #memes.')
  293.  
  294.         if text_channel_id == megalinks:
  295.             await client.send_message(client.get_channel(channel_id), 'Successfully purged **#megalinks**. %s' % (ok_emoji))
  296.             print('%s: %s' %(message.author.name, message.content))
  297.             print ('Status: Cleaned contents of #megalinks.')
  298.  
  299.         if text_channel_id == bots:
  300.             await client.send_message(client.get_channel(channel_id), 'Successfully purged **#bots**. %s' % (ok_emoji))
  301.             print('%s: %s' %(message.author.name, message.content))
  302.             print ('Status: Cleaned contents of #bots.')
  303.  
  304.     if message.content.startswith('!fix'):
  305.         msg = "Restarting: **%s** and **%s**. %s" % (bot_name, slave_bot_name, peace_emoji)
  306.  
  307.         await client.purge_from(client.get_channel(channel_id), limit=100, check=lambda m: m.content == '!fix')
  308.  
  309.         await client.send_typing(client.get_channel(channel_id))
  310.         await client.send_message(client.get_channel(channel_id), msg)
  311.  
  312.         print('%s: %s' %(message.author.name, message.content))
  313.         print ('\nStatus: Restarting %s and %s.' %(bot_name, slave_bot_name))
  314.  
  315.         subprocess.Popen(bot_name + '.bat', creationflags=subprocess.CREATE_NEW_CONSOLE)
  316.         subprocess.Popen(slave_bot_name + '.bat', creationflags=subprocess.CREATE_NEW_CONSOLE)
  317.  
  318.     else:
  319.         if message.author.name != "null":
  320.  
  321.             if message.channel.id != bots or message.content.startswith('!') or message.content.startswith('http'):
  322.                 return
  323.  
  324.             if message.author.name == "Bango-Bot" or message.author.name == "Bingo-Bot" or message.author.name == "Bungo-Bot":
  325.                 return
  326.  
  327.             else:
  328.                 confusing_url = 'http://my.confusing.life/'
  329.                 confusing_url_request = requests.get(confusing_url)
  330.                 soup = BeautifulSoup(confusing_url_request.text, 'html.parser')
  331.                 confusing_quote = soup.find("span").get_text(strip=True)
  332.  
  333.                 msg = confusing_quote
  334.  
  335.                 await client.send_typing(client.get_channel(channel_id))
  336.                 await asyncio.sleep(.3)
  337.                 await client.send_message(client.get_channel(channel_id), msg)
  338.  
  339.                 print('%s: %s' %(message.author.name, message.content))
  340.                 print('%s: %s' %(bot_name, msg))
  341.  
  342. # on connect events
  343. @client.event
  344. async def on_ready():
  345.     print ("Status: Connected!")
  346.     print('------')
  347.     print('Bot: ' + client.user.name)
  348.     print('Client ID: ' + client.user.id)
  349.     print('------')
  350.  
  351.     default_presence = 'Bingo-Bot v%s' % (bot_version)
  352.     print ('Current presence: %s' %(default_presence))
  353.     await client.change_presence(game=discord.Game(name=default_presence))
  354.  
  355.     await client.purge_from(client.get_channel(channel_id), limit=100, check=None)
  356.  
  357.     await client.send_typing(client.get_channel(channel_id))
  358.  
  359.     if WindowExists("Bungo-Bot"):
  360.         msg = (
  361.         '**%s** Status: **Online** %s\n'
  362.         '**%s** Status: **Online** %s'
  363.         ) % (
  364.         bot_name, ok_emoji, slave_bot_name, ok_emoji
  365.         )
  366.         await client.send_message(client.get_channel(channel_id), msg)
  367.     else:
  368.         msg = (
  369.         '**%s** Status: **Online** %s\n'
  370.         '**%s** Status: **Offline** %s'
  371.         ) % (
  372.         bot_name, ok_emoji, slave_bot_name, peace_emoji
  373.         )
  374.         await client.send_message(client.get_channel(channel_id), msg)
  375.  
  376. # sign in
  377. client.run(bot_token)
Add Comment
Please, Sign In to add comment