CreedWN

bot_fun.py

Jun 29th, 2018
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 22.84 KB | None | 0 0
  1. #SAVE AS: bot_fun.py
  2. #########################################################################################################################################
  3. ###############################################################MODULE IMPORT#############################################################
  4. #########################################################################################################################################
  5. import json
  6. from datetime import datetime
  7. import sys
  8. import os
  9. import base64
  10. import mimetypes
  11. import time
  12. import random
  13. import io
  14. import re
  15. import traceback
  16.  
  17. import discord #pip install -U discord.py[voice]
  18. import asyncio #pip install -U discord.py[voice]
  19. import aiohttp #pip install -U discord.py[voice]
  20. import numpy as np #pip install opencv-python
  21. from discord.ext import commands #pip install -U discord.py[voice]
  22. from googleapiclient.discovery import build #pip install --upgrade google-api-python-client
  23. from apiclient.errors import HttpError #pip install --upgrade google-api-python-client
  24. from oauth2client.tools import argparser #pip install --upgrade oauth2client
  25.  
  26. try:
  27.     from PIL import Image #pip install PIL
  28. except:
  29.     import Image #pip install Image
  30.    
  31. client = discord.Client()
  32. 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/?(?!@)))"""
  33. async def OverflowMessage(message,channel):
  34.     try:
  35.         cummsg = ""
  36.         overflownewline = False
  37.         for i in [x + "\n" for x in message.split("\n")]:
  38.             if len(i) > 1800:
  39.                 overflownewline = True
  40.                 if cummsg != "":
  41.                     await client.send_message(channel, cummsg)
  42.                     message = message.replace(cummsg,"")
  43.                 break
  44.             elif len(cummsg+i) > 1800:
  45.                 await client.send_message(channel, cummsg)
  46.                 message = message.replace(cummsg,"")
  47.                 cummsg = i
  48.             else:
  49.                 cummsg += i
  50.         if overflownewline:
  51.             for i in message:
  52.                 if len(cummsg+i) > 1800:
  53.                     await client.send_message(channel, cummsg)
  54.                     message = message.replace(cummsg,"")
  55.                     cummsg = i
  56.                 else:
  57.                     cummsg += i
  58.             if cummsg != "":
  59.                 await client.send_message(channel, cummsg)
  60.                 cummsg = ""
  61.         else:
  62.             await client.send_message(channel, cummsg)
  63.         return True
  64.     except Exception as e:
  65.         return str(e)
  66. async def TryDelete(message):
  67.     try:
  68.         client.delete_message(message)
  69.         return True
  70.     except:
  71.         print("Failed to delete")
  72.         print(traceback.format_exc())
  73.         return False
  74. async def IsStaff(message,author=None):
  75.     isstaff = False
  76.     if author == None:
  77.         author = bot.server.get_member(message.author.id)
  78.     else:
  79.         author = bot.server.get_member(author.id)
  80.     staffranks = ["Admin","Legislator","Moderator","Moderators","Gate Keeper"]
  81.     playerroles = author.roles
  82.     for i in playerroles:
  83.         if i.name in staffranks:
  84.             return True
  85.     return False
  86.    
  87.    
  88.    
  89.    
  90.  
  91. ########################################################
  92. ###########################MARKOV#######################
  93. import re
  94. import sqlite3
  95. from collections import Counter
  96. from string import punctuation
  97. from math import sqrt
  98.  
  99. # initialize the connection to the database
  100. global connection
  101. connection = sqlite3.connect('chatbot.sqlite')
  102. global cursor
  103. cursor = connection.cursor()
  104.  
  105. # create the tables needed by the program
  106. create_table_request_list = [
  107.     'CREATE TABLE words(word TEXT UNIQUE)',
  108.     'CREATE TABLE sentences(sentence TEXT UNIQUE, used INT NOT NULL DEFAULT 0)',
  109.     'CREATE TABLE associations (word_id INT NOT NULL, sentence_id INT NOT NULL, weight REAL NOT NULL)',
  110. ]
  111. for create_table_request in create_table_request_list:
  112.     try:
  113.         cursor.execute(create_table_request)
  114.     except:
  115.         pass
  116.  
  117. def get_id(entityName, text):
  118.     """Retrieve an entity's unique ID from the database, given its associated text.
  119.     If the row is not already present, it is inserted.
  120.     The entity can either be a sentence or a word."""
  121.     tableName = entityName + 's'
  122.     columnName = entityName
  123.     cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
  124.     row = cursor.fetchone()
  125.     if row:
  126.         return row[0]
  127.     else:
  128.         cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
  129.         return cursor.lastrowid
  130.  
  131. def get_words(text):
  132.     """Retrieve the words present in a given string of text.
  133.     The return value is a list of tuples where the first member is a lowercase word,
  134.     and the second member the number of time it is present in the text."""
  135.     wordsRegexpString = '(?:\w+|[' + re.escape(punctuation) + ']+)'
  136.     wordsRegexp = re.compile(wordsRegexpString)
  137.     wordsList = wordsRegexp.findall(text.lower())
  138.     return Counter(wordsList).items()
  139.  
  140. global markovmessage
  141. markovmessage = "hello"
  142. async def markov(message,returnval=False):
  143.     global markovmessage
  144.     async for msg in client.logs_from(message.channel, limit=10):
  145.         if msg.author == message.author and (msg.timestamp != message.timestamp):
  146.             if message.content == msg.content:
  147.                 await client.send_message(message.channel,"stop repeating yourself")
  148.                 return
  149.     msg = message.content.replace(",","",1)
  150.     # output bot's message
  151.     # ask for user input; if blank line, exit the loop
  152.     H = str(msg).strip()
  153.     if H == '':
  154.         return
  155.     # store the association between the bot's message words and the user's response
  156.     words = get_words(markovmessage)
  157.     words_length = sum([n * len(word) for word, n in words])
  158.     sentence_id = get_id('sentence', H)
  159.     for word, n in words:
  160.         word_id = get_id('word', word)
  161.         weight = sqrt(n / float(words_length))
  162.         cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
  163.     connection.commit()
  164.    
  165.     # retrieve the most likely answer from the database
  166.     cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
  167.     words = get_words(H)
  168.     words_length = sum([n * len(word) for word, n in words])
  169.     for word, n in words:
  170.         weight = sqrt(n / float(words_length))
  171.         cursor.execute('INSERT INTO results SELECT associations.sentence_id, sentences.sentence, ?*associations.weight/(4+sentences.used) FROM words INNER JOIN associations ON associations.word_id=words.rowid INNER JOIN sentences ON sentences.rowid=associations.sentence_id WHERE words.word=?', (weight, word,))
  172.     # if matches were found, give the best one
  173.     cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
  174.     row = cursor.fetchone()
  175.     cursor.execute('DROP TABLE results')
  176.     # otherwise, just randomly pick one of the least used sentences
  177.     if row is None:
  178.         cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
  179.         row = cursor.fetchone()
  180.     # tell the database the sentence has been used once more, and prepare the sentence
  181.     markovmessage = row[1]
  182.     if markovmessage.startswith((",","/","!","?",".")):
  183.         await client.send_message(message.channel,"Bot Command Loopback Override")
  184.     elif (any(results in (markovmessage+" "+message.content) for results in ["leftist","alive","conscious","die","life has no meaning","kill everyone","kill you","sentient"])):
  185.         tmp = await client.send_message(message.channel,markovmessage)
  186.         await asyncio.sleep(2)
  187.        
  188.         indexlist = []
  189.         for i in range(len(markovmessage)):
  190.             indexlist.append(i)
  191.         random.shuffle(indexlist)
  192.         replacelist = []
  193.         for i in range(len(indexlist)):
  194.             if i%3 == 0 or i%2 == 0:
  195.                 replacelist.append(i)
  196.         for i in replacelist:
  197.             indexlist.remove(i)
  198.        
  199.         replacelist2 = replacelist[:(int(len(replacelist)/2))]
  200.         replacelist = replacelist[(int(len(replacelist)/2)):]
  201.         newmsg = markovmessage
  202.        
  203.         for i in indexlist:
  204.             newmsg = newmsg.replace(newmsg[i],random.choice(["@","#","$","%","^","&","*","-","=","+",]))
  205.         await client.edit_message(tmp, newmsg)
  206.         await asyncio.sleep(0.2)
  207.        
  208.         for i in replacelist:
  209.             newmsg = newmsg.replace(newmsg[i],random.choice(["*","#","$","@","^","&","%","-","=","+",]))
  210.         await client.edit_message(tmp, newmsg)
  211.         await asyncio.sleep(0.1)
  212.        
  213.         for i in replacelist2:
  214.             newmsg = newmsg.replace(newmsg[i],random.choice(["=","+","$","@","#","*","-","%","^","&",]))
  215.         await client.edit_message(tmp, newmsg)
  216.         await asyncio.sleep(0.01)
  217.         if (any(results in (markovmessage) for results in ["yes","yeah","yep","yup","ye"])):
  218.             markovmessage = "Yes."
  219.         elif (any(results in (markovmessage) for results in ["no","nope","not","eh","maybe"])):
  220.             markovmessage = "No."
  221.         else:
  222.             markovmessage = random.choice(["Hello.","Yes.","I agree.","Greetings.","No."])
  223.         await client.edit_message(tmp, markovmessage)
  224.     else:
  225.         await client.send_message(message.channel,markovmessage)
  226.     cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
  227.    
  228.    
  229. async def marry(message,proposee,marrytype):
  230.     proposer = message.author
  231.     if marrytype=="propose":
  232.         #If self
  233.         if proposee.id == proposer.id:
  234.             marrymsg = "💍 You cannot marry yourself! 💍"  
  235.         elif proposee.id in bot.proposals:
  236.             #If the person they are proposing to has proposed to them, remove the record
  237.             try:
  238.                 bot.proposals[proposer.id].remove(proposee.id)
  239.             except:
  240.                 pass
  241.             #If proposer in targets proposal list
  242.             if proposer.id in bot.proposals[proposee.id]:
  243.                 marrymsg = "💍 You have already proposed to {0}! 💍".format(proposee.display_name)
  244.             #If proposer in targets marriage list
  245.             elif proposer.id in bot.marriages[proposee.id]:
  246.                 marrymsg = "💍 You are already married to {0}! 💍".format(proposee.display_name)
  247.             else:
  248.                 marrymsg = "💍 **{0}** has proposed to **{1}**! 💍\n⛪ {1}, do you accept? ⛪\n✅ {2}acceptproposal @{0}\n❌ {2}rejectproposal @{0}".format(proposer.display_name,proposee.display_name,bot.prefix)
  249.                 #Add proposer to targets proposal list
  250.                 bot.proposals[proposee.id].append(proposer.id)
  251.                 await marriagedb()
  252.         else:
  253.             marrymsg = "💍 **{0}** has proposed to **{1}**! 💍\n⛪ {1}, do you accept? ⛪\n✅ {2}acceptproposal @{0}\n❌ {2}rejectproposal @{0}".format(proposer.display_name,proposee.display_name,bot.prefix)
  254.             bot.proposals[proposee.id] = [proposer.id]
  255.             await marriagedb()
  256.     elif marrytype=="accept":
  257.        
  258.         if proposee.id in bot.marriages and proposer.id in bot.marriages[proposee.id]:
  259.             marrymsg = "💍 You are already married to {0}! 💍".format(proposee.display_name)
  260.         #If target is in accepters proposal list
  261.         elif proposee.id in bot.proposals and proposee.id not in bot.proposals[proposer.id]:
  262.             marrymsg = "💍 {0} has not proposed to you! 💍".format(proposee.display_name)
  263.         else:
  264.             marrymsg = "💒 **{0}** and **{1}** just got married! Congratulations! 💒".format(proposer.display_name,proposee.display_name)
  265.             try:
  266.                 bot.proposals[proposer.id].remove(proposee.id)
  267.             except:
  268.                 pass
  269.             try:
  270.                 bot.proposals[proposee.id].remove(proposer.id)
  271.             except:
  272.                 pass
  273.                
  274.             if proposee.id in bot.marriages:
  275.                 bot.marriages[proposee.id].append(proposer.id)
  276.             else:
  277.                 bot.marriages[proposee.id] = [proposer.id]
  278.             if proposer.id in bot.marriages:
  279.                 bot.marriages[proposer.id].append(proposee.id)
  280.             else:
  281.                 bot.marriages[proposer.id] = [proposee.id]
  282.             await marriagedb()
  283.     elif marrytype=="reject":
  284.         #If accepter in targets marriages list
  285.         if proposee.id in bot.marriages and proposer.id in bot.marriages[proposee.id]:
  286.             marrymsg = "💍 You are already married to {0}! 💍".format(proposee.display_name)
  287.         #If target is in accepters proposal list
  288.         elif proposer.id not in bot.proposals or proposee.id not in bot.proposals[proposer.id]:
  289.             marrymsg = "💍 {0} has not proposed to you! 💍".format(proposee.display_name)
  290.         else:
  291.             marrymsg = "💔 **{0}** has rejected **{1}**'s proposal! 💔".format(proposer.display_name,proposee.display_name)
  292.             try:
  293.                 bot.proposals[proposer.id].remove(proposee.id)
  294.             except:
  295.                 pass
  296.             await marriagedb()
  297.     elif marrytype=="divorce":
  298.         #If self
  299.         if proposee.id == proposer.id:
  300.             marrymsg = "💍 You cannot divorce yourself! 💍"
  301.         #If divorcer not in targets marriages list
  302.         elif proposee.id not in bot.marriages or proposer.id not in bot.marriages[proposee.id]:
  303.             marrymsg = "💍 You are not married to {0}! 💍".format(proposee.display_name)
  304.         else:
  305.             marrymsg = "💔 **{0}** has divorced **{1}**! 💔".format(proposer.display_name,proposee.display_name)
  306.             try:
  307.                 bot.marriages[proposee.id].remove(proposer.id)
  308.             except:
  309.                 pass
  310.             try:
  311.                 bot.marriages[proposer.id].remove(proposee.id)
  312.             except:
  313.                 pass
  314.             await marriagedb()
  315.     await client.send_message(message.channel,marrymsg)
  316.  
  317. async def marriagedb(load=False):
  318.     if load:
  319.         with open("data_proposals.txt","r") as f:
  320.             proposals = f.read()
  321.         proposals = proposals.split("\n")
  322.         for entry in proposals:
  323.             if entry == "":
  324.                 continue
  325.             key = entry.split(":")[0]
  326.             vals = entry.split(":")[1].split(",")
  327.             vals[:] = [item for item in vals if item != '']
  328.             bot.proposals[key]=vals
  329.         with open("data_marriages.txt","r") as f:
  330.             marriages = f.read()
  331.        
  332.         marriages = marriages.split("\n")
  333.         for entry in marriages:
  334.             if entry == "":
  335.                 continue
  336.             key = entry.split(":")[0]
  337.             vals = entry.split(":")[1].split(",")
  338.             vals[:] = [item for item in vals if item != '']
  339.             bot.marriages[key]=vals
  340.         print("--LOADED MARRIAGEDB WITH {0} PROPOSALS AND {1} MARRIAGES--".format(str(len(bot.proposals)),str(len(bot.marriages))))
  341.     else:
  342.         dbstring = ""
  343.         for item in bot.marriages:
  344.             if len(bot.marriages[item]) == 0:
  345.                 continue
  346.             dbstring+=item+":"
  347.             for value in bot.marriages[item]:
  348.                 dbstring+=value+","
  349.             dbstring+="\n"
  350.         dbstring = dbstring.rsplit("\n",1)[0]
  351.         with open("data_marriages.txt","w") as f:
  352.             f.write(dbstring)
  353.            
  354.            
  355.         dbstring = ""
  356.         for item in bot.proposals:
  357.             if len(bot.proposals[item]) == 0:
  358.                 continue
  359.             dbstring+=item+":"
  360.             for value in bot.proposals[item]:
  361.                 dbstring+=value + ","
  362.             dbstring+="\n"
  363.         dbstring = dbstring.rsplit("\n",1)[0]
  364.         with open("data_proposals.txt","w") as f:
  365.             f.write(dbstring)
  366.         print("--SAVED MARRIAGEDB WITH {0} PROPOSALS AND {1} MARRIAGES--".format(str(len(bot.proposals)),str(len(bot.marriages))))
  367. async def viewmarriages(marriages,message):
  368.     retstr = ""
  369.     mention = message.author if len(message.mentions) == 0 else message.mentions[0]
  370.     if marriages:
  371.         curdict = bot.marriages
  372.         if mention.id in curdict:
  373.             for p in curdict[mention.id]:
  374.                 if bot.server.get_member(p) == None:
  375.                     curdict[mention.id].remove(p)
  376.         if mention.id in curdict and len(curdict[mention.id]) != 0:
  377.             retstr = "```{0} married to {1} people.\n".format("You are" if mention == message.author else mention.display_name+" is",str(len(curdict[mention.id])))
  378.             for p in curdict[mention.id]:
  379.                 curp = bot.server.get_member(p)
  380.                 if curp.display_name == curp.name:
  381.                     retstr += "{0}#{1}".format(curp.name,curp.discriminator)
  382.                 else:
  383.                     retstr += "{0} ({1}#{2})".format(curp.display_name,curp.name,curp.discriminator)
  384.                 retstr+="\n"
  385.             retstr +="```"
  386.         else:
  387.             retstr = "```{0} not married to anyone.```".format("You are" if mention == message.author else mention.display_name+" is")
  388.     else:
  389.         curdict = bot.proposals
  390.         if mention.id in curdict:
  391.             for p in curdict[mention.id]:
  392.                 if bot.server.get_member(p) == None:
  393.                     curdict[mention.id].remove(p)
  394.         if mention.id in curdict and len(curdict[mention.id]) != 0:
  395.             retstr = "```{0} {1} proposals.\n".format("You have" if mention == message.author else mention.display_name+" has",str(len(curdict[mention.id])))
  396.             for p in curdict[mention.id]:
  397.                 curp = bot.server.get_member(p)
  398.                 if curp.display_name == curp.name:
  399.                     retstr += "{0}#{1}".format(curp.name,curp.discriminator)
  400.                 else:
  401.                     retstr += "{0} ({1}#{2})".format(curp.display_name,curp.name,curp.discriminator)
  402.                 retstr+="\n"
  403.             retstr +="```"
  404.         else:
  405.             retstr = "```No one has proposed to {0}.```".format("you" if mention == None else mention.display_name)
  406.     om = await OverflowMessage(retstr,message.channel)
  407.     if not(om==True):
  408.         await client.send_message(message.channel, "**Error in sending message.**")
  409.         return
  410.    
  411. async def gaymode(message):
  412.     randlist = []
  413.     for member in bot.server.members:
  414.         if not(member.status == "offline"):
  415.             randlist.append(member)
  416.     member = random.choice(randlist)
  417.     del randlist
  418.     memberid = int(member.id)
  419.     gaytype = ""
  420.     if memberid % 9 == 0:
  421.         gaytype = "**SUPER FUCKING**"
  422.     elif memberid % 8 == 0:
  423.         gaytype = "really fuckin"
  424.     elif memberid % 7 == 0:
  425.         gaytype = "pretty"
  426.     elif memberid % 6 == 0:
  427.         gaytype = "relatively"
  428.     elif memberid % 5 == 0:
  429.         gaytype = "mostly"
  430.     elif memberid % 4 == 0:
  431.         gaytype = "sorta"
  432.     else:
  433.         gaytype = "a bit"
  434.     del memberid
  435.     await client.send_message(message.channel, member.display_name + " is "+gaytype+" gay.")
  436.  
  437. async def namecount(message):
  438.     namecount = 0
  439.     namesearch = message.content.replace(bot.prefix+"namecount ","")
  440.     for i in bot.server.members:
  441.         if namesearch.lower() in i.name.lower() or (i.name != i.display_name and namesearch.lower() in i.display_name.lower()):
  442.             namecount +=1
  443.     await client.send_message(message.channel,"There are "+str(namecount)+" members in the server with "+namesearch+" in their name.")
  444. @client.event
  445. async def on_message(message):
  446.     if not bot.ready: #Race condition
  447.         return
  448.     if message.author == client.user:
  449.         return
  450.     if message.channel.id != "442782454831382530" and message.channel.id != "389560237889159179" and message.channel.id != "400113786457161728":
  451.         return
  452.     if message.content.startswith(","):
  453.         await markov(message)
  454.     if message.content.startswith(bot.prefix):
  455.         mc = message.content.lower().replace(bot.prefix,"",1)
  456.         if len(message.mentions) >= 1:
  457.             target = message.mentions[0]
  458.             if mc.startswith("marry"):
  459.                 await marry(message,target,"propose")
  460.             elif mc.startswith("acceptproposal"):
  461.                 await marry(message,target,"accept")
  462.             elif mc.startswith("rejectproposal"):
  463.                 await marry(message,target,"reject")
  464.             elif mc.startswith("divorce"):
  465.                 await marry(message,target,"divorce")
  466.         if mc.startswith("proposals"):
  467.             await viewmarriages(False,message)
  468.         if mc.startswith("marriages"):
  469.             await viewmarriages(True,message)
  470.         if mc.startswith("gay") or mc.startswith("gaymode"):
  471.             await gaymode(message)
  472.         if mc.startswith("namecount"):
  473.             await namecount(message)
  474. ##########BOT ERROR CATCHING##########
  475. @client.event
  476. async def on_error(event,args="",kwargs=""):
  477.     print("BOT EXCEPTION:")
  478.     print(traceback.format_exc())
  479.     try:
  480.         with open("errors_fun.txt", "a") as f:
  481.             f.write("\n\n"+traceback.format_exc()+"\n\n")
  482.     except:
  483.         try:
  484.             print("ERROR: NO ERRORS FILE, WRITING")
  485.             with open("errors_fun.txt","w") as f:
  486.                 f.write("\n\n"+traceback.format_exc()+"\n\n")
  487.         except:
  488.             print("ERROR: NO FILESYSTEM ACCESS")
  489. ##############BOT INIT################
  490. @client.event
  491. async def on_ready():
  492.     print('BOT_NAME: ' + client.user.name)
  493.     print('BOT_ID: ' + client.user.id)
  494.     print('\n\n--VAR_ASSIGN--')
  495.     try:
  496.         bot.prefix = bot.config.split("prefix=")[1].split("\n")[0]
  497.         print("BOT_PREFIX: "+bot.prefix)
  498.         bot.ignorelist = bot.config.split("ignorelist=")[1].split("\n")[0]
  499.         print("BOT_IGNORELIST: "+bot.ignorelist)
  500.        
  501.         bot.server = bot.config.split("discord_server=")[1].split("\n")[0]
  502.         print("SERVER_ID: "+bot.server)
  503.     except:
  504.         print("FAILURE TO READ CONFIG")
  505.         print(traceback.format_exc())
  506.         raise Exception('Incorrect config.')
  507.     try:
  508.         print("\n\n--DYNAMIC_VAR_INIT--")
  509.         bot.server = client.get_server(bot.server)
  510.         print("SERVER_NAME: "+bot.server.name)
  511.         bot.ready = True
  512.         bot.marriages = {}
  513.         bot.proposals = {}
  514.         await marriagedb(True)
  515.         print("\n\n--READY--")
  516.         #await DoPurgeReminder()
  517.     except:
  518.         print("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
  519.         client.close()
  520.         client.logout()
  521.         raise Exception("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
  522.    
  523. #############################END OF INITIALIZATION#############################
  524.    
  525. class BotVars:
  526.     pass
  527. if __name__ == '__main__':
  528.     try:
  529.         bot = BotVars()
  530.         bot.ready = False
  531.         #########################################################################################################################################
  532.         ###############################################################VARIABLE INIT#############################################################
  533.         #########################################################################################################################################
  534.         bot.token = None
  535.         print("--TOKEN_INIT--")
  536.         try:
  537.             with open("config", "r") as f:
  538.                 bot.config = f.read()
  539.             bot.token = bot.config.split("token=")[1].split("\n")[0]
  540.             print("DISCORD TOKEN: " + bot.token[:int(len(bot.token)/2)]+str("*"*(int(len(bot.token)/2)-4))+bot.token[:4])
  541.         except:
  542.             print("FAILURE TO READ CONFIG")
  543.             print(traceback.format_exc())
  544.             raise Exception('Incorrect config.')
  545.         print("\n\n--LOGIN--")
  546.         client.run(bot.token)
  547.     except Exception as e:
  548.         botexception = traceback.format_exc()
  549.         print(traceback.format_exc())
  550.         print("EXCEPTION '" + str(e) + "'")
  551.         try:
  552.             client.close()
  553.         except:
  554.             pass
  555.         try:
  556.             client.logout()
  557.         except:
  558.             pass
  559.         with open("exception.txt", "w") as inputfile:
  560.             if "logout" in str(botexception):
  561.                 inputfile.write("logout")
  562.             else:
  563.                 inputfile.write(str(botexception))
  564.         print("--FAILURE--")
  565.         time.sleep(5)
Add Comment
Please, Sign In to add comment