Advertisement
CreedWN

bot_security.py

Jun 29th, 2018
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.51 KB | None | 0 0
  1. #SAVE AS: bot_security.py
  2. #########################################################################################################################################
  3. ###############################################################MODULE IMPORT#############################################################
  4. #########################################################################################################################################
  5. import json
  6. from datetime import datetime
  7. import sys
  8. import os
  9. import base64
  10. import mimetypes
  11. import time
  12. import random
  13. import io
  14. import re
  15. import traceback
  16. import warnings
  17.  
  18. from skimage.measure import compare_ssim as ssim #pip install scikit-image
  19. import cv2 #pip install opencv-python
  20. import discord #pip install -U discord.py[voice]
  21. import asyncio #pip install -U discord.py[voice]
  22. import aiohttp #pip install -U discord.py[voice]
  23. import numpy as np #pip install opencv-python
  24. from discord.ext import commands #pip install -U discord.py[voice]
  25. from googleapiclient.discovery import build #pip install --upgrade google-api-python-client
  26. from apiclient.errors import HttpError #pip install --upgrade google-api-python-client
  27. from oauth2client.tools import argparser #pip install --upgrade oauth2client
  28.  
  29. try:
  30.     from PIL import Image #pip install PIL
  31. except:
  32.     import Image #pip install Image
  33.    
  34. client = discord.Client()
  35. URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"""
  36. async def OverflowMessage(message,channel):
  37.     try:
  38.         cummsg = ""
  39.         overflownewline = False
  40.         for i in [x + "\n" for x in message.split("\n")]:
  41.             if len(i) > 1800:
  42.                 overflownewline = True
  43.                 if cummsg != "":
  44.                     await client.send_message(channel, cummsg)
  45.                     message = message.replace(cummsg,"")
  46.                 break
  47.             elif len(cummsg+i) > 1800:
  48.                 await client.send_message(channel, cummsg)
  49.                 message = message.replace(cummsg,"")
  50.                 cummsg = i
  51.             else:
  52.                 cummsg += i
  53.         if overflownewline:
  54.             for i in message:
  55.                 if len(cummsg+i) > 1800:
  56.                     await client.send_message(channel, cummsg)
  57.                     message = message.replace(cummsg,"")
  58.                     cummsg = i
  59.                 else:
  60.                     cummsg += i
  61.             if cummsg != "":
  62.                 await client.send_message(channel, cummsg)
  63.                 cummsg = ""
  64.         else:
  65.             await client.send_message(channel, cummsg)
  66.         return True
  67.     except Exception as e:
  68.         return str(e)
  69. async def TryDelete(message):
  70.     try:
  71.         client.delete_message(message)
  72.         return True
  73.     except:
  74.         print("Failed to delete")
  75.         print(traceback.format_exc())
  76.         return False
  77. async def IsStaff(message,author=None):
  78.     isstaff = False
  79.     if author == None:
  80.         author = bot.server.get_member(message.author.id)
  81.     else:
  82.         author = bot.server.get_member(author.id)
  83.     staffranks = ["Admin","Legislator","Moderator","Moderators","Gate Keeper"]
  84.     playerroles = author.roles
  85.     for i in playerroles:
  86.         if i.name in staffranks:
  87.             return True
  88.     return False
  89. ##############################################################################################################
  90. ##############################################################################################################
  91. ##########################################START OF !FUNCTIONS#################################################
  92. ##############################################################################################################
  93. async def InviteScan(member):
  94.     invused = None
  95.     newinvites = []
  96.     invfound = True
  97.     for inv in await client.invites_from(bot.server):      
  98.         newinvites.append([inv.code,inv.uses])
  99.     for oldinv in bot.invites:
  100.         if invused != None or not(invfound):
  101.             break
  102.         for newinv in newinvites:
  103.             if oldinv[0] == newinv[0]: #If we found the inv (if oldcode == newcode)
  104.                 if oldinv[1] < newinv[1]: #If useages changed
  105.                     invused = oldinv[0] #Gotcha faggot
  106.                     break
  107.             #elif newinv == newinvites[-1]: #If we didn't find the invite
  108.             #   invfound = False #Wait what hang on somethings fucky here
  109.             #   invused = oldinv[0] #The invite missing must be the one used probably expired or some bullshit so in that case gotcha faggot
  110.             #   break
  111.     if invused == None:
  112.         retstr = "Unable to find invite used by <@"+member.id+">."
  113.     else:
  114.         for inv in await client.invites_from(bot.server):
  115.             if inv.code == invused:
  116.                 invused = inv
  117.         retstr = "__Invite used by <@"+member.id+">__\n"
  118.         if invused.code == "6rrzdTQ":
  119.             retstr += "**Invite Notes: Invite used in Love and Support discord**\n"
  120.         elif invused.code == "RSFSb4u":
  121.             return
  122.             retstr += "**Invite Notes: Primary JY invite, used on reddit and ddlcmods.fun**\n"
  123.         elif invused.code == "jCMf24a":
  124.             retstr += "**Invite Notes: Twitter invite used at https://twitter.com/JustYuriDevTeam**\n"
  125.            
  126.         retstr+="Inviter: <@"+invused.inviter.id+">\nUrl Used: "+invused.url
  127.     if not(invfound):
  128.         retstr += "\n(Invite now expired/removed)"
  129.     await client.send_message(bot.botlogchannel, retstr)
  130. ##########BOT ON MESSAGE##############
  131. @client.event
  132. async def on_member_join(member):
  133.     if not(member.bot):
  134.         await InviteScan(member)
  135. @client.event
  136. async def on_message(message):
  137.     if not bot.ready: #Race condition
  138.         return
  139.     #Skip entirely if its in the ignorelist
  140.    
  141. ##########BOT ERROR CATCHING##########
  142. @client.event
  143. async def on_error(event,args="",kwargs=""):
  144.     print("BOT EXCEPTION:")
  145.     print(traceback.format_exc())
  146.     try:
  147.         with open("errors_sec.txt", "a") as f:
  148.             f.write("\n\n"+traceback.format_exc()+"\n\n")
  149.     except:
  150.         try:
  151.             print("ERROR: NO ERRORS FILE, WRITING")
  152.             with open("errors_sec.txt","w") as f:
  153.                 f.write("\n\n"+traceback.format_exc()+"\n\n")
  154.         except:
  155.             print("ERROR: NO FILESYSTEM ACCESS")
  156. ##############BOT INIT################
  157. @client.event
  158. async def on_ready():
  159.     print('BOT_NAME: ' + client.user.name)
  160.     print('BOT_ID: ' + client.user.id)
  161.     print('\n\n--VAR_ASSIGN--')
  162.     try:
  163.         bot.prefix = bot.config.split("prefix=")[1].split("\n")[0]
  164.         print("BOT_PREFIX: "+bot.prefix)
  165.         bot.ignorelist = bot.config.split("ignorelist=")[1].split("\n")[0]
  166.         print("BOT_IGNORELIST: "+bot.ignorelist)
  167.        
  168.         bot.server = bot.config.split("discord_server=")[1].split("\n")[0]
  169.         print("SERVER_ID: "+bot.server)
  170.         bot.pendingchannel = bot.config.split("pendingchannel=")[1].split("\n")[0]
  171.         print("PENDING_CHANNEL_ID: "+bot.pendingchannel)
  172.        
  173.         bot.botlogchannel = bot.config.split("botlogchannel=")[1].split("\n")[0]
  174.         print("BOT_LOG_CHANNEL_ID "+bot.botlogchannel)
  175.        
  176.     except:
  177.         print("FAILURE TO READ CONFIG")
  178.         print(traceback.format_exc())
  179.         raise Exception('Incorrect config.')
  180.     try:
  181.         print("\n\n--DYNAMIC_VAR_INIT--")
  182.         bot.server = client.get_server(bot.server)
  183.         print("SERVER_NAME: "+bot.server.name)
  184.        
  185.         bot.pendingchannel = bot.server.get_channel(bot.pendingchannel)
  186.         print("PENDING_CHANNEL_NAME: "+bot.pendingchannel.name)
  187.         bot.botlogchannel = bot.server.get_channel(bot.botlogchannel)
  188.         print("BOT_LOG_CHANNEL_NAME: "+bot.botlogchannel.name)
  189.         bot.invites = []
  190.         for inv in await client.invites_from(bot.server):      
  191.             bot.invites.append([inv.code,inv.uses])
  192.         bot.ready = True
  193.         print("\n\n--READY--")
  194.         #await DoPurgeReminder()
  195.     except:
  196.         print("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
  197.         client.close()
  198.         client.logout()
  199.         raise Exception("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
  200.    
  201. #############################END OF INITIALIZATION#############################
  202.    
  203. class BotVars:
  204.     pass
  205. if __name__ == '__main__':
  206.     try:
  207.         bot = BotVars()
  208.         bot.ready = False
  209.         #########################################################################################################################################
  210.         ###############################################################VARIABLE INIT#############################################################
  211.         #########################################################################################################################################
  212.         bot.token = None
  213.         print("--TOKEN_INIT--")
  214.         try:
  215.             with open("config", "r") as f:
  216.                 bot.config = f.read()
  217.             bot.token = bot.config.split("token=")[1].split("\n")[0]
  218.             print("DISCORD TOKEN: " + bot.token[:int(len(bot.token)/2)]+str("*"*(int(len(bot.token)/2)-4))+bot.token[:4])
  219.         except:
  220.             print("FAILURE TO READ CONFIG")
  221.             print(traceback.format_exc())
  222.             raise Exception('Incorrect config.')
  223.         print("\n\n--LOGIN--")
  224.         client.run(bot.token)
  225.     except Exception as e:
  226.         botexception = traceback.format_exc()
  227.         print(traceback.format_exc())
  228.         print("EXCEPTION '" + str(e) + "'")
  229.         try:
  230.             client.close()
  231.         except:
  232.             pass
  233.         try:
  234.             client.logout()
  235.         except:
  236.             pass
  237.         with open("exception.txt", "w") as inputfile:
  238.             if "logout" in str(botexception):
  239.                 inputfile.write("logout")
  240.             else:
  241.                 inputfile.write(str(botexception))
  242.         print("--FAILURE--")
  243.         time.sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement