Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #SAVE AS: bot_security.py
- #########################################################################################################################################
- ###############################################################MODULE IMPORT#############################################################
- #########################################################################################################################################
- import json
- from datetime import datetime
- import sys
- import os
- import base64
- import mimetypes
- import time
- import random
- import io
- import re
- import traceback
- import warnings
- from skimage.measure import compare_ssim as ssim #pip install scikit-image
- import cv2 #pip install opencv-python
- import discord #pip install -U discord.py[voice]
- import asyncio #pip install -U discord.py[voice]
- import aiohttp #pip install -U discord.py[voice]
- import numpy as np #pip install opencv-python
- from discord.ext import commands #pip install -U discord.py[voice]
- from googleapiclient.discovery import build #pip install --upgrade google-api-python-client
- from apiclient.errors import HttpError #pip install --upgrade google-api-python-client
- from oauth2client.tools import argparser #pip install --upgrade oauth2client
- try:
- from PIL import Image #pip install PIL
- except:
- import Image #pip install Image
- client = discord.Client()
- 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/?(?!@)))"""
- async def OverflowMessage(message,channel):
- try:
- cummsg = ""
- overflownewline = False
- for i in [x + "\n" for x in message.split("\n")]:
- if len(i) > 1800:
- overflownewline = True
- if cummsg != "":
- await client.send_message(channel, cummsg)
- message = message.replace(cummsg,"")
- break
- elif len(cummsg+i) > 1800:
- await client.send_message(channel, cummsg)
- message = message.replace(cummsg,"")
- cummsg = i
- else:
- cummsg += i
- if overflownewline:
- for i in message:
- if len(cummsg+i) > 1800:
- await client.send_message(channel, cummsg)
- message = message.replace(cummsg,"")
- cummsg = i
- else:
- cummsg += i
- if cummsg != "":
- await client.send_message(channel, cummsg)
- cummsg = ""
- else:
- await client.send_message(channel, cummsg)
- return True
- except Exception as e:
- return str(e)
- async def TryDelete(message):
- try:
- client.delete_message(message)
- return True
- except:
- print("Failed to delete")
- print(traceback.format_exc())
- return False
- async def IsStaff(message,author=None):
- isstaff = False
- if author == None:
- author = bot.server.get_member(message.author.id)
- else:
- author = bot.server.get_member(author.id)
- staffranks = ["Admin","Legislator","Moderator","Moderators","Gate Keeper"]
- playerroles = author.roles
- for i in playerroles:
- if i.name in staffranks:
- return True
- return False
- ##############################################################################################################
- ##############################################################################################################
- ##########################################START OF !FUNCTIONS#################################################
- ##############################################################################################################
- async def InviteScan(member):
- invused = None
- newinvites = []
- invfound = True
- for inv in await client.invites_from(bot.server):
- newinvites.append([inv.code,inv.uses])
- for oldinv in bot.invites:
- if invused != None or not(invfound):
- break
- for newinv in newinvites:
- if oldinv[0] == newinv[0]: #If we found the inv (if oldcode == newcode)
- if oldinv[1] < newinv[1]: #If useages changed
- invused = oldinv[0] #Gotcha faggot
- break
- #elif newinv == newinvites[-1]: #If we didn't find the invite
- # invfound = False #Wait what hang on somethings fucky here
- # invused = oldinv[0] #The invite missing must be the one used probably expired or some bullshit so in that case gotcha faggot
- # break
- if invused == None:
- retstr = "Unable to find invite used by <@"+member.id+">."
- else:
- for inv in await client.invites_from(bot.server):
- if inv.code == invused:
- invused = inv
- retstr = "__Invite used by <@"+member.id+">__\n"
- if invused.code == "6rrzdTQ":
- retstr += "**Invite Notes: Invite used in Love and Support discord**\n"
- elif invused.code == "RSFSb4u":
- return
- retstr += "**Invite Notes: Primary JY invite, used on reddit and ddlcmods.fun**\n"
- elif invused.code == "jCMf24a":
- retstr += "**Invite Notes: Twitter invite used at https://twitter.com/JustYuriDevTeam**\n"
- retstr+="Inviter: <@"+invused.inviter.id+">\nUrl Used: "+invused.url
- if not(invfound):
- retstr += "\n(Invite now expired/removed)"
- await client.send_message(bot.botlogchannel, retstr)
- ##########BOT ON MESSAGE##############
- @client.event
- async def on_member_join(member):
- if not(member.bot):
- await InviteScan(member)
- @client.event
- async def on_message(message):
- if not bot.ready: #Race condition
- return
- #Skip entirely if its in the ignorelist
- ##########BOT ERROR CATCHING##########
- @client.event
- async def on_error(event,args="",kwargs=""):
- print("BOT EXCEPTION:")
- print(traceback.format_exc())
- try:
- with open("errors_sec.txt", "a") as f:
- f.write("\n\n"+traceback.format_exc()+"\n\n")
- except:
- try:
- print("ERROR: NO ERRORS FILE, WRITING")
- with open("errors_sec.txt","w") as f:
- f.write("\n\n"+traceback.format_exc()+"\n\n")
- except:
- print("ERROR: NO FILESYSTEM ACCESS")
- ##############BOT INIT################
- @client.event
- async def on_ready():
- print('BOT_NAME: ' + client.user.name)
- print('BOT_ID: ' + client.user.id)
- print('\n\n--VAR_ASSIGN--')
- try:
- bot.prefix = bot.config.split("prefix=")[1].split("\n")[0]
- print("BOT_PREFIX: "+bot.prefix)
- bot.ignorelist = bot.config.split("ignorelist=")[1].split("\n")[0]
- print("BOT_IGNORELIST: "+bot.ignorelist)
- bot.server = bot.config.split("discord_server=")[1].split("\n")[0]
- print("SERVER_ID: "+bot.server)
- bot.pendingchannel = bot.config.split("pendingchannel=")[1].split("\n")[0]
- print("PENDING_CHANNEL_ID: "+bot.pendingchannel)
- bot.botlogchannel = bot.config.split("botlogchannel=")[1].split("\n")[0]
- print("BOT_LOG_CHANNEL_ID "+bot.botlogchannel)
- except:
- print("FAILURE TO READ CONFIG")
- print(traceback.format_exc())
- raise Exception('Incorrect config.')
- try:
- print("\n\n--DYNAMIC_VAR_INIT--")
- bot.server = client.get_server(bot.server)
- print("SERVER_NAME: "+bot.server.name)
- bot.pendingchannel = bot.server.get_channel(bot.pendingchannel)
- print("PENDING_CHANNEL_NAME: "+bot.pendingchannel.name)
- bot.botlogchannel = bot.server.get_channel(bot.botlogchannel)
- print("BOT_LOG_CHANNEL_NAME: "+bot.botlogchannel.name)
- bot.invites = []
- for inv in await client.invites_from(bot.server):
- bot.invites.append([inv.code,inv.uses])
- bot.ready = True
- print("\n\n--READY--")
- #await DoPurgeReminder()
- except:
- print("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
- client.close()
- client.logout()
- raise Exception("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
- #############################END OF INITIALIZATION#############################
- class BotVars:
- pass
- if __name__ == '__main__':
- try:
- bot = BotVars()
- bot.ready = False
- #########################################################################################################################################
- ###############################################################VARIABLE INIT#############################################################
- #########################################################################################################################################
- bot.token = None
- print("--TOKEN_INIT--")
- try:
- with open("config", "r") as f:
- bot.config = f.read()
- bot.token = bot.config.split("token=")[1].split("\n")[0]
- print("DISCORD TOKEN: " + bot.token[:int(len(bot.token)/2)]+str("*"*(int(len(bot.token)/2)-4))+bot.token[:4])
- except:
- print("FAILURE TO READ CONFIG")
- print(traceback.format_exc())
- raise Exception('Incorrect config.')
- print("\n\n--LOGIN--")
- client.run(bot.token)
- except Exception as e:
- botexception = traceback.format_exc()
- print(traceback.format_exc())
- print("EXCEPTION '" + str(e) + "'")
- try:
- client.close()
- except:
- pass
- try:
- client.logout()
- except:
- pass
- with open("exception.txt", "w") as inputfile:
- if "logout" in str(botexception):
- inputfile.write("logout")
- else:
- inputfile.write(str(botexception))
- print("--FAILURE--")
- time.sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement