Advertisement
Guest User

đŸ” 𝙱𝙱Self | Beta eco +

a guest
Feb 9th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 45.34 KB | None | 0 0
  1. import collections
  2. import datetime
  3. import math
  4. import subprocess
  5. import asyncio
  6. import random
  7. import glob
  8. import gc
  9. import psutil
  10. import sys
  11. import re
  12. import traceback
  13. import argparse
  14. import os
  15. import logging
  16. import requests
  17. import logging.handlers
  18. import discord
  19. from bs4 import BeautifulSoup
  20. from json import load, dump
  21. from datetime import timezone
  22. from cogs.utils.dataIO import dataIO
  23. from cogs.utils.allmsgs import custom, quickcmds
  24. from cogs.utils.webhooks import Webhook
  25. from cogs.utils.checks import *
  26. from cogs.utils.config import *
  27. from collections import namedtuple
  28. from discord.ext import commands
  29.  
  30.  
  31. FakeGuild = namedtuple("FakeGuild", ["name", "id", "icon_url", "members", "me", "channels", "emojis"])
  32.  
  33. def parse_cmd_arguments():  # allows for arguments
  34.     parser = argparse.ArgumentParser(description="Discord-Selfbot")
  35.     parser.add_argument("-test", "--test-run",  # test run flag for Travis
  36.                         action="store_true",
  37.                         help="Makes the bot quit before trying to log in")
  38.     parser.add_argument("--force-mac",  # Allows for Testing of mac related code
  39.                         action="store_true",
  40.                         help="Forces to run the Mac checks")
  41.     parser.add_argument("--reset-config",  # Allows for Testing of mac related code
  42.                         action="store_true",
  43.                         help="Reruns the setup")
  44.     parser.add_argument("-s", "--silent",  # Allows for Testing of mac related code
  45.                         action="store_true",
  46.                         help="Supresses all errors")
  47.     return parser
  48.  
  49.  
  50. args = parse_cmd_arguments().parse_args()
  51. _test_run = args.test_run
  52. _force_mac = args.force_mac
  53. _reset_cfg = args.reset_config
  54. _silent = args.silent
  55. _force_admin = False
  56.  
  57. try:
  58.     import uvloop
  59. except ImportError:
  60.     pass
  61. else:
  62.     asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  63.  
  64. try:
  65.     token = os.environ['TOKEN']
  66.     heroku = True
  67. except KeyError:
  68.     heroku = False
  69.  
  70. if _test_run:
  71.     try:
  72.         samples = os.listdir('settings')  #gĂ©nĂ©rer les fichiers de configuration Ă  partir de l'Ă©chantillon pendant la construction
  73.         for f in samples:
  74.             if f.endswith('sample') and f[:-7] not in samples:
  75.                 with open('settings/%s' % f, 'r', encoding="utf8") as template:
  76.                     with open('settings/%s' % f[:-7], 'w', encoding="utf8") as g:
  77.                         fields = json.load(template)
  78.                         json.dump(fields, g, sort_keys=True, indent=4)
  79.     except:
  80.         print('Quelque chose ne va pas. Rechercher des exemples de fichiers manquants')  # only visible in Travis
  81.         pass  # duo to some sample files sometimes missing passing it will make sure nothing goes wrong
  82.     print("Quitting: test run")
  83.     exit(0)
  84.  
  85. def wizard():
  86.     # setup wizard
  87.     if _silent:
  88.         print('Impossible d'utiliser l'assistant de configuration en raison du mode silencieux')
  89.         exit(0)
  90.     config = {}
  91.     print("Errr")
  92.    
  93.     print("La premiĂšre Ă©tape consiste Ă  configurer votre jeton.")
  94.     print("Allez dans votre fenĂȘtre Discord et appuyez sur Ctrl + Maj + I (Ctrl + Opt + Je peux aussi travailler sur macOS) ")
  95.      print ("Ensuite, allez dans l'onglet Applications (vous devrez peut-ĂȘtre cliquer sur la flĂšche en haut Ă  droite pour y arriver)), dĂ©veloppez la liste dĂ©roulante" Stockage local ", sĂ©lectionnez discordapp, puis saisissez la valeur du jeton en bas. Voici comment il semble: https://imgur.com/h3g9uf6")
  96.     print("Collez le contenu de cette entrĂ©e ci-dessous.")
  97.     print("-------------------------------------------------------------")
  98.     config["token"] = input("| ").strip().strip('"')
  99.    
  100.     config["cmd_prefix"] = False
  101.     while not config["cmd_prefix"]:
  102.         print("\ nEntrez le prĂ©fixe de la commande que vous souhaitez utiliser pour les commandes principales (par exemple, si vous entrez>, vous utiliserez des commandes telles que:> Ă  propos de).")
  103.         print("-------------------------------------------------------------")
  104.         config["cmd_prefix"] = input("| ").strip()
  105.         if not config["cmd_prefix"]:
  106.             print("Empty command prefixes are invalid.")
  107.            
  108.     config["customcmd_prefix"] = False
  109.     while not config["customcmd_prefix"]:
  110.         print("\ nEntrez le prĂ©fixe de commande que vous souhaitez utiliser pour les commandes personnalisĂ©es (les commandes que vous ajoutez vous-mĂȘme au bot avec des rĂ©ponses personnalisĂ©es). L'utilisation du mĂȘme prĂ©fixe que le prĂ©fixe de la commande principale est autorisĂ©e, mais non recommandĂ©e.")
  111.         print("-------------------------------------------------------------")
  112.         config["customcmd_prefix"] = input("| ").strip()
  113.         if not config["customcmd_prefix"]:
  114.             print("Empty command prefixes are invalid.")
  115.    
  116.     print("\ nEntrez quelque chose qui prĂ©cĂ©dera chaque rĂ©ponse du bot. Il s’agit de distinguer les rĂ©ponses des robots des bavardages normaux des utilisateurs, c’est-Ă -dire si vous entrez: robot: obligera le bot Ă  rĂ©pondre avec le robot emoji devant chaque message qu’il envoie.
  117. ")
  118.     print("-------------------------------------------------------------")
  119.     config["bot_identifier"] = input("| ").strip()
  120.  
  121.     print("\ Voulez-vous que les informations sur votre utilisation du bot soient enregistrĂ©es Ă  des fins statistiques? Toutes les informations sont anonymes et ne peuvent vous ĂȘtre retracĂ©es. (O / N)")
  122.     print("-------------------------------------------------------------")
  123.     config["track"] = "y" in input("| ").strip().lower()
  124.    
  125.     input("\nThis concludes the setup wizard. For further setup options (ex. setting up google image search), refer to the Discord Selfbot wiki.\n\nYour settings:\nInvoke commands with: {cmd}  Ex: {cmd}ping\nInvoke custom commands with: {custom}  Ex: {custom}get good\nYou may restart this wizard at any time by deleting config.json in the settings folder.\n\nPress Enter to start the bot....\n".format(cmd=config["cmd_prefix"], custom=config["customcmd_prefix"]))
  126.  
  127.     print("Starting up...")
  128.     with open('settings/config.json', encoding='utf-8', mode="w") as f:
  129.         dump(config, f, sort_keys=True, indent=4)
  130.  
  131.  
  132. if _reset_cfg and not heroku:
  133.     wizard()
  134. else:
  135.     try:
  136.         with open('settings/config.json', encoding='utf-8', mode="r") as f:
  137.             data = load(f)  # checks if the settings file is valid json file
  138.     except IOError:
  139.         if not heroku:
  140.             wizard()
  141.         else:
  142.             print("Error: Heroku environment detected, but config.json not found!\nThis is usually due to user error during Heroku setup.")
  143.             exit(-1)
  144.  
  145. shutdown = False
  146. if os.name == 'nt':
  147.     try:
  148.         # only windows users with admin privileges can read the C:\windows\temp
  149.         temp = os.listdir(os.sep.join([os.environ.get('SystemRoot', 'C:\\windows'), 'temp']))
  150.     except:
  151.         shutdown = False
  152.     else:
  153.         shutdown = True
  154. else:
  155.     if os.geteuid() == 0:
  156.         shutdown = True
  157.     else:
  158.         shutdown = False
  159.        
  160. if shutdown is True and not _force_admin:
  161.     if os.name == 'nt':
  162.         print('It is not advised to run the bot as Admin.\nContinuing logging in...')
  163.     else:
  164.         print('It is not advised to run the bot with root privileges.\nContinuing logging in...')
  165.  
  166.  
  167. def set_log():
  168.     errformat = logging.Formatter(
  169.         '%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d: '
  170.         '%(message)s',
  171.         datefmt="[%d/%m/%Y %H:%M]")
  172.  
  173.     logger = logging.getLogger("discord")
  174.     logger.setLevel(logging.INFO)
  175.     stdout_handler = logging.StreamHandler(sys.stdout)
  176.     stdout_handler.setLevel(logging.INFO)
  177.  
  178.     if not os.path.exists('settings/logs'):
  179.         os.makedirs('settings/logs')
  180.     errhandler = logging.handlers.RotatingFileHandler(
  181.         filename='settings/logs/bot.log', encoding='utf-8', mode='a',
  182.         maxBytes=10**7, backupCount=5)
  183.     errhandler.setFormatter(errformat)
  184.  
  185.     logger.addHandler(errhandler)
  186.  
  187.     return logger
  188.  
  189.  
  190. logger = set_log()
  191.  
  192. samples = os.listdir('settings')
  193. for f in samples:
  194.     if f.endswith('sample') and f.rsplit('.', 1)[0] not in samples:
  195.         with open('settings/%s' % f, 'r', encoding="utf8") as template:
  196.             with open('settings/%s' % f.rsplit('.', 1)[0], 'w', encoding="utf8") as g:
  197.                 fields = json.load(template)
  198.                 json.dump(fields, g, sort_keys=True, indent=4)
  199.  
  200.  
  201. bot = commands.Bot(command_prefix=get_config_value('config', 'cmd_prefix'), description='''Selfbot by 9mm''', self_bot=True)
  202.  
  203. if __name__ == "__main__":
  204.     _runs_in_loop = False
  205. else:
  206.     _runs_in_loop = True
  207.  
  208. bot.bot_prefix = get_config_value('config', 'bot_identifier')
  209. if bot.bot_prefix != '':
  210.     bot.bot_prefix += ' '
  211.  
  212. bot.cmd_prefix = get_config_value('config', 'cmd_prefix')
  213. bot.customcmd_prefix = get_config_value('config', 'customcmd_prefix')
  214. bot.track = get_config_value('config', 'track', None)
  215. if bot.track is None:
  216.     print("Would you like information about your usage of the bot to be recorded for statistic purposes? All information is anonymous and cannot be tracked back to you. (Y/N)")
  217.     print("-------------------------------------------------------------")
  218.     bot.track = "y" in input("| ").strip().lower()
  219.     write_config_value("config", "track", bot.track)
  220.  
  221. # Startup
  222. @bot.event
  223. async def on_ready():
  224.     message = 'logged in as %s' % bot.user
  225.     uid_message = 'user id %s' % bot.user.id
  226.     separator = '-' * max(len(message), len(uid_message))
  227.     print(separator)
  228.     try:
  229.         print(message)
  230.     except: # some bot usernames with special chars fail on shitty platforms
  231.         print(message.encode(errors='replace').decode())
  232.     print(uid_message)
  233.     if bot.track:
  234.         print("anonymous tracking of bot usage is enabled")
  235.     print("'unclosed client session' and 'unclosed connector' are not errors")
  236.     print(separator)
  237.  
  238.     bot.session = aiohttp.ClientSession(loop=bot.loop, headers={"User-Agent": "9mmSelfBot"})
  239.  
  240.     bot.uptime = datetime.datetime.now()
  241.     bot.icount = bot.message_count = bot.mention_count = bot.keyword_log = 0
  242.     bot.self_log = bot.all_log = {}
  243.     bot.imagedumps = []
  244.     bot.is_stream = False
  245.     bot.game = bot.game_interval = bot.avatar = bot.avatar_interval = bot.subpro = bot.keyword_found = None
  246.     bot.game_time = bot.avatar_time = bot.gc_time = bot.refresh_time = time.time()
  247.     bot.notify = load_notify_config()
  248.     bot.command_count = {}
  249.     bot.channel_last = [None, None]
  250.     if not os.path.isfile('settings/ignored.json'):
  251.         with open('settings/ignored.json', 'w', encoding="utf8") as fp:
  252.             json.dump({'servers': []}, fp, indent=4)
  253.     with open('settings/ignored.json', encoding="utf8") as fp:
  254.         bot.ignored_servers = json.load(fp)
  255.  
  256.     if os.path.isfile('restart.txt'):
  257.         with open('restart.txt', 'r', encoding="utf8") as re:
  258.             channel = bot.get_channel(int(re.readline()))
  259.             print('Bot has restarted.')
  260.             await channel.send(bot.bot_prefix + 'Bot has restarted.')
  261.         os.remove('restart.txt')
  262.     bot.log_conf = load_log_config()
  263.     bot.key_users = bot.log_conf['keyusers']
  264.  
  265.     if os.path.isfile('settings/games.json'):
  266.         with open('settings/games.json', 'r+', encoding="utf8") as g:
  267.             games = json.load(g)
  268.             if type(games['games']) is list:
  269.                 bot.game = games['games'][0]
  270.                 bot.game_interval = games['interval']
  271.             else:
  272.                 bot.game = games['games']
  273.             if 'stream' not in games:
  274.                 games['stream'] = 'no'
  275.             if games['stream'] == 'yes':
  276.                 bot.is_stream = True
  277.             try:
  278.                 bot.status_type = games['status']
  279.             except KeyError:
  280.                 bot.status_type = discord.ActivityType.playing
  281.             g.seek(0)
  282.             g.truncate()
  283.             json.dump(games, g, indent=4)
  284.  
  285.     # Dealing with old versions updating
  286.     if not os.path.isfile('settings/fc.json'):
  287.         data = {"bnet_fc": "", "ds_fc": "", "psn_fc": "", "steam_fc": "", "switch_fc": "", "xbox_fc": ""}
  288.         dataIO.save_json("settings/fc.json", data)
  289.     if not os.path.isfile('settings/replacements.json'):
  290.         data = {":lennyface:": "( ͥ° ͜ʖ ͥ°)", ":tableflip": "(â•ŻÂ°â–ĄÂ°ïŒ‰â•Żïž” ┻━┻"}
  291.         dataIO.save_json("settings/replacements.json", data)
  292.     if not os.path.isfile('settings/moderation.json'):
  293.         with open('settings/moderation.json', 'w', encoding="utf8") as m:
  294.             mod = {}
  295.             json.dump(mod, m, indent=4)
  296.     if not os.path.isfile('settings/todo.json'):
  297.         with open('settings/todo.json', 'w', encoding="utf8") as t:
  298.             todo = {}
  299.             json.dump(todo, t, indent=4)
  300.  
  301.     if not os.path.exists('avatars'):
  302.         os.makedirs('avatars')
  303.     if not os.path.isfile('settings/avatars.json'):
  304.         with open('settings/avatars.json', 'w', encoding="utf8") as avis:
  305.             json.dump({'password': '', 'interval': '0', 'type': 'random'}, avis, indent=4)
  306.     with open('settings/avatars.json', 'r', encoding="utf8") as g:
  307.         avatars = json.load(g)
  308.     bot.avatar_interval = avatars['interval']
  309.     if os.listdir('avatars') and avatars['interval'] != '0':
  310.         all_avis = os.listdir('avatars')
  311.         all_avis.sort()
  312.         avi = random.choice(all_avis)
  313.         bot.avatar = avi
  314.     if not os.path.isfile('settings/optional_config.json'):
  315.         conf = load_config()
  316.         o_conf = {'google_api_key': conf['google_api_key'], 'custom_search_engine': conf['custom_search_engine'], 'mal_username': conf['mal_username'], 'mal_password': conf['mal_password']}
  317.         with open('settings/optional_config.json', 'w', encoding="utf8") as oc:
  318.             json.dump(o_conf, oc, indent=4)
  319.     with open('settings/optional_config.json', 'r+', encoding="utf8") as fp:
  320.         opt = json.load(fp)
  321.         if 'embed_color' not in opt:
  322.             opt['embed_color'] = ''
  323.         if 'quoteembed_color' not in opt:
  324.             opt['quoteembed_color'] = 'bc0b0b'
  325.         if 'customcmd_color' not in opt:
  326.             opt['customcmd_color'] = '27007A'
  327.         if 'rich_embed' not in opt:
  328.             opt['rich_embed'] = 'on'
  329.         if 'default_status' not in opt:
  330.             opt['default_status'] = 'idle'
  331.         if 'ascii_font' not in opt:
  332.             opt['ascii_font'] = 'big'
  333.         if 'timezone' not in opt:
  334.             opt['timezone'] = ''
  335.         if '24hours' not in opt:
  336.             opt['24hours'] = 'true'
  337.         if 'password' not in opt:
  338.             opt['password'] = ''
  339.         if avatars['password'] != '' and opt['password'] == '':
  340.             opt['password'] = avatars['password']
  341.         bot.default_status = opt['default_status']
  342.         fp.seek(0)
  343.         fp.truncate()
  344.         json.dump(opt, fp, indent=4)
  345.  
  346.     if not os.path.isfile('settings/github.json'):
  347.         with open('settings/github.json', 'w', encoding="utf8") as fp:
  348.             git = {}
  349.             json.dump(git, fp, indent=4)
  350.     with open('settings/github.json', 'r+', encoding="utf8") as fp:
  351.         opt = json.load(fp)
  352.         if 'username' not in opt:
  353.             opt['username'] = ''
  354.         if 'password' not in opt:
  355.             opt['password'] = ''
  356.         if 'reponame' not in opt:
  357.             opt['reponame'] = ''
  358.         fp.seek(0)
  359.         fp.truncate()
  360.         json.dump(opt, fp, indent=4)
  361.  
  362.     notif = load_notify_config()
  363.     if notif['type'] == 'dm':
  364.         if os.path.exists('notifier.txt'):
  365.             pid = open('notifier.txt', 'r', encoding="utf8").read()
  366.             try:
  367.                 p = psutil.Process(int(pid))
  368.                 p.kill()
  369.             except:
  370.                 pass
  371.             os.remove('notifier.txt')
  372.         bot.subpro = subprocess.Popen([sys.executable, 'cogs/utils/notify.py'])
  373.         with open('notifier.txt', 'w', encoding="utf8") as fp:
  374.             fp.write(str(bot.subpro.pid))
  375.  
  376.  
  377. @bot.after_invoke
  378. async def after_any_command(ctx):
  379.     if not ctx.command_failed:
  380.         if str(ctx.command) not in bot.command_count:
  381.             bot.command_count[str(ctx.command)] = 1
  382.         else:
  383.             bot.command_count[str(ctx.command)] += 1
  384.  
  385.  
  386. @bot.event
  387. async def on_command_error(ctx, error):
  388.     if isinstance(error, commands.errors.CommandNotFound):
  389.         pass
  390.     elif isinstance(error, commands.errors.CheckFailure):
  391.         await ctx.send(bot.bot_prefix + "You don't have permissions to use that command.")
  392.     elif isinstance(error, commands.errors.MissingRequiredArgument):
  393.         formatter = commands.formatter.HelpFormatter()
  394.         help = await formatter.format_help_for(ctx, ctx.command)
  395.         await ctx.send(bot.bot_prefix + "You are missing required arguments.\n" + help[0])
  396.     elif isinstance(error, commands.errors.BadArgument):
  397.         await ctx.send(bot.bot_prefix + "You have given an invalid argument.")
  398.     else:
  399.         if _silent:
  400.             await ctx.send(bot.bot_prefix + "An error occurred with the `{}` command.".format(ctx.command.name))
  401.         else:
  402.             await ctx.send(bot.bot_prefix + "An error occurred with the `{}` command. Check the console for details.".format(ctx.command.name))
  403.             print("Ignoring exception in command {}".format(ctx.command.name))
  404.             trace = traceback.format_exception(type(error), error, error.__traceback__)
  405.             print("".join(trace))
  406.  
  407.  
  408. @bot.command(pass_context=True, aliases=['reboot'])
  409. async def restart(ctx):
  410.     """Restarts the bot."""
  411.     def check(msg):
  412.         if msg:
  413.             return (msg.content.lower().strip() == 'y' or msg.content.lower().strip() == 'n') and msg.author == bot.user
  414.         else:
  415.             return False
  416.  
  417.     latest = update_bot(True)
  418.     if latest:
  419.         await ctx.send(bot.bot_prefix + 'There is an update available for the bot. Download and apply the update on restart? (y/n)')
  420.         reply = await bot.wait_for("message", check=check)
  421.         with open('restart.txt', 'w', encoding="utf8") as re:
  422.             re.write(str(ctx.message.channel.id))
  423.         if not reply or reply.content.lower().strip() == 'n':
  424.             print('Restarting...')
  425.             await ctx.send(bot.bot_prefix + 'Restarting...')
  426.         else:
  427.             try:
  428.                 await ctx.send(content=None, embed=latest)
  429.             except:
  430.                 pass
  431.             with open('quit.txt', 'w', encoding="utf8") as q:
  432.                 q.write('update')
  433.             print('Downloading update and restarting...')
  434.             await ctx.send(bot.bot_prefix + 'Downloading update and restarting (check your console to see the progress)...')
  435.  
  436.     else:
  437.         print('Restarting...')
  438.         with open('restart.txt', 'w', encoding="utf8") as re:
  439.             re.write(str(ctx.message.channel.id))
  440.         await ctx.send(bot.bot_prefix + 'Restarting...')
  441.  
  442.     if bot.subpro:
  443.         bot.subpro.kill()
  444.     os._exit(0)
  445.  
  446.  
  447. @bot.command(pass_context=True, aliases=['upgrade'])
  448. async def update(ctx, msg: str = None):
  449.     """Update the bot if there is an update available."""
  450.     if msg:
  451.         latest = update_bot(False) if msg == 'show' else update_bot(True)
  452.     else:
  453.         latest = update_bot(True)
  454.     if latest:
  455.         if not msg == 'show':
  456.             if embed_perms(ctx.message):
  457.                 try:
  458.                     await ctx.send(content=None, embed=latest)
  459.                 except:
  460.                     pass
  461.             await ctx.send(bot.bot_prefix + 'There is an update available. Downloading update and restarting (check your console to see the progress)...')
  462.         else:
  463.             try:
  464.                 await ctx.send(content=None, embed=latest)
  465.             except:
  466.                 pass
  467.             return
  468.         with open('quit.txt', 'w', encoding="utf8") as q:
  469.             q.write('update')
  470.         with open('restart.txt', 'w', encoding="utf8") as re:
  471.             re.write(str(ctx.message.channel.id))
  472.         if bot.subpro:
  473.             bot.subpro.kill()
  474.         os._exit(0)
  475.     else:
  476.         await ctx.send(bot.bot_prefix + 'The bot is up to date.')
  477.  
  478.  
  479. @bot.command(pass_context=True, aliases=['stop', 'shutdown'])
  480. async def quit(ctx):
  481.     """Quits the bot."""
  482.     print('Bot exiting...')
  483.     if bot.subpro:
  484.         bot.subpro.kill()
  485.     open('quit.txt', 'a', encoding="utf8").close()
  486.     await ctx.send(bot.bot_prefix + 'Bot shut down.')
  487.     os._exit(0)
  488.  
  489.  
  490. @bot.command(pass_context=True)
  491. async def reload(ctx, txt: str = None):
  492.     """Reloads all modules."""
  493.     await ctx.message.delete()
  494.     if txt:
  495.         bot.unload_extension(txt)
  496.         try:
  497.             bot.load_extension(txt)
  498.         except Exception as e:
  499.             try:
  500.                 bot.load_extension(txt)
  501.             except:
  502.                 await ctx.send('``` {}: {} ```'.format(type(e).__name__, e))
  503.                 return
  504.     else:
  505.         utils = []
  506.         for i in bot.extensions:
  507.             utils.append(i)
  508.         l = len(utils)
  509.         utils.append(utils.pop(utils.index('cogs.help')))
  510.         for i in utils:
  511.             bot.unload_extension(i)
  512.             try:
  513.                 bot.load_extension(i)
  514.             except Exception as e:
  515.                 await ctx.send('{}Failed to reload module `{}` ``` {}: {} ```'.format(bot.bot_prefix, i, type(e).__name__, e))
  516.                 l -= 1
  517.         await ctx.send(bot.bot_prefix + 'Reloaded {} of {} modules.'.format(l, len(utils)))
  518.  
  519. # On all messages sent (for quick commands, custom commands, and logging messages)
  520. @bot.event
  521. async def on_message(message):
  522.  
  523.     if hasattr(bot, 'message_count'):
  524.         bot.message_count += 1
  525.  
  526.     # If the message was sent by me
  527.     if message.author.id == bot.user.id:
  528.         if ">>" in message.content:
  529.             if message.content.rsplit(">>", 1)[0] != "":
  530.                 if message.content.rsplit(">>", 1)[1].strip().isdigit():
  531.                     if bot.get_channel(int(message.content.rsplit(">>", 1)[1].strip())):
  532.                         message.content, new_channel = message.content.rsplit(">>", 1)
  533.                         if new_channel.strip().isdigit():
  534.                             message.channel = bot.get_channel(int(new_channel.strip()))
  535.                         elif new_channel.strip() == "" and bot.channel_last[0] != None:
  536.                             message.channel = bot.get_channel(bot.channel_last[0])
  537.  
  538.         if hasattr(bot, 'channel_last'):
  539.             if message.channel and message.channel.id not in bot.channel_last:
  540.                 bot.channel_last.pop(0)
  541.                 bot.channel_last.append(message.channel.id)
  542.         if hasattr(bot, 'icount'):
  543.             bot.icount += 1
  544.         try:
  545.             if hasattr(bot, 'ignored_servers'):
  546.                 if any(str(message.guild.id) == str(guild_id) for guild_id in bot.ignored_servers['servers']):
  547.                     return
  548.         except AttributeError:  # Happens when it's a direct message.
  549.             pass
  550.         if hasattr(bot, 'self_log'):
  551.             try:
  552.                 if str(message.channel.id) not in bot.self_log:
  553.                     bot.self_log[str(message.channel.id)] = collections.deque(maxlen=100)
  554.             except AttributeError:
  555.                 return
  556.             bot.self_log[str(message.channel.id)].append(message)
  557.             if message.content.startswith(bot.customcmd_prefix):
  558.                 response = custom(message.content.lower().strip())
  559.                 if response:
  560.                     await message.delete()
  561.                     if get_config_value('optional_config', 'rich_embed') == 'on':
  562.                         if response[0] == 'embed' and embed_perms(message):
  563.                             try:
  564.                                 if get_config_value('optional_config', 'customcmd_color'):
  565.                                     color = int('0x' + get_config_value('optional_config', 'customcmd_color'), 16)
  566.                                     await message.channel.send(content=None, embed=discord.Embed(colour=color).set_image(url=response[1]))
  567.                                 else:
  568.                                     await message.channel.send(content=None, embed=discord.Embed().set_image(url=response[1]))
  569.                             except:
  570.                                 await message.channel.send(response[1])
  571.                         else:
  572.                             await message.channel.send(response[1])
  573.                     else:
  574.                         await message.channel.send(response[1])
  575.             else:
  576.                 response = quickcmds(message.content.lower().strip())
  577.                 if response:
  578.                     await message.delete()
  579.                     await message.channel.send(response)
  580.  
  581.     notified = message.mentions
  582.     if notified:
  583.         for i in notified:
  584.             if i.id == bot.user.id:
  585.                 bot.mention_count += 1
  586.  
  587.     if not hasattr(bot, 'log_conf'):
  588.         bot.log_conf = load_log_config()
  589.        
  590.     if isinstance(message.channel, discord.abc.PrivateChannel):
  591.         add_alllog(str(message.channel.id), "DM", message)
  592.     else:
  593.         add_alllog(str(message.channel.id), str(message.guild.id), message)
  594.  
  595.     # Keyword logging.
  596.     if bot.log_conf['keyword_logging'] == 'on' and isinstance(message.channel, discord.abc.GuildChannel):
  597.  
  598.         try:
  599.             word_found = False
  600.             if (bot.log_conf['allservers'] == 'True' or str(message.guild.id) in bot.log_conf['servers']) and (str(message.guild.id) not in bot.log_conf['blacklisted_servers'] and str(message.channel.id) not in bot.log_conf['blacklisted_channels']):
  601.                 if message.author.id != bot.user.id and (not message.author.bot and not any(x in str(message.author.id) for x in bot.log_conf['blacklisted_users'])) and message.author not in bot.user.blocked:
  602.                     for word in bot.log_conf['keywords']:
  603.                         if ' [server]' in word:
  604.                             word, guild = word.split(' [server]')
  605.                             if str(message.guild.id) != guild:
  606.                                 continue
  607.                         elif ' [channel]' in word:
  608.                             word, channel = word.split(' [channel]')
  609.                             if str(message.channel.id) != channel:
  610.                                 continue
  611.                         if word.startswith('[isolated]'):
  612.                             word = word[10:].lower()
  613.                             found = re.findall(r'\b' + re.escape(word) + r'\b', message.content.lower())
  614.                             if found:
  615.                                 word_found = True
  616.                                 break
  617.                         else:
  618.                             if word.lower() in message.content.lower():
  619.                                 word_found = True
  620.                                 break
  621.  
  622.                     for x in bot.log_conf['blacklisted_words']:
  623.                         if '[server]' in x:
  624.                             bword, id = x.split('[server]')
  625.                             if bword.strip().lower() in message.content.lower() and str(message.guild.id) == id:
  626.                                 word_found = False
  627.                                 break
  628.                         elif '[channel]' in x:
  629.                             bword, id = x.split('[channel]')
  630.                             if bword.strip().lower() in message.content.lower() and str(message.channel.id) == id:
  631.                                 word_found = False
  632.                                 break
  633.                         if x.lower() in message.content.lower():
  634.                             word_found = False
  635.                             break
  636.  
  637.             user_found = False
  638.             if bot.log_conf['user_logging'] == 'on':
  639.                 if '{} {}'.format(str(message.author.id), str(message.guild.id)) in bot.log_conf['keyusers']:
  640.                     user = '{} {}'.format(str(message.author.id), str(message.guild.id))
  641.                     cd_active, user_p = user_post(bot.key_users, user)
  642.                     if cd_active:
  643.                         bot.log_conf['keyusers'][user] = bot.key_users[user] = user_p
  644.                         user_found = message.author.name
  645.  
  646.                 elif '{} all'.format(str(message.author.id)) in bot.log_conf['keyusers']:
  647.                     user = '{} all'.format(str(message.author.id), str(message.guild.id))
  648.                     cd_active, user_p = user_post(bot.key_users, user)
  649.                     if cd_active:
  650.                         bot.log_conf['keyusers'][user] = bot.key_users[user] = user_p
  651.                         user_found = message.author.name
  652.  
  653.             if word_found is True or user_found:
  654.                 if bot.log_conf['user_location'] != bot.log_conf['log_location'] and bot.log_conf['user_location'] != '' and not word_found:
  655.                     location = bot.log_conf['user_location'].split()
  656.                     is_separate = True
  657.                 else:
  658.                     location = bot.log_conf['log_location'].split()
  659.                     is_separate = False
  660.                 guild = bot.get_guild(int(location[1]))
  661.                 if str(message.channel.id) != location[0]:
  662.                     msg = message.clean_content.replace('`', '')
  663.  
  664.                     context = []
  665.                     total_context = 0
  666.                     try:
  667.                         for i in range(1, min(int(bot.log_conf['context_len']), len(bot.all_log[str(message.channel.id) + ' ' + str(message.guild.id)]))):
  668.                             context.append(bot.all_log[str(message.channel.id) + ' ' + str(message.guild.id)][len(bot.all_log[str(message.channel.id) + ' ' + str(message.guild.id)])-i-1])
  669.                             total_context += 1
  670.                     except IndexError:  # This usually means that the bot's internal log has not been sufficiently populated yet
  671.                         pass
  672.                     msg = ''
  673.                     for i in range(0, total_context):
  674.                         temp = context[len(context)-i-1][0]
  675.                         if temp.clean_content:
  676.                             msg += 'User: %s | %s\n' % (temp.author.name, temp.created_at.replace(tzinfo=timezone.utc).astimezone(tz=None).__format__('%x @ %X')) + temp.clean_content.replace('`', '') + '\n\n'
  677.                     msg += 'User: %s | %s\n' % (message.author.name, message.created_at.replace(tzinfo=timezone.utc).astimezone(tz=None).__format__('%x @ %X')) + message.clean_content.replace('`', '')
  678.                     part = int(math.ceil(len(msg) / 1950))
  679.                     if user_found:
  680.                         title = '%s posted' % user_found
  681.                     else:
  682.                         title = '%s mentioned: %s' % (message.author.name, word)
  683.                     if part == 1:
  684.                         em = discord.Embed(timestamp=message.created_at, color=0xbc0b0b, title=title, description='Server: ``%s``\nChannel: <#%s> | %s\n\n**Context:**' % (str(message.guild), str(message.channel.id), message.channel.name))
  685.                         while context:
  686.                             temp = context.pop()
  687.                             if temp[0].clean_content:
  688.                                 em.add_field(name='%s' % temp[0].author.name, value=temp[0].clean_content, inline=False)
  689.                         em.add_field(name='%s' % message.author.name, value=message.clean_content, inline=False)
  690.                         try:
  691.                             em.set_thumbnail(url=message.author.avatar_url)
  692.                         except:
  693.                             pass
  694.                         if bot.notify['type'] == 'msg':
  695.                             await webhook(em, 'embed', is_separate)
  696.                         elif bot.notify['type'] == 'ping':
  697.                             await webhook(em, 'embed ping', is_separate)
  698.                         else:
  699.                             await guild.get_channel(int(location[0])).send(embed=em)
  700.                     else:
  701.                         split_list = [msg[i:i + 1950] for i in range(0, len(msg), 1950)]
  702.                         all_words = []
  703.                         split_msg = ''
  704.                         for i, blocks in enumerate(split_list):
  705.                             for b in blocks.split('\n'):
  706.                                 split_msg += b + '\n'
  707.                             all_words.append(split_msg)
  708.                             split_msg = ''
  709.                         if user_found:
  710.                             logged_msg = '``%s`` posted' % user_found
  711.                         else:
  712.                             logged_msg = '``%s`` mentioned' % word
  713.                         for b, i in enumerate(all_words):
  714.                             if b == 0:
  715.                                 if bot.notify['type'] == 'msg':
  716.                                     await webhook(bot.bot_prefix + '%s in server: ``%s`` Context: Channel: <#%s> | %s\n\n```%s```' % (logged_msg, str(message.guild), str(message.channel.id), message.channel.name, i), 'message', is_separate)
  717.                                 elif bot.notify['type'] == 'ping':
  718.                                     await webhook(bot.bot_prefix + '%s in server: ``%s`` Context: Channel: <#%s> | %s\n\n```%s```' % (logged_msg, str(message.guild), str(message.channel.id), message.channel.name, i), 'message ping', is_separate)
  719.                                 else:
  720.                                     await guild.get_channel(int(location[0])).send(bot.bot_prefix + '%s in server: ``%s`` Context: Channel: <#%s>\n\n```%s```' % (logged_msg, str(message.guild), str(message.channel.id), i))
  721.                             else:
  722.                                 if bot.notify['type'] == 'msg':
  723.                                     await webhook('```%s```' % i, 'message', is_separate)
  724.                                 elif bot.notify['type'] == 'ping':
  725.                                     await webhook('```%s```' % i, 'message ping', is_separate)
  726.                                 else:
  727.                                     await guild.get_channel(int(location[0])).send('```%s```' % i)
  728.                     bot.keyword_log += 1
  729.  
  730.         # Bad habit but this is for skipping errors when dealing with Direct messages, blocked users, etc. Better to just ignore.
  731.         except (AttributeError, discord.errors.HTTPException):
  732.             pass
  733.  
  734.    
  735.     await bot.process_commands(message)
  736.  
  737.  
  738. def add_alllog(channel, guild, message):
  739.     if not hasattr(bot, 'all_log'):
  740.         bot.all_log = {}
  741.     if channel + ' ' + guild in bot.all_log:
  742.         bot.all_log[channel + ' ' + guild].append((message, message.clean_content))
  743.     else:
  744.         bot.all_log[channel + ' ' + guild] = collections.deque(maxlen=int(get_config_value('log', 'log_size', 25)))
  745.         bot.all_log[channel + ' ' + guild].append((message, message.clean_content))
  746.  
  747.  
  748. def remove_alllog(channel, guild):
  749.     del bot.all_log[channel + ' ' + guild]
  750.  
  751.  
  752. # Webhook for keyword notifications
  753. async def webhook(keyword_content, send_type, is_separate):
  754.     if not is_separate:
  755.         temp = bot.log_conf['webhook_url'].split('/')
  756.     else:
  757.         temp = bot.log_conf['webhook_url2'].split('/')
  758.     channel = temp[len(temp) - 2]
  759.     token = temp[len(temp) - 1]
  760.     webhook_class = Webhook(bot)
  761.     request_webhook = webhook_class.request_webhook
  762.     if send_type.startswith('embed'):
  763.         if 'ping' in send_type:
  764.             await request_webhook('/{}/{}'.format(channel, token), embeds=[keyword_content.to_dict()], content=bot.user.mention)
  765.         else:
  766.             await request_webhook('/{}/{}'.format(channel, token), embeds=[keyword_content.to_dict()], content=None)
  767.     else:
  768.         if 'ping' in send_type:
  769.             await request_webhook('/{}/{}'.format(channel, token), content=keyword_content + '\n' + bot.user.mention, embeds=None)
  770.         else:
  771.             await request_webhook('/{}/{}'.format(channel, token), content=keyword_content, embeds=None)
  772.  
  773. # Set/cycle game
  774. async def game_and_avatar(bot):
  775.     await bot.wait_until_ready()
  776.     current_game = next_game = current_avatar = next_avatar = 0
  777.  
  778.     while True:
  779.         # Cycles game if game cycling is enabled.
  780.         try:
  781.             if hasattr(bot, 'game_time') and hasattr(bot, 'game'):
  782.                 if bot.game:
  783.                     if bot.game_interval:
  784.                         game_check = game_time_check(bot.game_time, bot.game_interval)
  785.                         if game_check:
  786.                             bot.game_time = game_check
  787.                             with open('settings/games.json', encoding="utf8") as g:
  788.                                 games = json.load(g)
  789.                             if games['type'] == 'random':
  790.                                 while next_game == current_game:
  791.                                     next_game = random.randint(0, len(games['games']) - 1)
  792.                                 current_game = next_game
  793.                                 bot.game = games['games'][next_game]
  794.                                 if bot.is_stream and '=' in games['games'][next_game]:
  795.                                     g, url = games['games'][next_game].split('=')
  796.                                     await bot.change_presence(activity=discord.Streaming(name=g,
  797.                                                                                 url=url),
  798.                                                               status=set_status(bot), afk=True)
  799.                                 else:
  800.                                     await bot.change_presence(activity=discord.Activity(name=games['games'][next_game], type=bot.status_type), status=set_status(bot), afk=True)
  801.                             else:
  802.                                 if next_game+1 == len(games['games']):
  803.                                     next_game = 0
  804.                                 else:
  805.                                     next_game += 1
  806.                                 bot.game = games['games'][next_game]
  807.                                 if bot.is_stream and '=' in games['games'][next_game]:
  808.                                     g, url = games['games'][next_game].split('=')
  809.                                     await bot.change_presence(activity=discord.Streaming(name=g, url=url), status=set_status(bot), afk=True)
  810.                                 else:
  811.                                     await bot.change_presence(activity=discord.Activity(name=games['games'][next_game], type=bot.status_type), status=set_status(bot), afk=True)
  812.  
  813.                     else:
  814.                         game_check = game_time_check(bot.game_time, 180)
  815.                         if game_check:
  816.                             bot.game_time = game_check
  817.                             with open('settings/games.json', encoding="utf8") as g:
  818.                                 games = json.load(g)
  819.  
  820.                             bot.game = games['games']
  821.                             if bot.is_stream and '=' in games['games']:
  822.                                 g, url = games['games'].split('=')
  823.                                 await bot.change_presence(activity=discord.Streaming(name=g, url=url), status=set_status(bot), afk=True)
  824.                             else:
  825.                                 await bot.change_presence(activity=discord.Activity(name=games['games'], type=bot.status_type), status=set_status(bot), afk=True)
  826.  
  827.             # Cycles avatar if avatar cycling is enabled.
  828.             if hasattr(bot, 'avatar_time') and hasattr(bot, 'avatar'):
  829.                 if bot.avatar:
  830.                     if bot.avatar_interval:
  831.                         avi_check = avatar_time_check(bot.avatar_time, bot.avatar_interval)
  832.                         if avi_check:
  833.                             bot.avatar_time = avi_check
  834.                             with open('settings/avatars.json', encoding="utf8") as g:
  835.                                 avi_config = json.load(g)
  836.                             all_avis = os.listdir('avatars')
  837.                             all_avis.sort()
  838.                             if avi_config['type'] == 'random':
  839.                                 while next_avatar == current_avatar:
  840.                                     next_avatar = random.randint(0, len(all_avis) - 1)
  841.                                 current_avatar = next_avatar
  842.                                 bot.avatar = all_avis[next_avatar]
  843.                                 with open('avatars/%s' % bot.avatar, 'rb') as fp:
  844.                                     await bot.user.edit(password=avi_config['password'], avatar=fp.read())
  845.                             else:
  846.                                 if next_avatar + 1 == len(all_avis):
  847.                                     next_avatar = 0
  848.                                 else:
  849.                                     next_avatar += 1
  850.                                 bot.avatar = all_avis[next_avatar]
  851.                                 with open('avatars/%s' % bot.avatar, 'rb') as fp:
  852.                                     await bot.user.edit(password=avi_config['password'], avatar=fp.read())
  853.  
  854.             # Sets status to default status when user goes offline (client status takes priority when user is online)
  855.             if hasattr(bot, 'refresh_time'):
  856.                 refresh_time = has_passed(bot.refresh_time)
  857.                 if refresh_time:
  858.                     bot.refresh_time = refresh_time
  859.                     if bot.game and bot.is_stream and '=' in bot.game:
  860.                         g, url = bot.game.split('=')
  861.                         await bot.change_presence(activity=discord.Streaming(name=g, url=url), status=set_status(bot), afk=True)
  862.                     elif bot.game and not bot.is_stream:
  863.                         await bot.change_presence(activity=discord.Activity(name=bot.game, type=bot.status_type),
  864.                                                   status=set_status(bot), afk=True)
  865.                     else:
  866.                         await bot.change_presence(status=set_status(bot), afk=True)
  867.  
  868.             if hasattr(bot, 'gc_time'):
  869.                 gc_t = gc_clear(bot.gc_time)
  870.                 if gc_t:
  871.                     gc.collect()
  872.                     bot.gc_time = gc_t
  873.  
  874.         except Exception as e:
  875.             print('Something went wrong: %s' % e)
  876.  
  877.         await asyncio.sleep(5)
  878.  
  879. if __name__ == '__main__':
  880.     err = sys.stderr
  881.     sys.stderr = open(os.devnull, 'w')
  882.     if not os.path.exists("custom_cogs"):
  883.         try:
  884.             os.makedirs("custom_cogs")
  885.             text = "Salut, Bienvenu sur ce selfbot pour la MI5, si tu a un soucis contacte moi sur discord : đŸ” 𝙱𝙱#0695"
  886.             with open("custom_cogs/what_is_this.txt", 'w') as fp:
  887.                 fp.write(text)
  888.             site = requests.get('https://github.com/LyricLy/ASCII/tree/master/cogs').text
  889.             soup = BeautifulSoup(site, "html.parser")
  890.             data = soup.find_all(attrs={"class": "js-navigation-open"})
  891.             list = []
  892.             for a in data:
  893.                 list.append(a.get("title"))
  894.             for cog in list[2:]:
  895.                 for entry in list[2:]:
  896.                     response = requests.get("http://nse.ec{}".format(entry))
  897.                     found_cog = response.json()
  898.                     filename = found_cog["link"].rsplit("/", 1)[1].rsplit(".", 1)[0]
  899.                     if os.path.isfile("cogs/" + filename + ".py"):
  900.                         os.rename("cogs/" + filename + ".py", "custom_cogs/" + filename + ".py")
  901.         except Exception as e:
  902.             print("Failed to transfer custom cogs to custom_cogs folder. Error: %s" % str(e))
  903.     for extension in os.listdir("cogs"):
  904.         if extension.endswith('.py'):
  905.             try:
  906.                 bot.load_extension("cogs." + extension[:-3])
  907.             except Exception as e:
  908.                 print('Failed to load extension {}\n{}: {}'.format(extension, type(e).__name__, e))
  909.     for extension in os.listdir("custom_cogs"):
  910.         if extension.endswith('.py'):
  911.             try:
  912.                 bot.load_extension("custom_cogs." + extension[:-3])
  913.             except Exception as e:
  914.                 print('Failed to load extension {}\n{}: {}'.format(extension, type(e).__name__, e))
  915.  
  916.     sys.stderr = err
  917.     bot.loop.create_task(game_and_avatar(bot))
  918.  
  919.     while True:
  920.         if heroku:
  921.             token = os.environ['TOKEN']
  922.         else:
  923.             token = get_config_value('config', 'token')
  924.         try:
  925.             bot.run(token, bot=False)
  926.         except discord.errors.LoginFailure:
  927.             if not heroku:
  928.                 if _silent:
  929.                     print('Cannot use setup Wizard becaue of silent mode')
  930.                     exit(0)
  931.                 print("It seems the token you entered is incorrect or has changed. If you changed your password or enabled/disabled 2fa, your token will change. Grab your new token. Here's how you do it:\n")
  932.                 print("Go into your Discord window and press Ctrl+Shift+I (Ctrl+Opt+I can also work on macOS)")
  933.                 print("Then, go into the Applications tab (you may have to click the arrow at the top right to get there), expand the 'Local Storage' dropdown, select discordapp, and then grab the token value at the bottom. Here's how it looks: https://imgur.com/h3g9uf6")
  934.                 print("Paste the contents of that entry below.")
  935.                 print("-------------------------------------------------------------")
  936.                 token = input("| ").strip('"')
  937.                 with open("settings/config.json", "r+", encoding="utf8") as fp:
  938.                     config = json.load(fp)
  939.                     config["token"] = token
  940.                     fp.seek(0)
  941.                     fp.truncate()
  942.                     json.dump(config, fp, indent=4)
  943.                 continue
  944.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement