Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #SAVE AS: bot.py
- #This codes a messy unoptimized piece of shit
- #########################################################################################################################################
- ###############################################################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
- import math
- 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/?(?!@)))"""
- ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(math.floor(n/10)%10!=1)*(n%10<4)*n%10::4])
- 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)
- if author == None:
- return False
- 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 DoPingReminder():
- async for msg in client.logs_from(bot.pendingchannel, limit=100):
- if msg.author == client.user:
- await client.delete_message(msg)
- 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!"]
- await client.send_message(bot.pendingchannel,"<@&400824614324011008> " + random.choice(randommessages))
- bot.lastpendingreminder = datetime.utcnow()
- print("Sent Ping reminder at "+bot.lastpendingreminder.strftime(" %Y-%b-%d_%Hh%Mm%Ss"))
- async def DoPurgeReminder():
- print("PERFORMING REMINDER")
- async for msg in client.logs_from(bot.pendingchannel, limit=100):
- if msg.author == client.user:
- await client.delete_message(msg)
- 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."]
- await client.send_message(bot.pendingchannel,"<@&417941723868823584> <@&389552626137563148> " + random.choice(randommessages))
- #await client.send_message(bot.pendingchannel,"<@& --DEBUG MODE-- AUTOKICK MODULE")
- bot.lastpendingreminder = datetime.utcnow()
- async def DoPurgeReminder_GetMembers():
- try:
- if server.large:
- await client.request_offline_members(bot.server)
- except:
- pass
- pendingmembers = []
- for i in bot.server.members:
- if (datetime.utcnow()-i.joined_at).days >= 7:
- for x in i.roles:
- if x.name == "Pending":
- pendingmembers.append(i)
- break
- return pendingmembers
- async def DoPurgeReminder_MemberList():
- print("SENDING KICKED USER LIST")
- pendingmembers = await DoPurgeReminder_GetMembers()
- text = ""
- text += "__**Here's a list of people that have been in this chat for over a week:**__\n"
- for i in pendingmembers:
- text += (i.display_name + " ("+i.name+"#"+i.discriminator+") <"+i.id+">\n").encode("ascii","replace").decode("ascii","replace")
- om = await OverflowMessage(text,bot.server.owner)
- if not(om==True):
- try:
- await client.send_message(bot.server.owner, "**Error in sending member list.**")
- except:
- print("Error in sending member list")
- async def DoPurgeReminder_DirectMessage():
- #await client.send_message(bot.pendingchannel, "**Direct messaging all week-old unscreened members.**")
- pendingmembers = await DoPurgeReminder_GetMembers()
- failedtosendlist = []
- print("DIRECT MESSAGING USERS ABOUT KICK")
- for i in pendingmembers:
- try:
- 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.")
- print("Success!")
- except Exception as e:
- toofast = False
- interval = 20
- if "opening direct messages" in str(e).lower() and "fast" in str(e).lower():
- toofast = True
- else:
- print("Failed, "+str(e))
- failedtosendlist.append(i)
- if toofast:
- while toofast:
- await asyncio.sleep(interval)
- try:
- 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.")
- print("Success!")
- toofast = False
- except Exception as e2:
- if "opening direct messages" in str(e2).lower() and "fast" in str(e2).lower():
- interval *= 2
- print("Direct messages too fast, delaying for "+str(interval)+" seconds")
- txt = ""
- 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"
- for i in failedtosendlist:
- txt+=i.display_name + " ("+i.name+"#"+i.discriminator+") <"+i.id+">\n"
- txt +="```"
- om = await OverflowMessage(txt,bot.pendingchannel)
- if not(om==True):
- await client.send_message(bot.pendingchannel, "**Error in sending failed member DM list.**")
- async def DoPurgeReminder_AutoKick():
- print("AUTO KICK BEGUN")
- if bot.server.get_member(client.user.id).server_permissions.kick_members:
- #tmp_kickmsg = await client.send_message(bot.pendingchannel, "Kicking all week-old members in <#422197075531530260>.")
- print("Begun")
- pendingmembers = await DoPurgeReminder_GetMembers()
- pendingmemberslen = str(len(pendingmembers))
- for i in pendingmembers:
- try:
- await client.kick(i)
- print("Kicked")
- except:
- 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?")
- #await client.edit_message(tmp_kickmsg, pendingmemberslen+" inactive members in <#422197075531530260> have been kicked.")
- else:
- await client.send_message(bot.pendingchannel, "``Error in pending auto-kick: Permission \"Kick Members\" not granted to bot.``")
- async def PingReminder():
- if bot.lastpendingreminder == None:
- bot.lastpendingreminder = -1
- async for msg in client.logs_from(bot.pendingchannel, limit=999):
- if msg.author == client.user and msg.content.startswith("<@&"):
- bot.lastpendingreminder = msg.timestamp
- break
- if bot.lastpendingreminder == -1:
- await DoPingReminder()
- elif (datetime.utcnow()-bot.lastpendingreminder).days >= 1:
- await DoPingReminder()
- #Also do some other daily stuff
- await DoDaily()
- #if datetime.utcnow().weekday() != 0:
- # await DoPingReminder()
- #else:
- # await DoPurgeReminder()
- # await DoPurgeReminder_MemberList()
- # await DoPurgeReminder_DirectMessage()
- # await DoPurgeReminder_AutoKick()
- async def DoYuriBotSwitch():
- tmp = await client.send_message(bot.server.get_channel("389560237889159179"), "y_act"+str((datetime.utcnow().day % 2)+1))
- await client.delete_message(tmp)
- async def DoDaily():
- await DoYuriBotSwitch()
- async def joinsdb(remove=None,add=None,save=False,load=False,):
- if remove != None:
- try:
- bot.joinsdb.remove(remove.id)
- except:
- pass
- if add != None:
- bot.joinsdb.append(add.id)
- if load:
- if not os.path.isfile("data_joins.txt"):
- with open("data_joins.txt","w") as f:
- f.write("")
- with open("data_joins.txt","r") as f:
- joins = f.read()
- joins = list(filter(None,joins.split("\n")))
- bot.joinsdb = []
- for i in joins:
- bot.joinsdb.append(i)
- if save:
- with open("data_joins.txt","w") as f:
- f.write('\n'.join(bot.joinsdb))
- async def joinlogs_join(member):
- if member.bot:
- await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"**, a bot, has been added to the server.")
- else:
- if member.server.large:
- await client.request_offline_members(member.server)
- memberlen = 0
- for i in member.server.members:
- if not(i.bot):
- memberlen+=1
- await asyncio.sleep(1)
- if member.id in bot.joinsdb:
- await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has rejoined as the "+ordinal(memberlen)+" member.")
- else:
- await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has joined as the "+ordinal(memberlen)+" member.")
- await joinsdb(add=member,save=True)
- async def joinlogs_remove(member):
- if member.bot:
- await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"**, a bot, has been removed from the server.")
- else:
- if member.server.large:
- await client.request_offline_members(member.server)
- memberlen = 0
- for i in member.server.members:
- if not(i.bot):
- memberlen+=1
- await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has left as the "+ordinal(memberlen+1)+" member.")
- await joinsdb(remove=member,save=True)
- async def joinlogs_ban(member):
- if member.bot:
- await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"**, a bot, has been banned. (Could be temporary or permanant)")
- else:
- await client.send_message(bot.joinleavechannel,"**"+member.display_name+"#"+member.discriminator+"** has been banned. (Could be temporary or permanant)")
- async def joinlogs_update(before,after):
- if before.roles != after.roles:
- print("ChangeRoles")
- beforeroles = []
- for role in before.roles:
- beforeroles.append(role.name)
- afterroles = []
- for role in after.roles:
- afterroles.append(role.name)
- if "Muted" not in beforeroles and "Muted" in afterroles:
- await client.send_message(bot.joinleavechannel,"**"+after.display_name+"#"+after.discriminator+"** has been muted.")
- if "Muted" in beforeroles and "Muted" not in afterroles:
- await client.send_message(bot.joinleavechannel,"**"+after.display_name+"#"+after.discriminator+"** has been unmuted.")
- if "Pending" in beforeroles and "Pending" not in afterroles:
- await client.send_message(bot.joinleavechannel,"**"+after.display_name+"#"+after.discriminator+"** has passed screening and is now a member.")
- async def getjoins():
- async for msg in client.logs_from(bot.joinleavechannel, limit=9999):
- if msg.author.id not in bot.joinsdb:
- bot.joinsdb.append(msg.author.id)
- await joinsdb(save=True)
- async def StaffSuggestionsDaily(force=False,message=None):
- suglist = []
- if force:
- suglist.append(message)
- else:
- async for msg in client.logs_from(bot.suggestionschannelstaff_bot, limit=99):
- if msg.author == client.user and "SUGGESTION FROM" in msg.content and not "(ALL STAFF VOTES REQUIRED)" in msg.content:
- if (datetime.utcnow()-msg.timestamp).days >= 1:
- suglist.append(msg)
- for sug in suglist:
- sugstr = sug.content.split(":**__\n")[1].split("\n** **\n** **")[0].replace("__(<#442782454831382530> Suggestion)__","(<#442782454831382530> Suggestion)")
- sug_y = 0
- sug_n = 0
- sug_a = 0
- for x in sug.reactions:
- if isinstance(x.emoji, str):
- y = x.emoji
- else:
- y = x.emoji.name
- if "👍" == y:
- sug_y += x.count-1
- if "👎" == y:
- sug_n += x.count-1
- if "🇦" == y:
- sug_a += x.count-1
- try:
- await client.delete_message(sug)
- except:
- print("No remove permission")
- 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** **")
- try:
- await client.pin_message(pinmsg)
- except Exception as e:
- if "Maximum number of pins reached (50)" in traceback.format_exc():
- try:
- await client.unpin_message(sorted(await client.pins_from(message.channel),key = lambda msg: msg.timestamp.timestamp())[0])
- await client.pin_message(pinmsg)
- except:
- print("Failed to remove oldest pin")
- print(traceback.format_exc())
- else:
- print("Some misc issue in pinning")
- print(traceback.format_exc())
- async for msg in client.logs_from(bot.suggestionschannelstaff_bot, limit=99):
- if "pinned a message to this channel" in msg.system_content:
- try:
- await client.delete_message(msg)
- except:
- print("Failed to remove 'user has pinned message to this channel' message")
- print(traceback.format_exc())
- if "(<#442782454831382530> Suggestion)" in pinmsg.content:
- await client.send_message(bot.server.get_channel("442782454831382530"), pinmsg.content)
- async def SuggestionsDone(reaction,user):
- 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)):
- return
- sugstr = reaction.message.content.split(":**__\n")[1].split("\n** **\n** **")[0]
- if reaction.emoji == bot.emoji_accepted:
- sugstr = "** **\n** **\n"+str(bot.emoji_accepted)+"__**Accepted by "+bot.server.get_member(user.id).display_name+":**__"+str(bot.emoji_accepted)+"\n"+sugstr
- elif reaction.emoji == bot.emoji_denied:
- sugstr = "** **\n** **\n"+str(bot.emoji_denied)+"__**Denied by "+bot.server.get_member(user.id).display_name+":**__"+str(bot.emoji_denied)+"\n"+sugstr
- pinmsg = await client.send_message(reaction.message.channel, sugstr)
- try:
- await client.pin_message(pinmsg)
- except Exception as e:
- if "Maximum number of pins reached (50)" in traceback.format_exc():
- try:
- await client.unpin_message(sorted(await client.pins_from(reaction.message.channel),key = lambda msg: msg.timestamp.timestamp())[0])
- await client.pin_message(pinmsg)
- except:
- print("Failed to remove oldest pin")
- print(traceback.format_exc())
- else:
- print("Some misc issue in pinning")
- print(traceback.format_exc())
- async for msg in client.logs_from(reaction.message.channel, limit=99):
- if "pinned a message to this channel" in msg.system_content:
- try:
- await client.delete_message(msg)
- except:
- print("Failed to remove 'user has pinned message to this channel' message")
- print(traceback.format_exc())
- try:
- await client.delete_message(reaction.message)
- except:
- print("No remove permission")
- #Q: Will this work? A:https://www.youtube.com/watch?v=DNeikvoqQ-s
- async def reaction_screening(reaction,user):
- if user.id == client.user.id or reaction.message.channel != bot.pendingchannel:
- return
- if not(await IsStaff(reaction.message,user)):
- try:
- await client.send_message(user,"Please do not touch the ratings in the pending channel. They are staff only.")
- except:
- pass
- await client.clear_reactions(reaction.message)
- await client.add_reaction(reaction.message,bot.emoji_accepted)
- await client.add_reaction(reaction.message,bot.emoji_denied)
- else:
- print("USER BEING PROMOTED: "+reaction.message.content.split("<@")[1].split(">")[0])
- promoteuser = bot.server.get_member(reaction.message.content.split("<@")[1].split(">")[0])
- if reaction.emoji == bot.emoji_accepted:
- for i in bot.server.roles:
- if i.name=="Member":
- try:
- await client.replace_roles(promoteuser,i)
- except Exception as e:
- await client.send_message(bot.pendingchannel,"Failed to promote <@"+promoteuser.id+"> to member, insufficient permissions. Is user pending without any other roles?")
- print(str(e))
- await client.clear_reactions(reaction.message)
- await client.add_reaction(reaction.message,bot.emoji_accepted)
- await client.add_reaction(reaction.message,bot.emoji_denied)
- return
- 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***!")
- try:
- await client.delete_message(reaction.message)
- except:
- pass
- elif reaction.emoji == bot.emoji_denied:
- await client.send_message(bot.pendingchannel,"<@"+promoteuser.id+">, you have been denied access to the server outside of <#422197075531530260>.")
- try:
- await client.delete_message(reaction.message)
- except:
- pass
- else:
- await client.clear_reactions(reaction.message)
- await client.add_reaction(pacappmsg,bot.emoji_accepted)
- await client.add_reaction(pacappmsg,bot.emoji_denied)
- async def reaction_suggestions(reaction,user):
- if reaction.message.channel == bot.suggestionschannel_bot:
- botchannel = bot.suggestionschannel_bot
- isstaff = False
- elif reaction.message.channel == bot.suggestionschannelstaff_bot:
- botchannel = bot.suggestionschannelstaff_bot
- isstaff = True
- else:
- return
- reaction_userlist = []
- for messagereaction in reaction.message.reactions:
- cur_reactionuserlist = await client.get_reaction_users(messagereaction, limit=99)
- for msguser in cur_reactionuserlist:
- reaction_userlist.append([msguser,messagereaction.emoji])
- for item in reaction_userlist:
- if item[0] == user and item[1] == reaction.emoji:
- continue
- if item[0] == user:
- await client.remove_reaction(reaction.message,item[1],bot.server.get_member(item[0].id))
- break
- async def reaction_staffsuggestionsoverflow(reaction,user):
- if reaction.message.channel != bot.suggestionschannelstaff_bot:
- return
- voters = 0
- votey = 0
- voten = 0
- votea = 0
- for messagereaction in reaction.message.reactions:
- cur_reactionuserlist = await client.get_reaction_users(messagereaction, limit=99)
- for msguser in cur_reactionuserlist:
- if msguser != client.user:
- voters += 1
- if isinstance(messagereaction.emoji, str):
- y = messagereaction.emoji
- else:
- y = messagereaction.emoji.name
- if "👍" == y:
- votey+= voters
- if "👎" == y:
- voten+= voters
- if "🇦" == y:
- votea+= voters
- voters = 0
- voters = votey+voten+votea
- stafflist = 0
- async for msg in client.logs_from(bot.stafflistchannel, limit=99):
- stafflist+=len(msg.mentions)
- if voters>=stafflist:
- await StaffSuggestionsDaily(True,reaction.message)
- if not("(ALL STAFF VOTES REQUIRED)" in reaction.message.content):
- staffthres = math.floor(((stafflist-votea)/2))
- print("Staff Threshold: "+str(staffthres))
- print("Staff voted yes: "+str(votey))
- print("Staff voted no: "+str(voten))
- if votey > staffthres or voten > staffthres:
- print("Majority Roleover")
- await StaffSuggestionsDaily(True,reaction.message)
- @client.event
- async def on_reaction_add(reaction, user):
- if user == client.user:
- return
- await reaction_screening(reaction,user)
- await reaction_suggestions(reaction,user)
- await reaction_staffsuggestionsoverflow(reaction,user)
- await SuggestionsDone(reaction,user)
- async def CheckForPasscode(message):
- if message.channel != bot.pendingchannel:
- return
- ispending = False
- for i in bot.server.get_member(message.author.id).roles:
- if i.name == "Pending":
- ispending = True
- break
- if not(ispending):
- return
- haspasscode = True
- hasmodpasscode = True
- for i in bot.passcode:
- if not(i in message.content.lower()):
- haspasscode = False
- break
- for i in bot.modpasscode:
- if not(i in message.content.lower()):
- hasmodpasscode = False
- break
- if haspasscode:
- tmpapprove=await client.send_message(bot.pendingchannel,"<@"+message.author.id+"> has entered the correct password for screening. Please stand by for staff approval.")
- await client.add_reaction(tmpapprove,bot.emoji_accepted)
- await client.add_reaction(tmpapprove,bot.emoji_denied)
- try:
- await client.delete_message(message)
- except:
- print("No remove permission")
- elif hasmodpasscode:
- tmpapprove=await client.send_message(bot.pendingchannel,"<@"+message.author.id+"> has entered the mod-only password and has been assigned the \"Mod Access\" role.")
- print("USER BEING PROMOTED TO MOD: "+message.author.id)
- promoteuser = bot.server.get_member(message.author.id)
- for i in bot.server.roles:
- if i.name=="Mod Access":
- try:
- await client.replace_roles(promoteuser,i)
- except Exception as e:
- await client.send_message(bot.pendingchannel,"Failed to promote <@"+promoteuser.id+"> to Mod Access, insufficient permissions. Is user pending without any other roles?")
- print(str(e))
- try:
- await client.delete_message(tmpapprove)
- except:
- pass
- break
- 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!")
- try:
- await client.delete_message(message)
- except:
- print("No remove permission")
- async def PreservePin(before,after):
- if not(before.pinned) and after.pinned and not(bot.doingpreserve):
- message = after
- try:
- pinlist = sorted(await client.pins_from(message.channel),key = lambda msg: msg.timestamp.timestamp(),reverse=True) #Oldest first
- bot.doingpreserve = True
- for pin in pinlist:
- if pin.content.startswith("=="):
- await client.unpin_message(pin)
- await client.pin_message(pin)
- if pin == pinlist[-1]:
- bot.doingpreserve = False
- async for msg in client.logs_from(message.channel, limit=99):
- 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):
- try:
- await client.delete_message(msg)
- except:
- pass
- except Exception as e:
- print(traceback.format_exc())
- bot.doingpreserve = False
- async def DoPassOfTheDay():
- async for msg in client.logs_from(bot.ruleschannel, limit=999):
- if msg.author == client.user and msg.content.startswith("Password for "):
- await client.delete_message(msg)
- randomwords = ["lane","dash","hall","pit","folk","swarm","trail","spell","fast","offer","great","good","nice","line","sport","old","new","park","red","blue","green","white","black"]
- bot.passcode = []
- bot.modpasscode = []
- for passcode in [bot.passcode,bot.modpasscode]:
- for i in range(random.randrange(1,3)):
- passcode.append(random.choice(randomwords))
- randomwords.remove(passcode[-1])
- 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.')
- 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.')
- bot.lastpass = datetime.utcnow()
- print("New password set at "+bot.lastpendingreminder.strftime(" %Y-%b-%d_%Hh%Mm%Ss"))
- async def PassOfTheDay():
- if bot.lastpass == None:
- bot.lastpass = -1
- async for msg in client.logs_from(bot.ruleschannel, limit=999):
- if msg.author == client.user:
- if msg.content.startswith('Password for the entire community server:'):
- bot.passcode = msg.content.split('"')[1].split('"')[0].split(" ")
- print("PASSCODE SET TO: "+' '.join(bot.passcode))
- bot.lastpass = msg.timestamp
- continue
- if msg.content.startswith('Password for Just Yuri mod access:'):
- bot.modpasscode = msg.content.split('"')[1].split('"')[0].split(" ")
- print("MOD PASSCODE SET TO: "+' '.join(bot.modpasscode))
- bot.lastpass = msg.timestamp
- continue
- if bot.lastpass == -1:
- await DoPassOfTheDay()
- if (datetime.utcnow()-bot.lastpass).days >= 1:
- await DoPassOfTheDay()
- async def FindImages(message):
- dl_urls = []
- dled_urls = []
- if len(message.attachments) != 0:
- for att in message.attachments:
- dl_urls.append(att["url"])
- if len(re.findall(URL_REGEX,message.content)) !=0: #URL
- for urlfound in re.findall(URL_REGEX,message.content):
- dl_urls.append(urlfound)
- for urlfound in dl_urls:
- if mimetypes.guess_type(urlfound)[0] != None and "image" in mimetypes.guess_type(urlfound)[0]:
- dled_urls.append(urlfound)
- if dled_urls == []:
- return None
- else:
- return dled_urls
- async def Suggestions(message):
- 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):
- if message.channel == bot.suggestionschannel_human:
- humanchannel = bot.suggestionschannel_human
- botchannel = bot.suggestionschannel_bot
- isstaff = False
- elif message.channel.id == "392835203447390208":
- humanchannel = bot.server.get_channel("392835203447390208")
- botchannel = bot.server.get_channel("447760673120976905")
- isstaff = False
- elif message.channel == bot.suggestionschannelstaff_human or message.channel.id =="442782454831382530":
- humanchannel = bot.suggestionschannelstaff_human
- botchannel = bot.suggestionschannelstaff_bot
- isstaff = True
- message.content=message.content.replace(bot.suggestionschannel_prefix,"",1)
- if message.content.startswith("<@") or message.content.startswith("<@!"):
- if message.content.startswith("<@!"):
- prefix = "<@!"
- else:
- prefix = "<@"
- authorid = message.content.split(prefix,1)[1].split(">",1)[0]
- mention = prefix+authorid+">"
- suggestion = message.content.replace(mention,"").lstrip()
- else:
- suggestion = message.content
- try:
- name = message.author.id
- mention = "<@!"+name+">"
- except Exception as e:
- print(str(e))
- name = "Unknown User"
- mention = "@"+name
- await client.send_message(message.channel, "To see and vote on **"+message.author.display_name+"**'s idea, please go to <#"+botchannel.id+">!")
- sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n{2}{1}\n** **\n** **"
- if message.channel.id == "442782454831382530":
- sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n{2}__(<#442782454831382530> Suggestion)__\n{1}\n** **\n** **"
- if message.content.startswith("--") and isstaff:
- suggestion = suggestion.replace("--","",1)
- allvotes = "__(ALL STAFF VOTES REQUIRED)__\n"
- else:
- allvotes = ""
- tmp_sug = await client.send_message(botchannel, sugstr.format(message.author.display_name+" ("+message.author.name+"#"+message.author.discriminator+")",suggestion,allvotes))
- print("Suggestion ID:" + tmp_sug.id)
- if len(message.attachments) != 0:
- for i in message.attachments:
- try:
- async with aiohttp.ClientSession() as cs:
- async with cs.get(i["url"]) as r:
- try:
- content = await r.content.read()
- with open(i["url"].split("/")[-1],"wb") as f:
- f.write(content)
- except:
- pass
- tmp_sug = await client.send_file(botchannel, i["url"].split("/")[-1])
- os.remove(i["url"].split("/")[-1])
- except:
- pass
- await asyncio.sleep(0.5)
- await client.add_reaction(tmp_sug,'\N{THUMBS UP SIGN}')
- await asyncio.sleep(0.5)
- await client.add_reaction(tmp_sug,'\N{THUMBS DOWN SIGN}')
- await asyncio.sleep(0.5)
- if isstaff:
- await client.add_reaction(tmp_sug,'🇦')
- else:
- await client.add_reaction(tmp_sug,'🇳')
- if message.channel.id != "442782454831382530":
- try:
- await client.delete_message(message)
- except:
- print("No remove permission")
- return True
- async def CMD_sugfix(message):
- if message.author.id != "380793206033612809":
- return
- if message.content.lower().startswith(bot.prefix+"sugfix"):
- fixid = message.content.lower().replace(bot.prefix+"sugfix","").strip()
- try:
- await client.delete_message(message)
- except:
- print("No remove permission")
- for i in ["447760673120976905","389552930639839244"]:
- try:
- async for msg in client.logs_from(bot.server.get_channel(i), limit=999):
- if msg.id == fixid:
- await client.clear_reactions(msg)
- await asyncio.sleep(0.5)
- await client.add_reaction(msg,'\N{THUMBS UP SIGN}')
- await asyncio.sleep(0.5)
- await client.add_reaction(msg,'\N{THUMBS DOWN SIGN}')
- await asyncio.sleep(0.5)
- await client.add_reaction(msg,'🇳')
- return
- except:
- pass
- async def MultiSuggestions(message):
- 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):
- if message.channel == bot.suggestionschannel_human:
- humanchannel = bot.suggestionschannel_human
- botchannel = bot.suggestionschannel_bot
- isstaff = False
- elif message.channel.id == "392835203447390208":
- humanchannel = bot.server.get_channel("392835203447390208")
- botchannel = bot.server.get_channel("447760673120976905")
- isstaff = False
- elif message.channel == bot.suggestionschannelstaff_human or message.channel.id =="442782454831382530":
- humanchannel = bot.suggestionschannelstaff_human
- botchannel = bot.suggestionschannelstaff_bot
- isstaff = True
- if isstaff:
- return
- message.content=message.content.replace(bot.suggestionschannel_prefix_multi,"",1)
- items = message.content.split("\n")
- precursor = items.pop(0)
- if len(items) > 10:
- await client.send_message(message.channel, "More than 10 suggestions are not supported, <@"+message.author.id+">.")
- return
- suggestion = message.content
- sugmodstr = precursor+"\n"
- for i in range(len(items)):
- sugmodstr+=u'{0}\u20e3'.format(str(i)) + " " +items[i]+"\n"
- await client.send_message(message.channel, "To see and vote on **"+message.author.display_name+"**'s idea, please go to <#"+botchannel.id+">!")
- sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n{1}\n** **\n** **"
- if message.channel.id == "442782454831382530":
- sugstr = "** **\n** **\n__**SUGGESTION FROM {0}:**__\n__(<#442782454831382530> Suggestion)__\n{1}\n** **\n** **"
- tmp_sug = await client.send_message(botchannel, sugstr.format(message.author.display_name+" ("+message.author.name+"#"+message.author.discriminator+")",sugmodstr))
- print("Suggestion ID:" + tmp_sug.id)
- if len(message.attachments) != 0:
- for i in message.attachments:
- try:
- async with aiohttp.ClientSession() as cs:
- async with cs.get(i["url"]) as r:
- try:
- content = await r.content.read()
- with open(i["url"].split("/")[-1],"wb") as f:
- f.write(content)
- except:
- pass
- tmp_sug = await client.send_file(botchannel, i["url"].split("/")[-1])
- os.remove(i["url"].split("/")[-1])
- except:
- pass
- for i in range(len(items)):
- await client.add_reaction(tmp_sug,u'{0}\u20e3'.format(str(i)))
- if isstaff:
- await client.add_reaction(tmp_sug,'🇦')
- else:
- await client.add_reaction(tmp_sug,'🇳')
- if message.channel.id != "442782454831382530":
- try:
- await client.delete_message(message)
- except:
- print("No remove permission")
- return True
- async def Looper():
- while True:
- await PingReminder()
- await PassOfTheDay()
- await StaffSuggestionsDaily()
- await asyncio.sleep(3)
- async def AntiSpam(message):
- imglist = await FindImages(message)
- if imglist != None:
- return
- nw = datetime.utcnow()
- count = 0
- msgs = [message]
- async for msg in client.logs_from(message.channel, limit=10):
- if msg.author == message.author:
- if (nw-msg.timestamp).seconds <=3:
- count +=1
- msgs.append(msg)
- if count >=4:
- tmp_antispam = await client.send_message(message.channel,"<@"+message.author.id+">, do not spam messages. This is a punishable infraction.")
- for msg in msgs:
- try:
- await client.delete_message(msg)
- except:
- pass
- await asyncio.sleep(3)
- await client.delete_message(tmp_antispam)
- return True
- return False
- async def AntiSpamImage(message):
- if message.channel.id in ["389588277222703104"]: #Art-and-photography
- return
- imglist = await FindImages(message)
- if imglist == None:
- return
- #print(len(imglist))
- if len(imglist) >3:
- tmp_imgantispam_multi = await client.send_message(message.channel,"<@"+message.author.id+">, you may only post three images at a time in this channel.")
- try:
- await client.delete_message(message)
- except:
- pass
- await asyncio.sleep(10)
- await client.delete_message(tmp_imgantispam_multi)
- return True
- elif len(imglist) >1:
- testlist = []
- imageduplicate = False
- for url in imglist:
- for urllisted in testlist:
- if urllisted == url:
- imageduplicate = True
- break
- testlist.append(url)
- if imageduplicate:
- 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.")
- try:
- await client.delete_message(message)
- except:
- pass
- await asyncio.sleep(10)
- await client.delete_message(tmp_imgantispam_multi_same)
- nw = datetime.utcnow()
- singleantispam = False
- waittime = 0
- async for msg in client.logs_from(message.channel, limit=50):
- if msg.author == message.author and message.timestamp != msg.timestamp:
- imglist_sub = await FindImages(msg)
- if imglist_sub != None and (nw-msg.timestamp).seconds <30:
- waittime = math.ceil(30-((nw-msg.timestamp).seconds))
- singleantispam = True
- break
- if singleantispam:
- 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)")
- try:
- await client.delete_message(message)
- except:
- pass
- await asyncio.sleep(waittime)
- await client.delete_message(tmp_imgantispam_single)
- return True
- return False
- async def AntiEXE(message):
- if len(message.attachments) != 0:
- for i in message.attachments:
- if i["url"].endswith("exe"):
- 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.")
- await client.delete_message(message)
- if len(re.findall(URL_REGEX,message.content)) !=0: #URL
- for i in re.findall(URL_REGEX,message.content):
- if i.endswith(".exe"):
- 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.")
- await client.delete_message(message)
- async def AntiInvite(message):
- if len(re.findall(URL_REGEX,message.content)) !=0: #URL
- for i in re.findall(URL_REGEX,message.content):
- if "discord.gg" in i or "discordapp.com/invite/" in i:
- await client.send_message(message.channel,"<@"+message.author.id+">, sending discord invites is not allowed in <#397087061846261761>. Please use <#400113786457161728>.")
- await client.delete_message(message)
- async def CMD_clearpin(message):
- if message.content.lower().startswith("/clearpin") or message.content.lower().startswith("/pinclear"):
- if await IsStaff(message):
- try:
- pindel = sorted(await client.pins_from(message.channel),key = lambda msg: msg.timestamp.timestamp())[0]
- pinmsg = "```\n"
- pinmsg+=pindel.timestamp.strftime("%Y-%b-%d_%Hh%Mm%Ss")+"\n"
- pinmsg+=pindel.author.display_name+"\n"
- pinmsg+="("+pindel.author.name+"#"+pindel.author.discriminator+")\n"
- pinmsg+=pindel.content
- pinimgs = await FindImages(pindel)
- if pinimgs != None:
- pinmsg+="\n"
- for i in pinimgs:
- pinmsg+=i
- if i != pinimgs[-1]:
- pinmsg+="\n"
- pinmsg +="```"
- await client.unpin_message(pindel)
- await client.send_message(message.channel,"Message unpinned:\n"+pinmsg)
- await client.send_message(message.channel,"<@"+message.author.id+"> has cleared a pinned message slot.")
- except Exception as e:
- await client.send_message(message.channel,"<@"+message.author.id+"> Failure!\n```"+str(e)+"```")
- print("Failed to remove oldest pin")
- print(traceback.format_exc())
- await client.delete_message(message)
- async def CMD_raid(message):
- if message.content.startswith("001"):
- staffchnl = bot.server.get_channel("396470791920680971")
- athr = message.author
- cnt = message.content.replace("001 ","").replace("001","")
- try:
- await client.delete_message(message)
- except:
- pass
- ments = "<@&389552626137563148>" #Mods
- for i in range(2):
- tmp_raid = await client.send_message(staffchnl,ments+" Code 001") #mods
- await client.delete_message(tmp_raid)
- await client.send_message(staffchnl,ments+"\n__<@"+athr.id+"> has activated code 001:__\n``"+cnt+"``")
- try:
- await client.send_message(athr,"__You have activated code 001:__\n``"+cnt+"``")
- except:
- pass
- async def CMD_suicide(message):
- if message.content.startswith("002"):
- staffchnl = bot.server.get_channel("396470791920680971")
- athr = message.author
- cnt = message.content.replace("002 ","").replace("002","")
- try:
- await client.delete_message(message)
- except:
- pass
- ments = "<@&389552626137563148> <@&417941723868823584> <@&428125906729566218>" #Mods admins couns
- for i in range(2):
- tmp_raid = await client.send_message(staffchnl,ments+" Code 002")
- await client.delete_message(tmp_raid)
- await client.send_message(staffchnl,ments+"\n__<@"+athr.id+"> has activated code 002:__\n``"+cnt+"``")
- try:
- await client.send_message(athr,"__You have activated code 002:__\n``"+cnt+"``")
- except:
- pass
- async def AntiBotCmds(message):
- if message.author.bot and message.channel != bot.botchannel and message.channel.id != "442782454831382530" and message.channel.id != "400113786457161728":
- if (message.author.id == "159985870458322944" or message.author.id == "172002275412279296") and "level" in message.content:
- return #Its just the stupid level up stuff
- async for msg in client.logs_from(message.channel, limit=10):
- isstaff = await IsStaff(msg)
- if msg.content.startswith(("!","'","+",".","?","t!","/")) and not(isstaff):
- tmp = await client.send_message(message.channel,"<@"+msg.author.id+">, please use <#"+bot.botchannel.id+">.")
- try:
- await client.delete_message(message)
- await client.delete_message(msg)
- except:
- print("Unable to delete")
- return True
- async def CMD_help(message):
- if message.content.lower() == bot.prefix+"helpmulti":
- 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"
- try:
- await client.send_message(message.author,helpstr)
- except:
- helpstr = "<@"+message.author.id+">\n"+helpstr
- await client.send_message(bot.botchannel,helpstr)
- return
- if not(message.content.lower().startswith(bot.prefix+"help")):
- return
- if await IsStaff(message) or message.author.id == "380793206033612809":
- helpmsg = ""
- helpmsg += "**__Staff Commands__\n\n**"
- helpmsg += "`/restartbot`\nYou ever just fucking smack a broken machine and it starts working again? This is the equivalent.\n\n"
- 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"
- 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"
- helpmsg += "`/nuke`\nRemoves most recent cBot commands in the channel.\n\n"
- helpmsg += "`/secnuke`\nIn the <#442782454831382530> chat, all \"Non-Relevant\" messages are cleaned up. \n\n"
- helpmsg += "`/undelete`\nToggles the \"undeleter\" function globally.\n\n"
- helpmsg += "`/undelete @user`\nIf undeleter is off, turns on undelete on a specific user.\n\n"
- helpmsg += "`--somesuggestiontextandorimage` in <#396470791920680971> or <#442782454831382530>\nPosts a suggestion to <#433373031013023775>.\n\n"
- 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"
- helpmsg += "** **\n ** **\n ** **\n"
- om = await OverflowMessage(helpmsg,message.author)
- if not(om==True):
- try:
- await client.send_message(bot.botchannel, "<@"+message.author.id+">")
- om = await OverflowMessage(helpmsg,bot.botchannel)
- if not(om==True):
- raise
- except:
- await client.send_message(message.channel, "**Error in sending message.**")
- return
- helpmsg = ""
- helpmsg += "**__User Commands__\n\n**"
- helpmsg += "``--somesuggestiontextandorimage`` in <#415652708591337503> or <#392835203447390208>\nPosts a suggestion to <#389552930639839244> or <#447760673120976905>\n\n"
- 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"
- helpmsg += "**__Fun Commands__\n\n**"
- helpmsg += "`/namecount somenamehere`\n1,2,3,4, how many somenamehere's are in my store?\n*(I knooooow you're stealing)*\n\n"
- helpmsg += "`/gaymode`\nCalls a random person a gay on a scale of \"a bit\" to \"Super fuckin\"*\n\n"
- helpmsg += "`/marry @user`\nPropose to a user\n\n"
- helpmsg += "`/divorce @user`\nDivorce a user\n\n"
- helpmsg += "`/proposals [@user]`\nShow who has proposed to you/@user\n\n"
- helpmsg += "`/marriages [@user]`\nShow who you/@user are married to\n\n"
- #helpmsg += "`/owo somegayowoshithere`\nMimic the gay owolord (General only)*\n\n"
- helpmsg += "** **\n ** **\n ** **\n"
- om = await OverflowMessage(helpmsg,message.author)
- if not(om==True):
- try:
- await client.send_message(bot.botchannel, "<@"+message.author.id+">")
- om = await OverflowMessage(helpmsg,bot.botchannel)
- if not(om==True):
- raise
- except:
- await client.send_message(message.channel, "**Error in sending message.**")
- return
- await TryDelete(message)
- async def CMD_undelete(message):
- if message.content.startswith(bot.prefix+"undelete"):
- await client.delete_message(message)
- bot.undeleteid = message.content.lower().split("<@")[1].split(">")[0].replace("!","")
- if await IsStaff(message) or message.author.id == "380793206033612809":
- bot.undelete = not(bot.undelete)
- await client.send_message(message.channel, "Undeleter: {status}".format(status="Active" if bot.undelete else "Inactive"))
- async def CMD_forge(message):
- if message.content.startswith(bot.prefix+"forge") and message.author.id == "380793206033612809":
- await client.delete_message(message)
- await client.send_message(message.channel,message.content.replace(bot.prefix+"forge","",1))
- async def MiscProc(message):
- if message.channel.id not in ["397087352633294848","413129174853746708","413584030928338945"]:
- await AntiBotCmds(message)
- if message.author != client.user:
- await CheckForPasscode(message)
- await AntiEXE(message)
- await CMD_clearpin(message)
- await CMD_raid(message)
- await CMD_suicide(message)
- await CMD_help(message)
- await CMD_sugfix(message)
- await CMD_undelete(message)
- await CMD_forge(message)
- 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
- await AntiSpam(message)
- await AntiSpamImage(message)
- await AntiInvite(message)
- #Pending notifier
- ##############################################################################################################
- ##############################################################################################################
- ##########################################END OF !FUNCTIONS###################################################
- ##############################################################################################################
- async def UnDelete(message):
- if message.content != "":
- await client.send_message(message.channel, "__**UNDELETER**__\n__{authorshit}__\n{msg}".format(authorshit=message.author.display_name,msg=message.content))
- foundimgs = await FindImages(message)
- if foundimgs != None:
- foundimgs_names = []
- for img in foundimgs:
- filename = img.rsplit("/",1)[1]
- async with aiohttp.ClientSession() as cs:
- async with cs.get(img) as r:
- try:
- content = await r.content.read()
- imgb = Image.open(io.BytesIO(content))
- imgb.save("undelete_"+filename)
- foundimgs_names.append("undelete_"+filename)
- except:
- print(traceback.format_exc())
- print("Undelete Failure")
- for img in foundimgs_names:
- await client.send_message(message.channel, "__**UNDELETER**__\n__{authorshit}__".format(authorshit=message.author.display_name))
- await client.send_file(message.channel,"undelete_"+filename)
- try:
- os.remove("undelete_"+filename)
- except OSError:
- pass
- ##########BOT ON MESSAGE##############
- @client.event
- async def on_member_join(member):
- await joinlogs_join(member)
- @client.event
- async def on_member_remove(member):
- await joinlogs_remove(member)
- @client.event
- async def on_member_ban(member):
- await joinlogs_ban(member)
- @client.event
- async def on_member_update(before,after):
- await joinlogs_update(before,after)
- @client.event
- async def on_message_edit(before,after):
- await PreservePin(before,after)
- if bot.undelete == True and (before.author.id == bot.undeleteid or bot.undeleteid == ""):
- await UnDelete(before)
- @client.event
- async def on_message_delete(message):
- if bot.undelete == True and (message.author.id == bot.undeleteid or bot.undeleteid == ""):
- await UnDelete(message)
- @client.event
- async def on_message(message):
- if not bot.ready: #Race condition
- return
- #Skip entirely if its in the ignorelist
- if message.author.id in bot.ignorelist or message.channel.id in bot.ignorelist:
- return
- ##Process the prefix commands
- await MiscProc(message)
- await Suggestions(message)
- await MultiSuggestions(message)
- #await ImageBlacklist(message)
- #if (await MiscProc(message) != True) and message.content.startswith(bot.prefix):
- # await ExclamationCommands(message)
- ##########BOT ERROR CATCHING##########
- @client.event
- async def on_error(event,args="",kwargs=""):
- print("BOT EXCEPTION:")
- print(traceback.format_exc())
- try:
- with open("errors.txt", "a") as f:
- f.write("\n\n"+traceback.format_exc()+"\n\n")
- except:
- try:
- print("ERROR: NO ERRORS FILE, WRITING")
- with open("errors.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.botchannel = bot.config.split("botchannel=")[1].split("\n")[0]
- print("BOT_CHANNEL_ID: "+bot.botchannel)
- bot.pendingchannel = bot.config.split("pendingchannel=")[1].split("\n")[0]
- print("PENDING_CHANNEL_ID: "+bot.pendingchannel)
- bot.ruleschannel = bot.config.split("ruleschannel=")[1].split("\n")[0]
- print("RULES_CHANNEL_ID: "+bot.ruleschannel)
- bot.suggestionschannel_prefix = bot.config.split("suggestionschannel_prefix=")[1].split("\n")[0]
- print("SUGGESTIONS_PREFIX "+bot.suggestionschannel_prefix)
- bot.suggestionschannel_bot = bot.config.split("suggestionschannel_bot=")[1].split("\n")[0]
- print("SUGGESTIONS_CHANNEL_BOT_ID "+bot.suggestionschannel_bot)
- bot.suggestionschannel_human = bot.config.split("suggestionschannel_human=")[1].split("\n")[0]
- print("SUGGESTIONS_CHANNEL_HUMAN_ID "+bot.suggestionschannel_human)
- bot.suggestionschannelstaff_bot = bot.config.split("suggestionschannelstaff_bot=")[1].split("\n")[0]
- print("SUGGESTIONS_CHANNEL_STAFF_BOT_ID "+bot.suggestionschannelstaff_bot)
- bot.suggestionschannelstaff_human = bot.config.split("suggestionschannelstaff_human=")[1].split("\n")[0]
- print("SUGGESTIONS_CHANNEL_STAFF_HUMAN_ID "+bot.suggestionschannelstaff_human)
- bot.stafflistchannel = bot.config.split("stafflistchannel=")[1].split("\n")[0]
- print("STAFF_LIST_CHANNEL_ID "+bot.stafflistchannel)
- bot.suggestionschannel_prefix_multi = "m--"
- bot.lastpendingreminder = None
- bot.lastpass = None
- bot.passcode = ["temp"]
- bot.modpasscode = ["temp"]
- bot.doingpreserve = False
- bot.joinleavechannel = bot.config.split("joinleavechannel=")[1].split("\n")[0]
- print("JOINLEAVE_CHANNEL_ID: "+bot.joinleavechannel)
- 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.botchannel = bot.server.get_channel(bot.botchannel)
- print("BOT_CHANNEL_NAME: "+bot.botchannel.name)
- bot.pendingchannel = bot.server.get_channel(bot.pendingchannel)
- print("PENDING_CHANNEL_NAME: "+bot.pendingchannel.name)
- bot.ruleschannel = bot.server.get_channel(bot.ruleschannel)
- print("RULES_CHANNEL_NAME: "+bot.ruleschannel.name)
- bot.suggestionschannel_bot = bot.server.get_channel(bot.suggestionschannel_bot)
- print("SUGGESTIONS_CHANNEL_BOT_NAME: "+bot.suggestionschannel_bot.name)
- bot.suggestionschannel_human = bot.server.get_channel(bot.suggestionschannel_human)
- print("SUGGESTIONS_CHANNEL_HUMAN_NAME: "+bot.suggestionschannel_human.name)
- bot.suggestionschannelstaff_bot = bot.server.get_channel(bot.suggestionschannelstaff_bot)
- print("SUGGESTIONS_CHANNEL_STAFF_BOT_NAME: "+bot.suggestionschannelstaff_bot.name)
- bot.suggestionschannelstaff_human = bot.server.get_channel(bot.suggestionschannelstaff_human)
- print("SUGGESTIONS_CHANNEL_STAFF_HUMAN_NAME: "+bot.suggestionschannelstaff_human.name)
- bot.stafflistchannel = bot.server.get_channel(bot.stafflistchannel)
- print("STAFF_LIST_CHANNEL_NAME: "+bot.stafflistchannel.name)
- bot.joinleavechannel = bot.server.get_channel(bot.joinleavechannel)
- print("JOINLEAVE_CHANNEL_NAME: "+bot.joinleavechannel.name)
- for i in bot.server.emojis:
- if i.name == "accepted":
- bot.emoji_accepted = i
- if i.name == "denied":
- bot.emoji_denied = i
- print("ADDED_EMOJI: "+bot.emoji_accepted.name)
- print("ADDED_EMOJI: "+bot.emoji_denied.name)
- async for msg in client.logs_from(bot.pendingchannel, limit=999):
- client.messages.append(msg)
- async for msg in client.logs_from(bot.suggestionschannel_bot, limit=999):
- client.messages.append(msg)
- async for msg in client.logs_from(bot.suggestionschannelstaff_bot, limit=999):
- client.messages.append(msg)
- async for msg in client.logs_from(bot.server.get_channel("447760673120976905"), limit=999):
- client.messages.append(msg)
- print("PRECACHED PENDING MESSAGES")
- bot.undelete = False
- bot.undeleteid = ""
- bot.joinsdb = []
- await joinsdb(load=True)
- #await getjoins()
- bot.ready = True
- print("\n\n--READY--")
- await client.change_presence(game=discord.Game(name="Creed's Bot | "+bot.prefix+"help", type=0))
- #---ALWAYS ENSURE CODE GOES ABOVE LOOPER OR IT WILL NOT EXEC---
- await Looper()
- #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)
Add Comment
Please, Sign In to add comment