CreedWN

bot.py

Jun 29th, 2018
1,029
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 58.36 KB | None | 0 0
  1. #SAVE AS: bot.py
  2. #This codes a messy unoptimized piece of shit
  3. #########################################################################################################################################
  4. ###############################################################MODULE IMPORT#############################################################
  5. #########################################################################################################################################
  6. import json
  7. from datetime import datetime
  8. import sys
  9. import os
  10. import base64
  11. import mimetypes
  12. import time
  13. import random
  14. import io
  15. import re
  16. import traceback
  17. import warnings
  18. import math
  19.  
  20. from skimage.measure import compare_ssim as ssim #pip install scikit-image
  21. import cv2 #pip install opencv-python
  22. import discord #pip install -U discord.py[voice]
  23. import asyncio #pip install -U discord.py[voice]
  24. import aiohttp #pip install -U discord.py[voice]
  25. import numpy as np #pip install opencv-python
  26. from discord.ext import commands #pip install -U discord.py[voice]
  27. from googleapiclient.discovery import build #pip install --upgrade google-api-python-client
  28. from apiclient.errors import HttpError #pip install --upgrade google-api-python-client
  29. from oauth2client.tools import argparser #pip install --upgrade oauth2client
  30. try:
  31.     from PIL import Image #pip install PIL
  32. except:
  33.     import Image #pip install Image
  34.    
  35. client = discord.Client()
  36. 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/?(?!@)))"""
  37. ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(math.floor(n/10)%10!=1)*(n%10<4)*n%10::4])
  38. async def OverflowMessage(message,channel):
  39.     try:
  40.         cummsg = ""
  41.         overflownewline = False
  42.         for i in [x + "\n" for x in message.split("\n")]:
  43.             if len(i) > 1800:
  44.                 overflownewline = True
  45.                 if cummsg != "":
  46.                     await client.send_message(channel, cummsg)
  47.                     message = message.replace(cummsg,"")
  48.                 break
  49.             elif len(cummsg+i) > 1800:
  50.                 await client.send_message(channel, cummsg)
  51.                 message = message.replace(cummsg,"")
  52.                 cummsg = i
  53.             else:
  54.                 cummsg += i
  55.         if overflownewline:
  56.             for i in message:
  57.                 if len(cummsg+i) > 1800:
  58.                     await client.send_message(channel, cummsg)
  59.                     message = message.replace(cummsg,"")
  60.                     cummsg = i
  61.                 else:
  62.                     cummsg += i
  63.             if cummsg != "":
  64.                 await client.send_message(channel, cummsg)
  65.                 cummsg = ""
  66.         else:
  67.             await client.send_message(channel, cummsg)
  68.         return True
  69.     except Exception as e:
  70.         return str(e)
  71. async def TryDelete(message):
  72.     try:
  73.         client.delete_message(message)
  74.         return True
  75.     except:
  76.         print("Failed to delete")
  77.         print(traceback.format_exc())
  78.         return False
  79. async def IsStaff(message,author=None):
  80.     isstaff = False
  81.     if author == None:
  82.         author = bot.server.get_member(message.author.id)
  83.     else:
  84.         author = bot.server.get_member(author.id)
  85.     if author == None:
  86.         return False
  87.     staffranks = ["Admin","Legislator","Moderator","Moderators","Gate Keeper"]
  88.     playerroles = author.roles
  89.     for i in playerroles:
  90.         if i.name in staffranks:
  91.             return True
  92.     return False
  93. ##############################################################################################################
  94. ##############################################################################################################
  95. ##########################################START OF !FUNCTIONS#################################################
  96. ##############################################################################################################
  97.  
  98. async def DoPingReminder():
  99.     async for msg in client.logs_from(bot.pendingchannel, limit=100):
  100.         if msg.author == client.user:
  101.             await client.delete_message(msg)
  102.     randommessages = ["Hey, the rest of the server isn't here! You should probably read the <#414633099775967233> and after doing so paste the passcode.", "Whoa there, hit the brakes, what are you still doing here? Check <#414633099775967233> and message the passcode here to access the rest of the server!","Daily reminder that this is not in fact, the main chat. You should probably verify yourself by checking <#414633099775967233> and putting the passcode here.", "Psst. Hey. I hear if you enter the passcode found in <#414633099775967233> in this chat you can access the rest of the server. You didn't hear it from me though.", "You and #general. I ship it. Just enter the passcode found in <#414633099775967233> and you'll be on your way! I believe in you!"]
  103.     await client.send_message(bot.pendingchannel,"<@&400824614324011008> " + random.choice(randommessages))
  104.     bot.lastpendingreminder = datetime.utcnow()
  105.     print("Sent Ping reminder at "+bot.lastpendingreminder.strftime(" %Y-%b-%d_%Hh%Mm%Ss"))
  106.  
  107. async def DoPurgeReminder():
  108.     print("PERFORMING REMINDER")
  109.     async for msg in client.logs_from(bot.pendingchannel, limit=100):
  110.         if msg.author == client.user:
  111.             await client.delete_message(msg)
  112.     randommessages= ["It's that time again! Purge all the people that have been in this chat for over 1 week.", "New weeks rolled around. Purging time. Remove all the people in this chat over 7 days old.", "It's about to be a hit James DeMonaco film up in here because it's purging time. Remove all users who are over a week old.","I really don't understand how people can chill in here for an entire week, but you don't have to understand. Weekly purge time.", "Weekly purge! But not the cool kind though. Just remove people who have been in this chat for over a week."]
  113.     await client.send_message(bot.pendingchannel,"<@&417941723868823584> <@&389552626137563148> " + random.choice(randommessages))
  114.     #await client.send_message(bot.pendingchannel,"<@& --DEBUG MODE-- AUTOKICK MODULE")
  115.     bot.lastpendingreminder = datetime.utcnow()
  116. async def DoPurgeReminder_GetMembers():
  117.     try:
  118.         if server.large:
  119.             await client.request_offline_members(bot.server)
  120.     except:
  121.         pass
  122.     pendingmembers = []
  123.     for i in bot.server.members:
  124.         if (datetime.utcnow()-i.joined_at).days >= 7:
  125.             for x in i.roles:
  126.                 if x.name == "Pending":
  127.                     pendingmembers.append(i)
  128.                     break
  129.     return pendingmembers
  130. async def DoPurgeReminder_MemberList():
  131.     print("SENDING KICKED USER LIST")
  132.     pendingmembers = await DoPurgeReminder_GetMembers()
  133.     text = ""
  134.     text += "__**Here's a list of people that have been in this chat for over a week:**__\n"
  135.     for i in pendingmembers:
  136.         text += (i.display_name + " ("+i.name+"#"+i.discriminator+") <"+i.id+">\n").encode("ascii","replace").decode("ascii","replace")
  137.     om = await OverflowMessage(text,bot.server.owner)
  138.     if not(om==True):
  139.         try:
  140.             await client.send_message(bot.server.owner, "**Error in sending member list.**")
  141.         except:
  142.             print("Error in sending member list")
  143. async def DoPurgeReminder_DirectMessage():
  144.     #await client.send_message(bot.pendingchannel, "**Direct messaging all week-old unscreened members.**")
  145.     pendingmembers = await DoPurgeReminder_GetMembers()
  146.     failedtosendlist = []
  147.     print("DIRECT MESSAGING USERS ABOUT KICK")
  148.     for i in pendingmembers:
  149.         try:
  150.             await client.send_message(i, "You are being removed from the Just Yuri discord server due to inactivity and loitering in the screening channel for over a week. If you wish to rejoin, please ensure you finish the screening process.")
  151.             print("Success!")
  152.         except Exception as e:
  153.             toofast = False
  154.             interval = 20
  155.             if "opening direct messages" in str(e).lower() and "fast" in str(e).lower():
  156.                 toofast = True
  157.             else:
  158.                 print("Failed, "+str(e))
  159.                 failedtosendlist.append(i)
  160.             if toofast:
  161.                 while toofast:
  162.                     await asyncio.sleep(interval)
  163.                     try:
  164.                         await client.send_message(i, "You are being removed from the Just Yuri discord server due to inactivity and loitering in the screening channel for over a week. If you wish to rejoin, please ensure you finish the screening process.")
  165.                         print("Success!")
  166.                         toofast = False
  167.                     except Exception as e2:
  168.                         if "opening direct messages" in str(e2).lower() and "fast" in str(e2).lower():
  169.                             interval *= 2
  170.                             print("Direct messages too fast, delaying for "+str(interval)+" seconds")
  171.     txt = ""
  172.     txt += "Directly messaged "+str(len(pendingmembers)-len(failedtosendlist))+"/"+str(len(pendingmembers))+" about their kick. The ones that have failed likely have ``\"Allow direct messages from server members.\"`` disabled in their Privacy settings.\nHere are the users failed to message directly:```\n"
  173.     for i in failedtosendlist:
  174.         txt+=i.display_name + " ("+i.name+"#"+i.discriminator+") <"+i.id+">\n"
  175.     txt +="```"
  176.     om = await OverflowMessage(txt,bot.pendingchannel)
  177.     if not(om==True):
  178.         await client.send_message(bot.pendingchannel, "**Error in sending failed member DM list.**")
  179.    
  180. async def DoPurgeReminder_AutoKick():
  181.     print("AUTO KICK BEGUN")
  182.     if bot.server.get_member(client.user.id).server_permissions.kick_members:
  183.         #tmp_kickmsg = await client.send_message(bot.pendingchannel, "Kicking all week-old members in <#422197075531530260>.")
  184.         print("Begun")
  185.         pendingmembers = await DoPurgeReminder_GetMembers()
  186.         pendingmemberslen = str(len(pendingmembers))
  187.         for i in pendingmembers:
  188.             try:
  189.                 await client.kick(i)
  190.                 print("Kicked")
  191.             except:
  192.                 await client.send_message(bot.pendingchannel,"CRITICAL ERROR: Kick permissions granted to bot, but failed to kick <@"+i.id+">. Are they still in the server?")
  193.         #await client.edit_message(tmp_kickmsg, pendingmemberslen+" inactive members in <#422197075531530260> have been kicked.")
  194.     else:
  195.         await client.send_message(bot.pendingchannel, "``Error in pending auto-kick: Permission \"Kick Members\" not granted to bot.``")
  196.    
  197. async def PingReminder():
  198.     if bot.lastpendingreminder == None:
  199.         bot.lastpendingreminder = -1
  200.         async for msg in client.logs_from(bot.pendingchannel, limit=999):
  201.             if msg.author == client.user and msg.content.startswith("<@&"):
  202.                 bot.lastpendingreminder = msg.timestamp
  203.                 break
  204.         if bot.lastpendingreminder == -1:
  205.             await DoPingReminder()
  206.     elif (datetime.utcnow()-bot.lastpendingreminder).days >= 1:
  207.         await DoPingReminder()
  208.         #Also do some other daily stuff
  209.         await DoDaily()
  210.         #if datetime.utcnow().weekday() != 0:
  211.         #   await DoPingReminder()
  212.         #else:
  213.         #   await DoPurgeReminder()
  214.         #   await DoPurgeReminder_MemberList()
  215.         #   await DoPurgeReminder_DirectMessage()
  216.         #   await DoPurgeReminder_AutoKick()
  217. async def DoYuriBotSwitch():
  218.     tmp = await client.send_message(bot.server.get_channel("389560237889159179"), "y_act"+str((datetime.utcnow().day % 2)+1))
  219.     await client.delete_message(tmp)
  220.  
  221. async def DoDaily():
  222.     await DoYuriBotSwitch()
  223. async def joinsdb(remove=None,add=None,save=False,load=False,):
  224.     if remove != None:
  225.         try:
  226.             bot.joinsdb.remove(remove.id)
  227.         except:
  228.             pass
  229.     if add != None:
  230.         bot.joinsdb.append(add.id)
  231.     if load:
  232.         if not os.path.isfile("data_joins.txt"):
  233.             with open("data_joins.txt","w") as f:
  234.                 f.write("")
  235.         with open("data_joins.txt","r") as f:
  236.             joins = f.read()
  237.         joins = list(filter(None,joins.split("\n")))
  238.         bot.joinsdb = []
  239.         for i in joins:
  240.             bot.joinsdb.append(i)
  241.     if save:
  242.         with open("data_joins.txt","w") as f:
  243.             f.write('\n'.join(bot.joinsdb))
  244.            
  245. async def joinlogs_join(member):
  246.     if member.bot:
  247.         await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"**, a bot, has been added to the server.")
  248.     else:
  249.         if member.server.large:
  250.             await client.request_offline_members(member.server)
  251.         memberlen = 0
  252.         for i in member.server.members:
  253.             if not(i.bot):
  254.                 memberlen+=1
  255.         await asyncio.sleep(1)
  256.         if member.id in bot.joinsdb:
  257.             await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has rejoined as the "+ordinal(memberlen)+" member.")
  258.         else:
  259.             await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has joined as the "+ordinal(memberlen)+" member.")
  260.     await joinsdb(add=member,save=True)
  261.    
  262. async def joinlogs_remove(member):
  263.     if member.bot:
  264.         await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"**, a bot, has been removed from the server.")
  265.     else:
  266.         if member.server.large:
  267.             await client.request_offline_members(member.server)
  268.         memberlen = 0
  269.         for i in member.server.members:
  270.             if not(i.bot):
  271.                 memberlen+=1
  272.         await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has left as the "+ordinal(memberlen+1)+" member.")
  273.     await joinsdb(remove=member,save=True)
  274.    
  275. async def joinlogs_ban(member):
  276.     if member.bot:
  277.         await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"**, a bot, has been banned. (Could be temporary or permanant)")
  278.     else:
  279.         await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has been banned. (Could be temporary or permanant)")
  280.    
  281. async def joinlogs_update(before,after):
  282.     if before.roles != after.roles:
  283.         print("ChangeRoles")
  284.         beforeroles = []
  285.         for role in before.roles:
  286.             beforeroles.append(role.name)
  287.         afterroles = []
  288.         for role in after.roles:
  289.             afterroles.append(role.name)
  290.         if "Muted" not in beforeroles and "Muted" in afterroles:
  291.             await client.send_message(bot.joinleavechannel,"**"+after.display_name+"#"+after.discriminator+"** has been muted.")
  292.            
  293.         if "Muted" in beforeroles and "Muted" not in afterroles:
  294.             await client.send_message(bot.joinleavechannel,"**"+after.display_name+"#"+after.discriminator+"** has been unmuted.")
  295.        
  296.         if "Pending" in beforeroles and "Pending" not in afterroles:
  297.             await client.send_message(bot.joinleavechannel,"**"+after.display_name+"#"+after.discriminator+"** has passed screening and is now a member.")
  298.            
  299. async def getjoins():
  300.     async for msg in client.logs_from(bot.joinleavechannel, limit=9999):
  301.         if msg.author.id not in bot.joinsdb:
  302.             bot.joinsdb.append(msg.author.id)
  303.     await joinsdb(save=True)
  304.    
  305. async def StaffSuggestionsDaily(force=False,message=None):
  306.     suglist = []
  307.     if force:
  308.         suglist.append(message)
  309.     else:
  310.         async for msg in client.logs_from(bot.suggestionschannelstaff_bot, limit=99):
  311.             if msg.author == client.user and "SUGGESTION FROM" in msg.content and not "(ALL STAFF VOTES REQUIRED)" in msg.content:
  312.                 if (datetime.utcnow()-msg.timestamp).days >= 1:
  313.                     suglist.append(msg)
  314.    
  315.     for sug in suglist:
  316.         sugstr = sug.content.split(":**__\n")[1].split("\n** **\n** **")[0].replace("__(<#442782454831382530> Suggestion)__","(<#442782454831382530> Suggestion)")
  317.         sug_y = 0
  318.         sug_n = 0
  319.         sug_a = 0
  320.         for x in sug.reactions:
  321.             if isinstance(x.emoji, str):
  322.                 y = x.emoji
  323.             else:
  324.                 y = x.emoji.name
  325.             if "👍" == y:
  326.                 sug_y += x.count-1
  327.             if "👎" == y:
  328.                 sug_n += x.count-1
  329.             if "🇦" == y:
  330.                 sug_a += x.count-1
  331.         try:
  332.             await client.delete_message(sug)       
  333.         except:
  334.             print("No remove permission")
  335.         pinmsg = await client.send_message(bot.suggestionschannelstaff_bot, "** **\n** **\n__**"+sugstr+"**__\n"+str(sug_y)+'\N{THUMBS UP SIGN}'+"\n"+str(sug_n)+'\N{THUMBS DOWN SIGN}'+"\n"+str(sug_a)+'🇦'+"\n** **\n** **")
  336.         try:
  337.             await client.pin_message(pinmsg)
  338.         except Exception as e:
  339.             if "Maximum number of pins reached (50)" in traceback.format_exc():
  340.                 try:
  341.                     await client.unpin_message(sorted(await client.pins_from(message.channel),key = lambda msg: msg.timestamp.timestamp())[0])
  342.                     await client.pin_message(pinmsg)
  343.                 except:
  344.                     print("Failed to remove oldest pin")
  345.                     print(traceback.format_exc())
  346.             else:
  347.                 print("Some misc issue in pinning")
  348.                 print(traceback.format_exc())
  349.         async for msg in client.logs_from(bot.suggestionschannelstaff_bot, limit=99):
  350.             if "pinned a message to this channel" in msg.system_content:
  351.                 try:
  352.                     await client.delete_message(msg)       
  353.                 except:
  354.                     print("Failed to remove 'user has pinned message to this channel' message")
  355.                     print(traceback.format_exc())
  356.         if "(<#442782454831382530> Suggestion)" in pinmsg.content:
  357.             await client.send_message(bot.server.get_channel("442782454831382530"), pinmsg.content)
  358.  
  359. async def SuggestionsDone(reaction,user):  
  360.     if not((reaction.message.channel == bot.suggestionschannel_bot or reaction.message.channel.id == "447760673120976905") and (reaction.emoji == bot.emoji_accepted or reaction.emoji == bot.emoji_denied)):
  361.         return
  362.     sugstr = reaction.message.content.split(":**__\n")[1].split("\n** **\n** **")[0]
  363.     if reaction.emoji == bot.emoji_accepted:
  364.         sugstr = "** **\n** **\n"+str(bot.emoji_accepted)+"__**Accepted by "+bot.server.get_member(user.id).display_name+":**__"+str(bot.emoji_accepted)+"\n"+sugstr       
  365.     elif reaction.emoji == bot.emoji_denied:
  366.         sugstr = "** **\n** **\n"+str(bot.emoji_denied)+"__**Denied by "+bot.server.get_member(user.id).display_name+":**__"+str(bot.emoji_denied)+"\n"+sugstr
  367.     pinmsg = await client.send_message(reaction.message.channel, sugstr)
  368.     try:
  369.         await client.pin_message(pinmsg)
  370.     except Exception as e:
  371.         if "Maximum number of pins reached (50)" in traceback.format_exc():
  372.             try:
  373.                 await client.unpin_message(sorted(await client.pins_from(reaction.message.channel),key = lambda msg: msg.timestamp.timestamp())[0])
  374.                 await client.pin_message(pinmsg)
  375.             except:
  376.                 print("Failed to remove oldest pin")
  377.                 print(traceback.format_exc())
  378.         else:
  379.             print("Some misc issue in pinning")
  380.             print(traceback.format_exc())
  381.     async for msg in client.logs_from(reaction.message.channel, limit=99):
  382.         if "pinned a message to this channel" in msg.system_content:
  383.             try:
  384.                 await client.delete_message(msg)
  385.             except:
  386.                 print("Failed to remove 'user has pinned message to this channel' message")
  387.                 print(traceback.format_exc())
  388.     try:
  389.         await client.delete_message(reaction.message)      
  390.     except:
  391.         print("No remove permission")
  392. #Q: Will this work? A:https://www.youtube.com/watch?v=DNeikvoqQ-s
  393.  
  394. async def reaction_screening(reaction,user):
  395.     if user.id == client.user.id or reaction.message.channel != bot.pendingchannel:
  396.         return
  397.     if not(await IsStaff(reaction.message,user)):
  398.         try:
  399.             await client.send_message(user,"Please do not touch the ratings in the pending channel. They are staff only.")
  400.         except:
  401.             pass
  402.         await client.clear_reactions(reaction.message)
  403.         await client.add_reaction(reaction.message,bot.emoji_accepted)
  404.         await client.add_reaction(reaction.message,bot.emoji_denied)
  405.     else:
  406.         print("USER BEING PROMOTED: "+reaction.message.content.split("<@")[1].split(">")[0])
  407.         promoteuser = bot.server.get_member(reaction.message.content.split("<@")[1].split(">")[0])
  408.         if reaction.emoji == bot.emoji_accepted:
  409.             for i in bot.server.roles:
  410.                 if i.name=="Member":
  411.                     try:
  412.                         await client.replace_roles(promoteuser,i)
  413.                     except Exception as e:
  414.                         await client.send_message(bot.pendingchannel,"Failed to promote <@"+promoteuser.id+"> to member, insufficient permissions. Is user pending without any other roles?")
  415.                         print(str(e))
  416.                         await client.clear_reactions(reaction.message)
  417.                         await client.add_reaction(reaction.message,bot.emoji_accepted)
  418.                         await client.add_reaction(reaction.message,bot.emoji_denied)
  419.                         return
  420.             await client.send_message(bot.server.get_channel("423209786981744642"),"Welcome to Just Yuri, <@"+promoteuser.id+">! If you have any questions or need any assistance, please directly message or ping an ***Admin***, ***Moderator***, or ***Legislator***!")
  421.             try:
  422.                 await client.delete_message(reaction.message)
  423.             except:
  424.                 pass
  425.         elif reaction.emoji == bot.emoji_denied:
  426.             await client.send_message(bot.pendingchannel,"<@"+promoteuser.id+">, you have been denied access to the server outside of <#422197075531530260>.")
  427.             try:
  428.                 await client.delete_message(reaction.message)
  429.             except:
  430.                 pass
  431.         else:
  432.             await client.clear_reactions(reaction.message)
  433.             await client.add_reaction(pacappmsg,bot.emoji_accepted)
  434.             await client.add_reaction(pacappmsg,bot.emoji_denied)
  435. async def reaction_suggestions(reaction,user):
  436.     if reaction.message.channel == bot.suggestionschannel_bot:
  437.         botchannel = bot.suggestionschannel_bot
  438.         isstaff = False
  439.     elif reaction.message.channel == bot.suggestionschannelstaff_bot:
  440.         botchannel = bot.suggestionschannelstaff_bot
  441.         isstaff = True
  442.     else:
  443.         return
  444.     reaction_userlist = []
  445.     for messagereaction in reaction.message.reactions:
  446.         cur_reactionuserlist = await client.get_reaction_users(messagereaction, limit=99)
  447.         for msguser in cur_reactionuserlist:
  448.             reaction_userlist.append([msguser,messagereaction.emoji])
  449.     for item in reaction_userlist:
  450.         if item[0] == user and item[1] == reaction.emoji:
  451.             continue
  452.         if item[0] == user:
  453.             await client.remove_reaction(reaction.message,item[1],bot.server.get_member(item[0].id))
  454.             break
  455. async def reaction_staffsuggestionsoverflow(reaction,user):
  456.     if reaction.message.channel != bot.suggestionschannelstaff_bot:
  457.         return
  458.     voters = 0
  459.     votey = 0
  460.     voten = 0
  461.     votea = 0
  462.     for messagereaction in reaction.message.reactions:
  463.         cur_reactionuserlist = await client.get_reaction_users(messagereaction, limit=99)
  464.         for msguser in cur_reactionuserlist:
  465.             if msguser != client.user:
  466.                 voters += 1
  467.         if isinstance(messagereaction.emoji, str):
  468.             y = messagereaction.emoji
  469.         else:
  470.             y = messagereaction.emoji.name
  471.         if "👍" == y:
  472.             votey+= voters
  473.         if "👎" == y:
  474.             voten+= voters
  475.         if "🇦" == y:
  476.             votea+= voters
  477.         voters = 0
  478.     voters = votey+voten+votea
  479.     stafflist = 0
  480.     async for msg in client.logs_from(bot.stafflistchannel, limit=99):
  481.         stafflist+=len(msg.mentions)
  482.     if voters>=stafflist:
  483.         await StaffSuggestionsDaily(True,reaction.message)
  484.     if not("(ALL STAFF VOTES REQUIRED)" in reaction.message.content):
  485.         staffthres = math.floor(((stafflist-votea)/2))
  486.         print("Staff Threshold: "+str(staffthres))
  487.         print("Staff voted yes: "+str(votey))
  488.         print("Staff voted no: "+str(voten))
  489.         if votey > staffthres or voten > staffthres:
  490.             print("Majority Roleover")
  491.             await StaffSuggestionsDaily(True,reaction.message)
  492.    
  493.  
  494. @client.event
  495. async def on_reaction_add(reaction, user):
  496.     if user == client.user:
  497.         return
  498.     await reaction_screening(reaction,user)
  499.     await reaction_suggestions(reaction,user)
  500.     await reaction_staffsuggestionsoverflow(reaction,user)
  501.     await SuggestionsDone(reaction,user)
  502. async def CheckForPasscode(message):
  503.     if message.channel != bot.pendingchannel:
  504.         return
  505.     ispending = False
  506.     for i in bot.server.get_member(message.author.id).roles:
  507.         if i.name == "Pending":
  508.             ispending = True
  509.             break
  510.     if not(ispending):
  511.         return
  512.     haspasscode = True
  513.     hasmodpasscode = True
  514.     for i in bot.passcode:
  515.         if not(i in message.content.lower()):
  516.             haspasscode = False
  517.             break
  518.     for i in bot.modpasscode:
  519.         if not(i in message.content.lower()):
  520.             hasmodpasscode = False
  521.             break
  522.     if haspasscode:
  523.         tmpapprove=await client.send_message(bot.pendingchannel,"<@"+message.author.id+"> has entered the correct password for screening. Please stand by for staff approval.")    
  524.         await client.add_reaction(tmpapprove,bot.emoji_accepted)
  525.         await client.add_reaction(tmpapprove,bot.emoji_denied)
  526.         try:
  527.             await client.delete_message(message)   
  528.         except:
  529.             print("No remove permission")
  530.     elif hasmodpasscode:
  531.         tmpapprove=await client.send_message(bot.pendingchannel,"<@"+message.author.id+"> has entered the mod-only password and has been assigned the \"Mod Access\" role.")
  532.         print("USER BEING PROMOTED TO MOD: "+message.author.id)
  533.         promoteuser = bot.server.get_member(message.author.id)
  534.         for i in bot.server.roles:
  535.             if i.name=="Mod Access":
  536.                 try:
  537.                     await client.replace_roles(promoteuser,i)
  538.                 except Exception as e:
  539.                     await client.send_message(bot.pendingchannel,"Failed to promote <@"+promoteuser.id+"> to Mod Access, insufficient permissions. Is user pending without any other roles?")
  540.                     print(str(e))
  541.                     try:
  542.                         await client.delete_message(tmpapprove)
  543.                     except:
  544.                         pass
  545.                 break
  546.         await client.send_message(bot.server.get_channel("440511325068591104"),"Welcome to the #mod-access channel, <@"+promoteuser.id+">! If you have any questions or need any assistance, please directly message or ping an Admin, Moderator, or Legislator! \nPlease check the pinned messages for more information!\nThank you!")
  547.         try:
  548.             await client.delete_message(message)   
  549.         except:
  550.             print("No remove permission")
  551. async def PreservePin(before,after):
  552.     if not(before.pinned) and after.pinned and not(bot.doingpreserve):
  553.         message = after
  554.         try:
  555.             pinlist = sorted(await client.pins_from(message.channel),key = lambda msg: msg.timestamp.timestamp(),reverse=True) #Oldest first
  556.             bot.doingpreserve = True
  557.             for pin in pinlist:
  558.                 if pin.content.startswith("=="):
  559.                     await client.unpin_message(pin)
  560.                     await client.pin_message(pin)
  561.                 if pin == pinlist[-1]:
  562.                     bot.doingpreserve = False
  563.             async for msg in client.logs_from(message.channel, limit=99):
  564.                 if "pinned a message to this channel" in msg.system_content and (bot.server.get_member(client.user.id).display_name in msg.system_content or client.user.id in msg.system_content):
  565.                     try:
  566.                         await client.delete_message(msg)
  567.                     except:
  568.                         pass
  569.         except Exception as e:
  570.             print(traceback.format_exc())
  571.             bot.doingpreserve = False
  572.  
  573. async def DoPassOfTheDay():
  574.     async for msg in client.logs_from(bot.ruleschannel, limit=999):
  575.         if msg.author == client.user and msg.content.startswith("Password for "):
  576.             await client.delete_message(msg)
  577.     randomwords = ["lane","dash","hall","pit","folk","swarm","trail","spell","fast","offer","great","good","nice","line","sport","old","new","park","red","blue","green","white","black"]
  578.     bot.passcode = []
  579.     bot.modpasscode = []
  580.     for passcode in [bot.passcode,bot.modpasscode]:
  581.         for i in range(random.randrange(1,3)):
  582.             passcode.append(random.choice(randomwords))
  583.             randomwords.remove(passcode[-1])
  584.     await client.send_message(bot.ruleschannel,'Password for the entire community server: "'+' '.join(bot.passcode)+'". Please type this passcode in <#422197075531530260> to gain access to the entire community.')
  585.     await client.send_message(bot.ruleschannel,'Password for Just Yuri mod access: "'+' '.join(bot.modpasscode)+'". Please type this passcode in <#422197075531530260> if you only want access to Just Yuri related items.')
  586.     bot.lastpass = datetime.utcnow()
  587.     print("New password set at "+bot.lastpendingreminder.strftime(" %Y-%b-%d_%Hh%Mm%Ss"))
  588.  
  589. async def PassOfTheDay():
  590.     if bot.lastpass == None:
  591.         bot.lastpass = -1
  592.         async for msg in client.logs_from(bot.ruleschannel, limit=999):
  593.             if msg.author == client.user:
  594.                 if msg.content.startswith('Password for the entire community server:'):
  595.                     bot.passcode = msg.content.split('"')[1].split('"')[0].split(" ")
  596.                     print("PASSCODE SET TO: "+' '.join(bot.passcode))
  597.                     bot.lastpass = msg.timestamp
  598.                     continue
  599.                 if msg.content.startswith('Password for Just Yuri mod access:'):
  600.                     bot.modpasscode = msg.content.split('"')[1].split('"')[0].split(" ")
  601.                     print("MOD PASSCODE SET TO: "+' '.join(bot.modpasscode))
  602.                     bot.lastpass = msg.timestamp
  603.                     continue
  604.         if bot.lastpass == -1:
  605.             await DoPassOfTheDay()
  606.     if (datetime.utcnow()-bot.lastpass).days >= 1:
  607.         await DoPassOfTheDay()
  608. async def FindImages(message)
  609.     dl_urls = []
  610.     dled_urls = []
  611.     if len(message.attachments) != 0:
  612.         for att in message.attachments:
  613.             dl_urls.append(att["url"])     
  614.     if len(re.findall(URL_REGEX,message.content)) !=0: #URL
  615.         for urlfound in re.findall(URL_REGEX,message.content):
  616.             dl_urls.append(urlfound)
  617.     for urlfound in dl_urls:
  618.         if mimetypes.guess_type(urlfound)[0] != None and "image" in mimetypes.guess_type(urlfound)[0]:
  619.             dled_urls.append(urlfound)
  620.     if dled_urls == []:
  621.         return None
  622.     else:
  623.         return dled_urls
  624.        
  625.  
  626. async def Suggestions(message):
  627.     if (message.channel == bot.suggestionschannel_human or message.channel == bot.suggestionschannelstaff_human or message.channel.id =="442782454831382530" or message.channel.id == "392835203447390208") and message.content.startswith(bot.suggestionschannel_prefix):
  628.         if message.channel == bot.suggestionschannel_human:
  629.             humanchannel = bot.suggestionschannel_human
  630.             botchannel = bot.suggestionschannel_bot
  631.             isstaff = False
  632.         elif message.channel.id == "392835203447390208":
  633.             humanchannel = bot.server.get_channel("392835203447390208")
  634.             botchannel = bot.server.get_channel("447760673120976905")
  635.             isstaff = False
  636.         elif message.channel == bot.suggestionschannelstaff_human or message.channel.id =="442782454831382530":
  637.             humanchannel = bot.suggestionschannelstaff_human
  638.             botchannel = bot.suggestionschannelstaff_bot
  639.             isstaff = True
  640.         message.content=message.content.replace(bot.suggestionschannel_prefix,"",1)
  641.         if message.content.startswith("<@") or message.content.startswith("<@!"):
  642.             if message.content.startswith("<@!"):
  643.                 prefix = "<@!"
  644.             else:
  645.                 prefix = "<@"
  646.             authorid = message.content.split(prefix,1)[1].split(">",1)[0]
  647.             mention = prefix+authorid+">"
  648.             suggestion = message.content.replace(mention,"").lstrip()
  649.         else:
  650.             suggestion = message.content
  651.             try:
  652.                 name = message.author.id
  653.                 mention = "<@!"+name+">"
  654.             except Exception as e:
  655.                 print(str(e))
  656.                 name = "Unknown User"
  657.                 mention = "@"+name     
  658.         await client.send_message(message.channel, "To see and vote on **"+message.author.display_name+"**'s idea, please go to <#"+botchannel.id+">!")
  659.         sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n{2}{1}\n** **\n** **"
  660.         if message.channel.id == "442782454831382530":
  661.             sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n{2}__(<#442782454831382530> Suggestion)__\n{1}\n** **\n** **"
  662.         if message.content.startswith("--") and isstaff:
  663.             suggestion = suggestion.replace("--","",1)
  664.             allvotes = "__(ALL STAFF VOTES REQUIRED)__\n"
  665.         else:
  666.             allvotes = ""
  667.         tmp_sug = await client.send_message(botchannel, sugstr.format(message.author.display_name+" ("+message.author.name+"#"+message.author.discriminator+")",suggestion,allvotes))
  668.         print("Suggestion ID:" + tmp_sug.id)
  669.         if len(message.attachments) != 0:
  670.             for i in message.attachments:
  671.                 try:
  672.                     async with aiohttp.ClientSession() as cs:
  673.                         async with cs.get(i["url"]) as r:
  674.                             try:
  675.                                 content = await r.content.read()
  676.                                 with open(i["url"].split("/")[-1],"wb") as f:
  677.                                     f.write(content)
  678.                             except:
  679.                                 pass
  680.                     tmp_sug = await client.send_file(botchannel, i["url"].split("/")[-1])
  681.                     os.remove(i["url"].split("/")[-1])
  682.                 except:
  683.                     pass
  684.         await asyncio.sleep(0.5)
  685.         await client.add_reaction(tmp_sug,'\N{THUMBS UP SIGN}')
  686.         await asyncio.sleep(0.5)
  687.         await client.add_reaction(tmp_sug,'\N{THUMBS DOWN SIGN}')
  688.         await asyncio.sleep(0.5)
  689.         if isstaff:
  690.             await client.add_reaction(tmp_sug,'🇦')
  691.         else:
  692.             await client.add_reaction(tmp_sug,'🇳')
  693.         if message.channel.id != "442782454831382530":
  694.             try:
  695.                 await client.delete_message(message)       
  696.             except:
  697.                 print("No remove permission")
  698.             return True
  699. async def CMD_sugfix(message):
  700.     if message.author.id != "380793206033612809":
  701.         return
  702.     if message.content.lower().startswith(bot.prefix+"sugfix"):
  703.         fixid = message.content.lower().replace(bot.prefix+"sugfix","").strip()
  704.         try:
  705.             await client.delete_message(message)       
  706.         except:
  707.             print("No remove permission")
  708.         for i in ["447760673120976905","389552930639839244"]:
  709.             try:
  710.                 async for msg in client.logs_from(bot.server.get_channel(i), limit=999):
  711.                     if msg.id == fixid:
  712.                         await client.clear_reactions(msg)
  713.                         await asyncio.sleep(0.5)
  714.                         await client.add_reaction(msg,'\N{THUMBS UP SIGN}')
  715.                         await asyncio.sleep(0.5)
  716.                         await client.add_reaction(msg,'\N{THUMBS DOWN SIGN}')
  717.                         await asyncio.sleep(0.5)
  718.                         await client.add_reaction(msg,'🇳')
  719.                         return
  720.             except:
  721.                 pass
  722. async def MultiSuggestions(message):
  723.     if (message.channel == bot.suggestionschannel_human or message.channel == bot.suggestionschannelstaff_human or message.channel.id =="442782454831382530" or message.channel.id == "392835203447390208") and message.content.startswith(bot.suggestionschannel_prefix_multi):
  724.         if message.channel == bot.suggestionschannel_human:
  725.             humanchannel = bot.suggestionschannel_human
  726.             botchannel = bot.suggestionschannel_bot
  727.             isstaff = False
  728.         elif message.channel.id == "392835203447390208":
  729.             humanchannel = bot.server.get_channel("392835203447390208")
  730.             botchannel = bot.server.get_channel("447760673120976905")
  731.             isstaff = False
  732.         elif message.channel == bot.suggestionschannelstaff_human or message.channel.id =="442782454831382530":
  733.             humanchannel = bot.suggestionschannelstaff_human
  734.             botchannel = bot.suggestionschannelstaff_bot
  735.             isstaff = True
  736.         if isstaff:
  737.             return
  738.        
  739.         message.content=message.content.replace(bot.suggestionschannel_prefix_multi,"",1)
  740.         items = message.content.split("\n")
  741.         precursor = items.pop(0)
  742.         if len(items) > 10:
  743.             await client.send_message(message.channel, "More than 10 suggestions are not supported, <@"+message.author.id+">.")
  744.             return
  745.         suggestion = message.content
  746.         sugmodstr = precursor+"\n"
  747.         for i in range(len(items)):
  748.             sugmodstr+=u'{0}\u20e3'.format(str(i)) + " " +items[i]+"\n"
  749.         await client.send_message(message.channel, "To see and vote on **"+message.author.display_name+"**'s idea, please go to <#"+botchannel.id+">!")
  750.         sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n{1}\n** **\n** **"
  751.         if message.channel.id == "442782454831382530":
  752.             sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n__(<#442782454831382530> Suggestion)__\n{1}\n** **\n** **"
  753.            
  754.         tmp_sug = await client.send_message(botchannel, sugstr.format(message.author.display_name+" ("+message.author.name+"#"+message.author.discriminator+")",sugmodstr))
  755.         print("Suggestion ID:" + tmp_sug.id)
  756.         if len(message.attachments) != 0:
  757.             for i in message.attachments:
  758.                 try:
  759.                     async with aiohttp.ClientSession() as cs:
  760.                         async with cs.get(i["url"]) as r:
  761.                             try:
  762.                                 content = await r.content.read()
  763.                                 with open(i["url"].split("/")[-1],"wb") as f:
  764.                                     f.write(content)
  765.                             except:
  766.                                 pass
  767.                     tmp_sug = await client.send_file(botchannel, i["url"].split("/")[-1])
  768.                     os.remove(i["url"].split("/")[-1])
  769.                 except:
  770.                     pass
  771.         for i in range(len(items)):
  772.             await client.add_reaction(tmp_sug,u'{0}\u20e3'.format(str(i)))
  773.         if isstaff:
  774.             await client.add_reaction(tmp_sug,'🇦')
  775.         else:
  776.             await client.add_reaction(tmp_sug,'🇳')
  777.         if message.channel.id != "442782454831382530":
  778.             try:
  779.                 await client.delete_message(message)       
  780.             except:
  781.                 print("No remove permission")
  782.             return True
  783. async def Looper():
  784.     while True:
  785.         await PingReminder()
  786.         await PassOfTheDay()
  787.         await StaffSuggestionsDaily()
  788.         await asyncio.sleep(3)
  789. async def AntiSpam(message):
  790.     imglist = await FindImages(message)
  791.     if imglist != None:
  792.         return
  793.     nw = datetime.utcnow()
  794.     count = 0
  795.     msgs = [message]
  796.     async for msg in client.logs_from(message.channel, limit=10):
  797.         if msg.author == message.author:
  798.             if (nw-msg.timestamp).seconds <=3:
  799.                 count +=1
  800.                 msgs.append(msg)
  801.     if count >=4:
  802.         tmp_antispam = await client.send_message(message.channel,"<@"+message.author.id+">, do not spam messages. This is a punishable infraction.")
  803.         for msg in msgs:
  804.             try:
  805.                 await client.delete_message(msg)
  806.             except:
  807.                 pass       
  808.         await asyncio.sleep(3)
  809.         await client.delete_message(tmp_antispam)
  810.         return True
  811.     return False
  812.  
  813. async def AntiSpamImage(message):
  814.     if message.channel.id in ["389588277222703104"]: #Art-and-photography
  815.         return
  816.    
  817.     imglist = await FindImages(message)
  818.     if imglist == None:
  819.         return
  820.     #print(len(imglist))
  821.     if len(imglist) >3:
  822.         tmp_imgantispam_multi = await client.send_message(message.channel,"<@"+message.author.id+">, you may only post three images at a time in this channel.")
  823.         try:
  824.             await client.delete_message(message)
  825.         except:
  826.             pass
  827.         await asyncio.sleep(10)
  828.         await client.delete_message(tmp_imgantispam_multi)
  829.         return True
  830.     elif len(imglist) >1:
  831.         testlist = []
  832.         imageduplicate = False
  833.         for url in imglist:
  834.             for urllisted in testlist:
  835.                 if urllisted == url:
  836.                     imageduplicate = True
  837.                     break
  838.             testlist.append(url)
  839.         if imageduplicate:
  840.             tmp_imgantispam_multi_same = await client.send_message(message.channel,"<@"+message.author.id+">, you are not allowed to post multiple of the same images all at once.")
  841.             try:
  842.                 await client.delete_message(message)
  843.             except:
  844.                 pass
  845.             await asyncio.sleep(10)
  846.             await client.delete_message(tmp_imgantispam_multi_same)
  847.     nw = datetime.utcnow()
  848.     singleantispam = False
  849.     waittime = 0
  850.     async for msg in client.logs_from(message.channel, limit=50):
  851.         if msg.author == message.author and message.timestamp != msg.timestamp:
  852.             imglist_sub = await FindImages(msg)
  853.             if imglist_sub != None and (nw-msg.timestamp).seconds <30:
  854.                 waittime = math.ceil(30-((nw-msg.timestamp).seconds))
  855.                 singleantispam = True
  856.                 break
  857.     if singleantispam:
  858.         tmp_imgantispam_single = await client.send_message(message.channel,"<@"+message.author.id+">, you may only post images in this channel every 30 seconds. \nYou may post another in "+str(waittime)+" seconds (when this mesage deletes)")
  859.         try:
  860.             await client.delete_message(message)
  861.         except:
  862.             pass
  863.         await asyncio.sleep(waittime)
  864.         await client.delete_message(tmp_imgantispam_single)
  865.         return True
  866.     return False
  867.    
  868.        
  869. async def AntiEXE(message):
  870.     if len(message.attachments) != 0:
  871.         for i in message.attachments:
  872.             if i["url"].endswith("exe"):
  873.                 await client.send_message(message.channel,"<@"+message.author.id+">, your .exe file '"+i["url"].split("/")[-1]+"' has been removed, as sharing executables in public chats is a security risk. \nPlease use DMs.")
  874.                 await client.delete_message(message)
  875.     if len(re.findall(URL_REGEX,message.content)) !=0: #URL
  876.         for i in re.findall(URL_REGEX,message.content):
  877.             if i.endswith(".exe"):
  878.                 await client.send_message(message.channel,"<@"+message.author.id+">, your .exe file '"+i.split("/")[-1]+"' has been removed, as sharing executables in public chats is a security risk. \nPlease use DMs.")
  879.                 await client.delete_message(message)
  880. async def AntiInvite(message):
  881.     if len(re.findall(URL_REGEX,message.content)) !=0: #URL
  882.         for i in re.findall(URL_REGEX,message.content):
  883.             if "discord.gg" in i or "discordapp.com/invite/" in i:
  884.                 await client.send_message(message.channel,"<@"+message.author.id+">, sending discord invites is not allowed in <#397087061846261761>. Please use <#400113786457161728>.")
  885.                 await client.delete_message(message)
  886. async def CMD_clearpin(message):
  887.     if message.content.lower().startswith("/clearpin") or message.content.lower().startswith("/pinclear"):
  888.         if await IsStaff(message):
  889.             try:
  890.                 pindel = sorted(await client.pins_from(message.channel),key = lambda msg: msg.timestamp.timestamp())[0]
  891.                 pinmsg = "```\n"
  892.                 pinmsg+=pindel.timestamp.strftime("%Y-%b-%d_%Hh%Mm%Ss")+"\n"
  893.                 pinmsg+=pindel.author.display_name+"\n"
  894.                 pinmsg+="("+pindel.author.name+"#"+pindel.author.discriminator+")\n"
  895.                 pinmsg+=pindel.content
  896.                 pinimgs = await FindImages(pindel)
  897.                 if pinimgs != None:
  898.                     pinmsg+="\n"
  899.                     for i in pinimgs:
  900.                         pinmsg+=i
  901.                         if i != pinimgs[-1]:
  902.                             pinmsg+="\n"
  903.                 pinmsg +="```"
  904.                 await client.unpin_message(pindel)
  905.                 await client.send_message(message.channel,"Message unpinned:\n"+pinmsg)
  906.                 await client.send_message(message.channel,"<@"+message.author.id+"> has cleared a pinned message slot.")
  907.             except Exception as e:
  908.                 await client.send_message(message.channel,"<@"+message.author.id+"> Failure!\n```"+str(e)+"```")
  909.                 print("Failed to remove oldest pin")
  910.                 print(traceback.format_exc())
  911.         await client.delete_message(message)
  912. async def CMD_raid(message):
  913.     if message.content.startswith("001"):
  914.         staffchnl = bot.server.get_channel("396470791920680971")
  915.         athr = message.author
  916.         cnt = message.content.replace("001 ","").replace("001","")
  917.         try:
  918.             await client.delete_message(message)
  919.         except:
  920.             pass
  921.         ments = "<@&389552626137563148>" #Mods
  922.         for i in range(2):
  923.             tmp_raid = await client.send_message(staffchnl,ments+" Code 001") #mods
  924.             await client.delete_message(tmp_raid)
  925.         await client.send_message(staffchnl,ments+"\n__<@"+athr.id+"> has activated code 001:__\n``"+cnt+"``")
  926.         try:
  927.             await client.send_message(athr,"__You have activated code 001:__\n``"+cnt+"``")
  928.         except:
  929.             pass
  930. async def CMD_suicide(message):
  931.     if message.content.startswith("002"):
  932.         staffchnl = bot.server.get_channel("396470791920680971")
  933.         athr = message.author
  934.         cnt = message.content.replace("002 ","").replace("002","")
  935.         try:
  936.             await client.delete_message(message)
  937.         except:
  938.             pass
  939.         ments = "<@&389552626137563148> <@&417941723868823584> <@&428125906729566218>" #Mods admins couns
  940.         for i in range(2):
  941.             tmp_raid = await client.send_message(staffchnl,ments+" Code 002")
  942.             await client.delete_message(tmp_raid)
  943.         await client.send_message(staffchnl,ments+"\n__<@"+athr.id+"> has activated code 002:__\n``"+cnt+"``")
  944.         try:
  945.             await client.send_message(athr,"__You have activated code 002:__\n``"+cnt+"``")
  946.         except:
  947.             pass
  948. async def AntiBotCmds(message):
  949.     if message.author.bot and message.channel != bot.botchannel and message.channel.id != "442782454831382530" and message.channel.id != "400113786457161728":
  950.         if (message.author.id == "159985870458322944" or message.author.id == "172002275412279296") and "level" in message.content:
  951.             return #Its just the stupid level up stuff
  952.         async for msg in client.logs_from(message.channel, limit=10):
  953.             isstaff = await IsStaff(msg)
  954.             if msg.content.startswith(("!","'","+",".","?","t!","/")) and not(isstaff):
  955.                 tmp = await client.send_message(message.channel,"<@"+msg.author.id+">, please use <#"+bot.botchannel.id+">.")
  956.                 try:
  957.                     await client.delete_message(message)
  958.                     await client.delete_message(msg)
  959.                 except:
  960.                     print("Unable to delete")
  961.                 return True
  962. async def CMD_help(message):
  963.     if message.content.lower() == bot.prefix+"helpmulti":
  964.         helpstr = "__**To make a multi suggestion:**__\n1) Prefix with \"m--\"\n2) State your initial summary of your suggestion\n3) With every new line after the first, it will make a new voting option (Press shift+enter while typing on PC to add a new line)\n__Command__\n```m--Please vote on creed\nCreed is a gay\nCreed is not a gay\nCreed is actually pretty alright\nCreed makes cool bots```\n__Result:__\nhttps://cdn.discordapp.com/attachments/415652708591337503/448501793916190720/unknown.png"
  965.         try:
  966.             await client.send_message(message.author,helpstr)
  967.         except:
  968.             helpstr = "<@"+message.author.id+">\n"+helpstr
  969.             await client.send_message(bot.botchannel,helpstr)
  970.         return
  971.     if not(message.content.lower().startswith(bot.prefix+"help")):
  972.         return
  973.     if await IsStaff(message) or message.author.id == "380793206033612809":
  974.         helpmsg = ""
  975.         helpmsg += "**__Staff Commands__\n\n**"
  976.         helpmsg += "`/restartbot`\nYou ever just fucking smack a broken machine and it starts working again? This is the equivalent.\n\n"
  977.         helpmsg += "`/clearpin` or `/pinclear`\nClears the oldest pin to make way for a new one. Displays a copy of the pin that was unpinned, for posterity.\n\n"
  978.         helpmsg += "`/fatban imageorurl`\nThe attached image will be added to the \"fat doki blacklist\" and the most recent section of chat will be scanned with new blacklist parameters.\n\n"
  979.         helpmsg += "`/nuke`\nRemoves most recent cBot commands in the channel.\n\n"
  980.         helpmsg += "`/secnuke`\nIn the <#442782454831382530> chat, all \"Non-Relevant\" messages are cleaned up. \n\n"     
  981.         helpmsg += "`/undelete`\nToggles the \"undeleter\" function globally.\n\n"
  982.         helpmsg += "`/undelete @user`\nIf undeleter is off, turns on undelete on a specific user.\n\n"
  983.         helpmsg += "`--somesuggestiontextandorimage` in <#396470791920680971> or <#442782454831382530>\nPosts a suggestion to <#433373031013023775>.\n\n"
  984.         helpmsg += "`==averyimportantmessage` pinned in a channel\nEnsures that no matter whats pinned in that channel, messages starting with \"==\" are always at the top.\n\n"
  985.         helpmsg += "** **\n ** **\n ** **\n"
  986.         om = await OverflowMessage(helpmsg,message.author)
  987.         if not(om==True):
  988.             try:
  989.                 await client.send_message(bot.botchannel, "<@"+message.author.id+">")
  990.                 om = await OverflowMessage(helpmsg,bot.botchannel)
  991.                 if not(om==True):
  992.                     raise
  993.             except:
  994.                 await client.send_message(message.channel, "**Error in sending message.**")
  995.                 return
  996.     helpmsg = ""
  997.     helpmsg += "**__User Commands__\n\n**"
  998.     helpmsg += "``--somesuggestiontextandorimage`` in <#415652708591337503> or <#392835203447390208>\nPosts a suggestion to <#389552930639839244> or <#447760673120976905>\n\n"
  999.     helpmsg += "``m--somesuggestiontextandorimage`` in <#415652708591337503> or <#392835203447390208>\nPosts a multi-option suggestion to <#389552930639839244> or <#447760673120976905>. Type \""+bot.prefix+"helpmulti\" for info on how to use\n\n"
  1000.     helpmsg += "**__Fun Commands__\n\n**"
  1001.     helpmsg += "`/namecount somenamehere`\n1,2,3,4, how many somenamehere's are in my store?\n*(I knooooow you're stealing)*\n\n"
  1002.     helpmsg += "`/gaymode`\nCalls a random person a gay on a scale of \"a bit\" to \"Super fuckin\"*\n\n"
  1003.     helpmsg += "`/marry @user`\nPropose to a user\n\n"
  1004.     helpmsg += "`/divorce @user`\nDivorce a user\n\n"
  1005.     helpmsg += "`/proposals [@user]`\nShow who has proposed to you/@user\n\n"
  1006.     helpmsg += "`/marriages [@user]`\nShow who you/@user are married to\n\n"
  1007.     #helpmsg += "`/owo somegayowoshithere`\nMimic the gay owolord (General only)*\n\n"
  1008.    
  1009.     helpmsg += "** **\n ** **\n ** **\n"
  1010.     om = await OverflowMessage(helpmsg,message.author)
  1011.     if not(om==True):
  1012.         try:
  1013.             await client.send_message(bot.botchannel, "<@"+message.author.id+">")
  1014.             om = await OverflowMessage(helpmsg,bot.botchannel)
  1015.             if not(om==True):
  1016.                 raise
  1017.         except:
  1018.             await client.send_message(message.channel, "**Error in sending message.**")
  1019.             return
  1020.     await TryDelete(message)
  1021. async def CMD_undelete(message):
  1022.     if message.content.startswith(bot.prefix+"undelete"):
  1023.         await client.delete_message(message)
  1024.         bot.undeleteid = message.content.lower().split("<@")[1].split(">")[0].replace("!","")
  1025.         if await IsStaff(message) or message.author.id == "380793206033612809":
  1026.             bot.undelete = not(bot.undelete)
  1027.             await client.send_message(message.channel, "Undeleter: {status}".format(status="Active" if bot.undelete else "Inactive"))  
  1028. async def CMD_forge(message):
  1029.     if message.content.startswith(bot.prefix+"forge") and message.author.id == "380793206033612809":
  1030.         await client.delete_message(message)
  1031.         await client.send_message(message.channel,message.content.replace(bot.prefix+"forge","",1))
  1032. async def MiscProc(message):
  1033.     if message.channel.id not in ["397087352633294848","413129174853746708","413584030928338945"]:
  1034.         await AntiBotCmds(message)
  1035.  
  1036.     if message.author != client.user:
  1037.         await CheckForPasscode(message)
  1038.         await AntiEXE(message)
  1039.         await CMD_clearpin(message)
  1040.         await CMD_raid(message)
  1041.         await CMD_suicide(message)
  1042.         await CMD_help(message)
  1043.         await CMD_sugfix(message)
  1044.         await CMD_undelete(message)
  1045.         await CMD_forge(message)
  1046.         if not(message.channel.id in ["397087352633294848","413129174853746708","413584030928338945", "413584030928338945","400113786457161728","413169308995289098","433373031013023775","434191966994169866","389560237889159179","396470791920680971"]) and not(message.content.startswith(bot.prefix)):#Sexy Chaos, Chaos,#Staff den,#staff-voting,#staff,#bot-commands
  1047.             await AntiSpam(message)
  1048.             await AntiSpamImage(message)
  1049.             await AntiInvite(message)
  1050.     #Pending notifier
  1051. ##############################################################################################################
  1052. ##############################################################################################################
  1053. ##########################################END OF !FUNCTIONS###################################################
  1054. ##############################################################################################################
  1055. async def UnDelete(message):
  1056.     if message.content != "":
  1057.         await client.send_message(message.channel, "__**UNDELETER**__\n__{authorshit}__\n{msg}".format(authorshit=message.author.display_name,msg=message.content))
  1058.     foundimgs = await FindImages(message)
  1059.     if foundimgs != None:
  1060.         foundimgs_names = []
  1061.         for img in foundimgs:
  1062.             filename = img.rsplit("/",1)[1]
  1063.             async with aiohttp.ClientSession() as cs:
  1064.                 async with cs.get(img) as r:
  1065.                     try:
  1066.                         content = await r.content.read()
  1067.                         imgb = Image.open(io.BytesIO(content))
  1068.                         imgb.save("undelete_"+filename)
  1069.                         foundimgs_names.append("undelete_"+filename)
  1070.                     except:
  1071.                         print(traceback.format_exc())
  1072.                         print("Undelete Failure")
  1073.         for img in foundimgs_names:
  1074.             await client.send_message(message.channel, "__**UNDELETER**__\n__{authorshit}__".format(authorshit=message.author.display_name))
  1075.             await client.send_file(message.channel,"undelete_"+filename)                           
  1076.             try:
  1077.                 os.remove("undelete_"+filename)
  1078.             except OSError:
  1079.                 pass
  1080. ##########BOT ON MESSAGE##############
  1081. @client.event
  1082. async def on_member_join(member):
  1083.     await joinlogs_join(member)
  1084. @client.event
  1085. async def on_member_remove(member):
  1086.     await joinlogs_remove(member)
  1087. @client.event
  1088. async def on_member_ban(member):
  1089.     await joinlogs_ban(member)
  1090. @client.event
  1091. async def on_member_update(before,after):
  1092.     await joinlogs_update(before,after)
  1093.    
  1094. @client.event
  1095. async def on_message_edit(before,after):
  1096.     await PreservePin(before,after)
  1097.     if bot.undelete == True and (before.author.id == bot.undeleteid or bot.undeleteid == ""):
  1098.         await UnDelete(before)
  1099.        
  1100. @client.event
  1101. async def on_message_delete(message):
  1102.     if bot.undelete == True and (message.author.id == bot.undeleteid or bot.undeleteid == ""):
  1103.         await UnDelete(message)
  1104.  
  1105. @client.event
  1106. async def on_message(message):
  1107.     if not bot.ready: #Race condition
  1108.         return
  1109.     #Skip entirely if its in the ignorelist
  1110.     if message.author.id in bot.ignorelist or message.channel.id in bot.ignorelist:
  1111.         return
  1112.     ##Process the prefix commands
  1113.     await MiscProc(message)
  1114.     await Suggestions(message)
  1115.     await MultiSuggestions(message)
  1116.     #await ImageBlacklist(message)
  1117.     #if (await MiscProc(message) != True) and message.content.startswith(bot.prefix):
  1118.     #   await ExclamationCommands(message)
  1119.    
  1120. ##########BOT ERROR CATCHING##########
  1121. @client.event
  1122. async def on_error(event,args="",kwargs=""):
  1123.     print("BOT EXCEPTION:")
  1124.     print(traceback.format_exc())
  1125.     try:
  1126.         with open("errors.txt", "a") as f:
  1127.             f.write("\n\n"+traceback.format_exc()+"\n\n")
  1128.     except:
  1129.         try:
  1130.             print("ERROR: NO ERRORS FILE, WRITING")
  1131.             with open("errors.txt","w") as f:
  1132.                 f.write("\n\n"+traceback.format_exc()+"\n\n")
  1133.         except:
  1134.             print("ERROR: NO FILESYSTEM ACCESS")
  1135. ##############BOT INIT################
  1136. @client.event
  1137. async def on_ready():
  1138.     print('BOT_NAME: ' + client.user.name)
  1139.     print('BOT_ID: ' + client.user.id)
  1140.     print('\n\n--VAR_ASSIGN--')
  1141.     try:
  1142.         bot.prefix = bot.config.split("prefix=")[1].split("\n")[0]
  1143.         print("BOT_PREFIX: "+bot.prefix)
  1144.         bot.ignorelist = bot.config.split("ignorelist=")[1].split("\n")[0]
  1145.         print("BOT_IGNORELIST: "+bot.ignorelist)
  1146.        
  1147.         bot.server = bot.config.split("discord_server=")[1].split("\n")[0]
  1148.         print("SERVER_ID: "+bot.server)
  1149.         bot.botchannel = bot.config.split("botchannel=")[1].split("\n")[0]
  1150.         print("BOT_CHANNEL_ID: "+bot.botchannel)       
  1151.         bot.pendingchannel = bot.config.split("pendingchannel=")[1].split("\n")[0]
  1152.         print("PENDING_CHANNEL_ID: "+bot.pendingchannel)       
  1153.         bot.ruleschannel = bot.config.split("ruleschannel=")[1].split("\n")[0]
  1154.         print("RULES_CHANNEL_ID: "+bot.ruleschannel)
  1155.                
  1156.         bot.suggestionschannel_prefix = bot.config.split("suggestionschannel_prefix=")[1].split("\n")[0]
  1157.         print("SUGGESTIONS_PREFIX "+bot.suggestionschannel_prefix)
  1158.         bot.suggestionschannel_bot = bot.config.split("suggestionschannel_bot=")[1].split("\n")[0]
  1159.         print("SUGGESTIONS_CHANNEL_BOT_ID "+bot.suggestionschannel_bot)
  1160.         bot.suggestionschannel_human = bot.config.split("suggestionschannel_human=")[1].split("\n")[0]
  1161.         print("SUGGESTIONS_CHANNEL_HUMAN_ID "+bot.suggestionschannel_human)
  1162.        
  1163.         bot.suggestionschannelstaff_bot = bot.config.split("suggestionschannelstaff_bot=")[1].split("\n")[0]
  1164.         print("SUGGESTIONS_CHANNEL_STAFF_BOT_ID "+bot.suggestionschannelstaff_bot)
  1165.         bot.suggestionschannelstaff_human = bot.config.split("suggestionschannelstaff_human=")[1].split("\n")[0]
  1166.         print("SUGGESTIONS_CHANNEL_STAFF_HUMAN_ID "+bot.suggestionschannelstaff_human)
  1167.        
  1168.         bot.stafflistchannel = bot.config.split("stafflistchannel=")[1].split("\n")[0]
  1169.         print("STAFF_LIST_CHANNEL_ID "+bot.stafflistchannel)
  1170.         bot.suggestionschannel_prefix_multi = "m--"
  1171.         bot.lastpendingreminder = None
  1172.         bot.lastpass = None
  1173.         bot.passcode = ["temp"]
  1174.         bot.modpasscode = ["temp"]
  1175.         bot.doingpreserve = False
  1176.        
  1177.         bot.joinleavechannel = bot.config.split("joinleavechannel=")[1].split("\n")[0]
  1178.         print("JOINLEAVE_CHANNEL_ID: "+bot.joinleavechannel)
  1179.     except:
  1180.         print("FAILURE TO READ CONFIG")
  1181.         print(traceback.format_exc())
  1182.         raise Exception('Incorrect config.')
  1183.     try:
  1184.         print("\n\n--DYNAMIC_VAR_INIT--")
  1185.         bot.server = client.get_server(bot.server)
  1186.         print("SERVER_NAME: "+bot.server.name)
  1187.        
  1188.         bot.botchannel = bot.server.get_channel(bot.botchannel)
  1189.         print("BOT_CHANNEL_NAME: "+bot.botchannel.name)
  1190.         bot.pendingchannel = bot.server.get_channel(bot.pendingchannel)
  1191.         print("PENDING_CHANNEL_NAME: "+bot.pendingchannel.name)
  1192.         bot.ruleschannel = bot.server.get_channel(bot.ruleschannel)
  1193.         print("RULES_CHANNEL_NAME: "+bot.ruleschannel.name)
  1194.         bot.suggestionschannel_bot = bot.server.get_channel(bot.suggestionschannel_bot)
  1195.         print("SUGGESTIONS_CHANNEL_BOT_NAME: "+bot.suggestionschannel_bot.name)
  1196.         bot.suggestionschannel_human = bot.server.get_channel(bot.suggestionschannel_human)
  1197.         print("SUGGESTIONS_CHANNEL_HUMAN_NAME: "+bot.suggestionschannel_human.name)
  1198.        
  1199.         bot.suggestionschannelstaff_bot = bot.server.get_channel(bot.suggestionschannelstaff_bot)
  1200.         print("SUGGESTIONS_CHANNEL_STAFF_BOT_NAME: "+bot.suggestionschannelstaff_bot.name)
  1201.         bot.suggestionschannelstaff_human = bot.server.get_channel(bot.suggestionschannelstaff_human)
  1202.         print("SUGGESTIONS_CHANNEL_STAFF_HUMAN_NAME: "+bot.suggestionschannelstaff_human.name)
  1203.        
  1204.         bot.stafflistchannel = bot.server.get_channel(bot.stafflistchannel)
  1205.         print("STAFF_LIST_CHANNEL_NAME: "+bot.stafflistchannel.name)
  1206.        
  1207.         bot.joinleavechannel = bot.server.get_channel(bot.joinleavechannel)
  1208.         print("JOINLEAVE_CHANNEL_NAME: "+bot.joinleavechannel.name)
  1209.        
  1210.         for i in bot.server.emojis:
  1211.             if i.name == "accepted":
  1212.                 bot.emoji_accepted = i
  1213.             if i.name == "denied":
  1214.                 bot.emoji_denied = i
  1215.         print("ADDED_EMOJI: "+bot.emoji_accepted.name)
  1216.         print("ADDED_EMOJI: "+bot.emoji_denied.name)       
  1217.         async for msg in client.logs_from(bot.pendingchannel, limit=999):
  1218.             client.messages.append(msg)
  1219.         async for msg in client.logs_from(bot.suggestionschannel_bot, limit=999):
  1220.             client.messages.append(msg)        
  1221.         async for msg in client.logs_from(bot.suggestionschannelstaff_bot, limit=999):
  1222.             client.messages.append(msg)        
  1223.         async for msg in client.logs_from(bot.server.get_channel("447760673120976905"), limit=999):
  1224.             client.messages.append(msg)
  1225.         print("PRECACHED PENDING MESSAGES")
  1226.         bot.undelete = False
  1227.         bot.undeleteid = ""
  1228.        
  1229.         bot.joinsdb = []
  1230.         await joinsdb(load=True)
  1231.         #await getjoins()
  1232.  
  1233.        
  1234.         bot.ready = True
  1235.         print("\n\n--READY--")
  1236.        
  1237.         await client.change_presence(game=discord.Game(name="Creed's Bot | "+bot.prefix+"help", type=0))
  1238.         #---ALWAYS ENSURE CODE GOES ABOVE LOOPER OR IT WILL NOT EXEC---
  1239.         await Looper()
  1240.         #await DoPurgeReminder()
  1241.     except:
  1242.         print("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
  1243.         client.close()
  1244.         client.logout()
  1245.         raise Exception("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
  1246.    
  1247. #############################END OF INITIALIZATION#############################
  1248.    
  1249. class BotVars:
  1250.     pass
  1251. if __name__ == '__main__':
  1252.     try:
  1253.         bot = BotVars()
  1254.         bot.ready = False
  1255.         #########################################################################################################################################
  1256.         ###############################################################VARIABLE INIT#############################################################
  1257.         #########################################################################################################################################
  1258.         bot.token = None
  1259.         print("--TOKEN_INIT--")
  1260.         try:
  1261.             with open("config", "r") as f:
  1262.                 bot.config = f.read()
  1263.             bot.token = bot.config.split("token=")[1].split("\n")[0]
  1264.             print("DISCORD TOKEN: " + bot.token[:int(len(bot.token)/2)]+str("*"*(int(len(bot.token)/2)-4))+bot.token[:4])
  1265.         except:
  1266.             print("FAILURE TO READ CONFIG")
  1267.             print(traceback.format_exc())
  1268.             raise Exception('Incorrect config.')
  1269.         print("\n\n--LOGIN--")
  1270.         client.run(bot.token)
  1271.     except Exception as e:
  1272.         botexception = traceback.format_exc()
  1273.         print(traceback.format_exc())
  1274.         print("EXCEPTION '" + str(e) + "'")
  1275.         try:
  1276.             client.close()
  1277.         except:
  1278.             pass
  1279.         try:
  1280.             client.logout()
  1281.         except:
  1282.             pass
  1283.         with open("exception.txt", "w") as inputfile:
  1284.             if "logout" in str(botexception):
  1285.                 inputfile.write("logout")
  1286.             else:
  1287.                 inputfile.write(str(botexception))
  1288.         print("--FAILURE--")
  1289.         time.sleep(5)
Add Comment
Please, Sign In to add comment