Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #SAVE AS: bot_fun.py
- #########################################################################################################################################
- ###############################################################MODULE IMPORT#############################################################
- #########################################################################################################################################
- import json
- from datetime import datetime
- import sys
- import os
- import base64
- import mimetypes
- import time
- import random
- import io
- import re
- import traceback
- import discord #pip install -U discord.py[voice]
- import asyncio #pip install -U discord.py[voice]
- import aiohttp #pip install -U discord.py[voice]
- import numpy as np #pip install opencv-python
- from discord.ext import commands #pip install -U discord.py[voice]
- from googleapiclient.discovery import build #pip install --upgrade google-api-python-client
- from apiclient.errors import HttpError #pip install --upgrade google-api-python-client
- from oauth2client.tools import argparser #pip install --upgrade oauth2client
- try:
- from PIL import Image #pip install PIL
- except:
- import Image #pip install Image
- client = discord.Client()
- URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"""
- async def OverflowMessage(message,channel):
- try:
- cummsg = ""
- overflownewline = False
- for i in [x + "\n" for x in message.split("\n")]:
- if len(i) > 1800:
- overflownewline = True
- if cummsg != "":
- await client.send_message(channel, cummsg)
- message = message.replace(cummsg,"")
- break
- elif len(cummsg+i) > 1800:
- await client.send_message(channel, cummsg)
- message = message.replace(cummsg,"")
- cummsg = i
- else:
- cummsg += i
- if overflownewline:
- for i in message:
- if len(cummsg+i) > 1800:
- await client.send_message(channel, cummsg)
- message = message.replace(cummsg,"")
- cummsg = i
- else:
- cummsg += i
- if cummsg != "":
- await client.send_message(channel, cummsg)
- cummsg = ""
- else:
- await client.send_message(channel, cummsg)
- return True
- except Exception as e:
- return str(e)
- async def TryDelete(message):
- try:
- client.delete_message(message)
- return True
- except:
- print("Failed to delete")
- print(traceback.format_exc())
- return False
- async def IsStaff(message,author=None):
- isstaff = False
- if author == None:
- author = bot.server.get_member(message.author.id)
- else:
- author = bot.server.get_member(author.id)
- staffranks = ["Admin","Legislator","Moderator","Moderators","Gate Keeper"]
- playerroles = author.roles
- for i in playerroles:
- if i.name in staffranks:
- return True
- return False
- ########################################################
- ###########################MARKOV#######################
- import re
- import sqlite3
- from collections import Counter
- from string import punctuation
- from math import sqrt
- # initialize the connection to the database
- global connection
- connection = sqlite3.connect('chatbot.sqlite')
- global cursor
- cursor = connection.cursor()
- # create the tables needed by the program
- create_table_request_list = [
- 'CREATE TABLE words(word TEXT UNIQUE)',
- 'CREATE TABLE sentences(sentence TEXT UNIQUE, used INT NOT NULL DEFAULT 0)',
- 'CREATE TABLE associations (word_id INT NOT NULL, sentence_id INT NOT NULL, weight REAL NOT NULL)',
- ]
- for create_table_request in create_table_request_list:
- try:
- cursor.execute(create_table_request)
- except:
- pass
- def get_id(entityName, text):
- """Retrieve an entity's unique ID from the database, given its associated text.
- If the row is not already present, it is inserted.
- The entity can either be a sentence or a word."""
- tableName = entityName + 's'
- columnName = entityName
- cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
- row = cursor.fetchone()
- if row:
- return row[0]
- else:
- cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
- return cursor.lastrowid
- def get_words(text):
- """Retrieve the words present in a given string of text.
- The return value is a list of tuples where the first member is a lowercase word,
- and the second member the number of time it is present in the text."""
- wordsRegexpString = '(?:\w+|[' + re.escape(punctuation) + ']+)'
- wordsRegexp = re.compile(wordsRegexpString)
- wordsList = wordsRegexp.findall(text.lower())
- return Counter(wordsList).items()
- global markovmessage
- markovmessage = "hello"
- async def markov(message,returnval=False):
- global markovmessage
- async for msg in client.logs_from(message.channel, limit=10):
- if msg.author == message.author and (msg.timestamp != message.timestamp):
- if message.content == msg.content:
- await client.send_message(message.channel,"stop repeating yourself")
- return
- msg = message.content.replace(",","",1)
- # output bot's message
- # ask for user input; if blank line, exit the loop
- H = str(msg).strip()
- if H == '':
- return
- # store the association between the bot's message words and the user's response
- words = get_words(markovmessage)
- words_length = sum([n * len(word) for word, n in words])
- sentence_id = get_id('sentence', H)
- for word, n in words:
- word_id = get_id('word', word)
- weight = sqrt(n / float(words_length))
- cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
- connection.commit()
- # retrieve the most likely answer from the database
- cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
- words = get_words(H)
- words_length = sum([n * len(word) for word, n in words])
- for word, n in words:
- weight = sqrt(n / float(words_length))
- 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,))
- # if matches were found, give the best one
- cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
- row = cursor.fetchone()
- cursor.execute('DROP TABLE results')
- # otherwise, just randomly pick one of the least used sentences
- if row is None:
- cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
- row = cursor.fetchone()
- # tell the database the sentence has been used once more, and prepare the sentence
- markovmessage = row[1]
- if markovmessage.startswith((",","/","!","?",".")):
- await client.send_message(message.channel,"Bot Command Loopback Override")
- elif (any(results in (markovmessage+" "+message.content) for results in ["leftist","alive","conscious","die","life has no meaning","kill everyone","kill you","sentient"])):
- tmp = await client.send_message(message.channel,markovmessage)
- await asyncio.sleep(2)
- indexlist = []
- for i in range(len(markovmessage)):
- indexlist.append(i)
- random.shuffle(indexlist)
- replacelist = []
- for i in range(len(indexlist)):
- if i%3 == 0 or i%2 == 0:
- replacelist.append(i)
- for i in replacelist:
- indexlist.remove(i)
- replacelist2 = replacelist[:(int(len(replacelist)/2))]
- replacelist = replacelist[(int(len(replacelist)/2)):]
- newmsg = markovmessage
- for i in indexlist:
- newmsg = newmsg.replace(newmsg[i],random.choice(["@","#","$","%","^","&","*","-","=","+",]))
- await client.edit_message(tmp, newmsg)
- await asyncio.sleep(0.2)
- for i in replacelist:
- newmsg = newmsg.replace(newmsg[i],random.choice(["*","#","$","@","^","&","%","-","=","+",]))
- await client.edit_message(tmp, newmsg)
- await asyncio.sleep(0.1)
- for i in replacelist2:
- newmsg = newmsg.replace(newmsg[i],random.choice(["=","+","$","@","#","*","-","%","^","&",]))
- await client.edit_message(tmp, newmsg)
- await asyncio.sleep(0.01)
- if (any(results in (markovmessage) for results in ["yes","yeah","yep","yup","ye"])):
- markovmessage = "Yes."
- elif (any(results in (markovmessage) for results in ["no","nope","not","eh","maybe"])):
- markovmessage = "No."
- else:
- markovmessage = random.choice(["Hello.","Yes.","I agree.","Greetings.","No."])
- await client.edit_message(tmp, markovmessage)
- else:
- await client.send_message(message.channel,markovmessage)
- cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
- async def marry(message,proposee,marrytype):
- proposer = message.author
- if marrytype=="propose":
- #If self
- if proposee.id == proposer.id:
- marrymsg = "💍 You cannot marry yourself! 💍"
- elif proposee.id in bot.proposals:
- #If the person they are proposing to has proposed to them, remove the record
- try:
- bot.proposals[proposer.id].remove(proposee.id)
- except:
- pass
- #If proposer in targets proposal list
- if proposer.id in bot.proposals[proposee.id]:
- marrymsg = "💍 You have already proposed to {0}! 💍".format(proposee.display_name)
- #If proposer in targets marriage list
- elif proposer.id in bot.marriages[proposee.id]:
- marrymsg = "💍 You are already married to {0}! 💍".format(proposee.display_name)
- else:
- 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)
- #Add proposer to targets proposal list
- bot.proposals[proposee.id].append(proposer.id)
- await marriagedb()
- else:
- 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)
- bot.proposals[proposee.id] = [proposer.id]
- await marriagedb()
- elif marrytype=="accept":
- if proposee.id in bot.marriages and proposer.id in bot.marriages[proposee.id]:
- marrymsg = "💍 You are already married to {0}! 💍".format(proposee.display_name)
- #If target is in accepters proposal list
- elif proposee.id in bot.proposals and proposee.id not in bot.proposals[proposer.id]:
- marrymsg = "💍 {0} has not proposed to you! 💍".format(proposee.display_name)
- else:
- marrymsg = "💒 **{0}** and **{1}** just got married! Congratulations! 💒".format(proposer.display_name,proposee.display_name)
- try:
- bot.proposals[proposer.id].remove(proposee.id)
- except:
- pass
- try:
- bot.proposals[proposee.id].remove(proposer.id)
- except:
- pass
- if proposee.id in bot.marriages:
- bot.marriages[proposee.id].append(proposer.id)
- else:
- bot.marriages[proposee.id] = [proposer.id]
- if proposer.id in bot.marriages:
- bot.marriages[proposer.id].append(proposee.id)
- else:
- bot.marriages[proposer.id] = [proposee.id]
- await marriagedb()
- elif marrytype=="reject":
- #If accepter in targets marriages list
- if proposee.id in bot.marriages and proposer.id in bot.marriages[proposee.id]:
- marrymsg = "💍 You are already married to {0}! 💍".format(proposee.display_name)
- #If target is in accepters proposal list
- elif proposer.id not in bot.proposals or proposee.id not in bot.proposals[proposer.id]:
- marrymsg = "💍 {0} has not proposed to you! 💍".format(proposee.display_name)
- else:
- marrymsg = "💔 **{0}** has rejected **{1}**'s proposal! 💔".format(proposer.display_name,proposee.display_name)
- try:
- bot.proposals[proposer.id].remove(proposee.id)
- except:
- pass
- await marriagedb()
- elif marrytype=="divorce":
- #If self
- if proposee.id == proposer.id:
- marrymsg = "💍 You cannot divorce yourself! 💍"
- #If divorcer not in targets marriages list
- elif proposee.id not in bot.marriages or proposer.id not in bot.marriages[proposee.id]:
- marrymsg = "💍 You are not married to {0}! 💍".format(proposee.display_name)
- else:
- marrymsg = "💔 **{0}** has divorced **{1}**! 💔".format(proposer.display_name,proposee.display_name)
- try:
- bot.marriages[proposee.id].remove(proposer.id)
- except:
- pass
- try:
- bot.marriages[proposer.id].remove(proposee.id)
- except:
- pass
- await marriagedb()
- await client.send_message(message.channel,marrymsg)
- async def marriagedb(load=False):
- if load:
- with open("data_proposals.txt","r") as f:
- proposals = f.read()
- proposals = proposals.split("\n")
- for entry in proposals:
- if entry == "":
- continue
- key = entry.split(":")[0]
- vals = entry.split(":")[1].split(",")
- vals[:] = [item for item in vals if item != '']
- bot.proposals[key]=vals
- with open("data_marriages.txt","r") as f:
- marriages = f.read()
- marriages = marriages.split("\n")
- for entry in marriages:
- if entry == "":
- continue
- key = entry.split(":")[0]
- vals = entry.split(":")[1].split(",")
- vals[:] = [item for item in vals if item != '']
- bot.marriages[key]=vals
- print("--LOADED MARRIAGEDB WITH {0} PROPOSALS AND {1} MARRIAGES--".format(str(len(bot.proposals)),str(len(bot.marriages))))
- else:
- dbstring = ""
- for item in bot.marriages:
- if len(bot.marriages[item]) == 0:
- continue
- dbstring+=item+":"
- for value in bot.marriages[item]:
- dbstring+=value+","
- dbstring+="\n"
- dbstring = dbstring.rsplit("\n",1)[0]
- with open("data_marriages.txt","w") as f:
- f.write(dbstring)
- dbstring = ""
- for item in bot.proposals:
- if len(bot.proposals[item]) == 0:
- continue
- dbstring+=item+":"
- for value in bot.proposals[item]:
- dbstring+=value + ","
- dbstring+="\n"
- dbstring = dbstring.rsplit("\n",1)[0]
- with open("data_proposals.txt","w") as f:
- f.write(dbstring)
- print("--SAVED MARRIAGEDB WITH {0} PROPOSALS AND {1} MARRIAGES--".format(str(len(bot.proposals)),str(len(bot.marriages))))
- async def viewmarriages(marriages,message):
- retstr = ""
- mention = message.author if len(message.mentions) == 0 else message.mentions[0]
- if marriages:
- curdict = bot.marriages
- if mention.id in curdict:
- for p in curdict[mention.id]:
- if bot.server.get_member(p) == None:
- curdict[mention.id].remove(p)
- if mention.id in curdict and len(curdict[mention.id]) != 0:
- retstr = "```{0} married to {1} people.\n".format("You are" if mention == message.author else mention.display_name+" is",str(len(curdict[mention.id])))
- for p in curdict[mention.id]:
- curp = bot.server.get_member(p)
- if curp.display_name == curp.name:
- retstr += "{0}#{1}".format(curp.name,curp.discriminator)
- else:
- retstr += "{0} ({1}#{2})".format(curp.display_name,curp.name,curp.discriminator)
- retstr+="\n"
- retstr +="```"
- else:
- retstr = "```{0} not married to anyone.```".format("You are" if mention == message.author else mention.display_name+" is")
- else:
- curdict = bot.proposals
- if mention.id in curdict:
- for p in curdict[mention.id]:
- if bot.server.get_member(p) == None:
- curdict[mention.id].remove(p)
- if mention.id in curdict and len(curdict[mention.id]) != 0:
- retstr = "```{0} {1} proposals.\n".format("You have" if mention == message.author else mention.display_name+" has",str(len(curdict[mention.id])))
- for p in curdict[mention.id]:
- curp = bot.server.get_member(p)
- if curp.display_name == curp.name:
- retstr += "{0}#{1}".format(curp.name,curp.discriminator)
- else:
- retstr += "{0} ({1}#{2})".format(curp.display_name,curp.name,curp.discriminator)
- retstr+="\n"
- retstr +="```"
- else:
- retstr = "```No one has proposed to {0}.```".format("you" if mention == None else mention.display_name)
- om = await OverflowMessage(retstr,message.channel)
- if not(om==True):
- await client.send_message(message.channel, "**Error in sending message.**")
- return
- async def gaymode(message):
- randlist = []
- for member in bot.server.members:
- if not(member.status == "offline"):
- randlist.append(member)
- member = random.choice(randlist)
- del randlist
- memberid = int(member.id)
- gaytype = ""
- if memberid % 9 == 0:
- gaytype = "**SUPER FUCKING**"
- elif memberid % 8 == 0:
- gaytype = "really fuckin"
- elif memberid % 7 == 0:
- gaytype = "pretty"
- elif memberid % 6 == 0:
- gaytype = "relatively"
- elif memberid % 5 == 0:
- gaytype = "mostly"
- elif memberid % 4 == 0:
- gaytype = "sorta"
- else:
- gaytype = "a bit"
- del memberid
- await client.send_message(message.channel, member.display_name + " is "+gaytype+" gay.")
- async def namecount(message):
- namecount = 0
- namesearch = message.content.replace(bot.prefix+"namecount ","")
- for i in bot.server.members:
- if namesearch.lower() in i.name.lower() or (i.name != i.display_name and namesearch.lower() in i.display_name.lower()):
- namecount +=1
- await client.send_message(message.channel,"There are "+str(namecount)+" members in the server with "+namesearch+" in their name.")
- @client.event
- async def on_message(message):
- if not bot.ready: #Race condition
- return
- if message.author == client.user:
- return
- if message.channel.id != "442782454831382530" and message.channel.id != "389560237889159179" and message.channel.id != "400113786457161728":
- return
- if message.content.startswith(","):
- await markov(message)
- if message.content.startswith(bot.prefix):
- mc = message.content.lower().replace(bot.prefix,"",1)
- if len(message.mentions) >= 1:
- target = message.mentions[0]
- if mc.startswith("marry"):
- await marry(message,target,"propose")
- elif mc.startswith("acceptproposal"):
- await marry(message,target,"accept")
- elif mc.startswith("rejectproposal"):
- await marry(message,target,"reject")
- elif mc.startswith("divorce"):
- await marry(message,target,"divorce")
- if mc.startswith("proposals"):
- await viewmarriages(False,message)
- if mc.startswith("marriages"):
- await viewmarriages(True,message)
- if mc.startswith("gay") or mc.startswith("gaymode"):
- await gaymode(message)
- if mc.startswith("namecount"):
- await namecount(message)
- ##########BOT ERROR CATCHING##########
- @client.event
- async def on_error(event,args="",kwargs=""):
- print("BOT EXCEPTION:")
- print(traceback.format_exc())
- try:
- with open("errors_fun.txt", "a") as f:
- f.write("\n\n"+traceback.format_exc()+"\n\n")
- except:
- try:
- print("ERROR: NO ERRORS FILE, WRITING")
- with open("errors_fun.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)
- 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.ready = True
- bot.marriages = {}
- bot.proposals = {}
- await marriagedb(True)
- print("\n\n--READY--")
- #await DoPurgeReminder()
- except:
- print("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
- client.close()
- client.logout()
- raise Exception("CRITICAL ERROR: FAILURE TO ASSIGN CHANNELS")
- #############################END OF INITIALIZATION#############################
- class BotVars:
- pass
- if __name__ == '__main__':
- try:
- bot = BotVars()
- bot.ready = False
- #########################################################################################################################################
- ###############################################################VARIABLE INIT#############################################################
- #########################################################################################################################################
- bot.token = None
- print("--TOKEN_INIT--")
- try:
- with open("config", "r") as f:
- bot.config = f.read()
- bot.token = bot.config.split("token=")[1].split("\n")[0]
- print("DISCORD TOKEN: " + bot.token[:int(len(bot.token)/2)]+str("*"*(int(len(bot.token)/2)-4))+bot.token[:4])
- except:
- print("FAILURE TO READ CONFIG")
- print(traceback.format_exc())
- raise Exception('Incorrect config.')
- print("\n\n--LOGIN--")
- client.run(bot.token)
- except Exception as e:
- botexception = traceback.format_exc()
- print(traceback.format_exc())
- print("EXCEPTION '" + str(e) + "'")
- try:
- client.close()
- except:
- pass
- try:
- client.logout()
- except:
- pass
- with open("exception.txt", "w") as inputfile:
- if "logout" in str(botexception):
- inputfile.write("logout")
- else:
- inputfile.write(str(botexception))
- print("--FAILURE--")
- time.sleep(5)
Add Comment
Please, Sign In to add comment