mirror of
https://github.com/Cog-Creators/Red-DiscordBot.git
synced 2025-12-08 02:12:32 -05:00
[Core] CLI flags, env vars login, revamped setup, in. selfbot support, etc (#513)
Startup flags: can be started and configured without ever doing the interactive setup Changed default settings format so that all unset values are None Removed new cogs prompt Removed `LOGIN_TYPE` from settings.json. It now defaults to token and fallbacks to email/password Smarter initial setup: only asks for the settings that are actually missing For the first installation all default cogs are loaded Startup flag that allows settings to be memory-only Initial selfbot support Only reset login credentials (on confirmation) instead of deleting the whole file in case of login failure Revamped main screen Made sure that nothing blows up when you run Red on Windows without `chcp 65001` Possibility of setting credentials in the environment variables `RED_TOKEN` / `RED_EMAIL` `RED_PASSWORD`. They will take priority over the configuration stored on disk.
This commit is contained in:
325
red.py
325
red.py
@@ -1,10 +1,8 @@
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
import sys
|
||||
import logging
|
||||
import logging.handlers
|
||||
import shutil
|
||||
import traceback
|
||||
import datetime
|
||||
|
||||
@@ -29,6 +27,7 @@ from cogs.utils.settings import Settings
|
||||
from cogs.utils.dataIO import dataIO
|
||||
from cogs.utils.chat_formatting import inline
|
||||
from collections import Counter
|
||||
from io import TextIOWrapper
|
||||
|
||||
#
|
||||
# Red, a Discord bot by Twentysix, based on discord.py and its command
|
||||
@@ -61,9 +60,11 @@ class Bot(commands.Bot):
|
||||
return bot.settings.get_prefixes(message.server)
|
||||
|
||||
self.counter = Counter()
|
||||
self.uptime = datetime.datetime.now()
|
||||
self.uptime = datetime.datetime.now() # Will be refreshed before login
|
||||
self._message_modifiers = []
|
||||
self.settings = Settings()
|
||||
self._intro_displayed = False
|
||||
kwargs["self_bot"] = self.settings.self_bot
|
||||
super().__init__(*args, command_prefix=prefix_manager, **kwargs)
|
||||
|
||||
async def send_message(self, *args, **kwargs):
|
||||
@@ -119,20 +120,23 @@ class Bot(commands.Bot):
|
||||
|
||||
async def send_cmd_help(self, ctx):
|
||||
if ctx.invoked_subcommand:
|
||||
pages = bot.formatter.format_help_for(ctx, ctx.invoked_subcommand)
|
||||
pages = self.formatter.format_help_for(ctx, ctx.invoked_subcommand)
|
||||
for page in pages:
|
||||
await bot.send_message(ctx.message.channel, page)
|
||||
await self.send_message(ctx.message.channel, page)
|
||||
else:
|
||||
pages = bot.formatter.format_help_for(ctx, ctx.command)
|
||||
pages = self.formatter.format_help_for(ctx, ctx.command)
|
||||
for page in pages:
|
||||
await bot.send_message(ctx.message.channel, page)
|
||||
await self.send_message(ctx.message.channel, page)
|
||||
|
||||
def user_allowed(self, message):
|
||||
author = message.author
|
||||
|
||||
if author.bot or author == self.user:
|
||||
if author.bot:
|
||||
return False
|
||||
|
||||
if author == self.user:
|
||||
return self.settings.self_bot
|
||||
|
||||
mod = self.get_cog('Mod')
|
||||
|
||||
if mod is not None:
|
||||
@@ -195,34 +199,62 @@ settings = bot.settings
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
if bot._intro_displayed:
|
||||
return
|
||||
bot._intro_displayed = True
|
||||
|
||||
owner_cog = bot.get_cog('Owner')
|
||||
total_cogs = len(owner_cog._list_cogs())
|
||||
users = len(set(bot.get_all_members()))
|
||||
servers = len(bot.servers)
|
||||
channels = len([c for c in bot.get_all_channels()])
|
||||
if settings.login_type == "token" and settings.owner == "id_here":
|
||||
await set_bot_owner()
|
||||
print('------')
|
||||
print("{} is now online.".format(bot.user.name))
|
||||
print('------')
|
||||
print("Connected to:")
|
||||
|
||||
login_time = datetime.datetime.now() - bot.uptime
|
||||
login_time = login_time.seconds + login_time.microseconds/1E6
|
||||
|
||||
print("Login successful. ({}ms)\n".format(login_time))
|
||||
|
||||
owner = await set_bot_owner()
|
||||
|
||||
print("-----------------")
|
||||
print("Red - Discord Bot")
|
||||
print("-----------------")
|
||||
print(str(bot.user))
|
||||
print("\nConnected to:")
|
||||
print("{} servers".format(servers))
|
||||
print("{} channels".format(channels))
|
||||
print("{} users".format(users))
|
||||
print("\n{}/{} active cogs with {} commands".format(
|
||||
len(bot.cogs), total_cogs, len(bot.commands)))
|
||||
print("{} users\n".format(users))
|
||||
prefix_label = "Prefixes:" if len(settings.prefixes) > 1 else "Prefix:"
|
||||
print("{} {}\n".format(prefix_label, " ".join(settings.prefixes)))
|
||||
if settings.login_type == "token":
|
||||
print("------")
|
||||
print("Use this url to bring your bot to a server:")
|
||||
print("{} {}".format(prefix_label, " ".join(settings.prefixes)))
|
||||
print("Owner: " + str(owner))
|
||||
print("{}/{} active cogs with {} commands".format(
|
||||
len(bot.cogs), total_cogs, len(bot.commands)))
|
||||
print("-----------------")
|
||||
|
||||
if settings.token and not settings.self_bot:
|
||||
print("\nUse this url to bring your bot to a server:")
|
||||
url = await get_oauth_url()
|
||||
bot.oauth_url = url
|
||||
print(url)
|
||||
print("------")
|
||||
|
||||
print("\nOfficial server: https://discord.me/Red-DiscordBot")
|
||||
|
||||
if os.name == "nt" and os.path.isfile("update.bat"):
|
||||
print("\nMake sure to keep your bot updated by running the file "
|
||||
"update.bat")
|
||||
else:
|
||||
print("\nMake sure to keep your bot updated by using: git pull")
|
||||
print("and: pip3 install -U git+https://github.com/Rapptz/"
|
||||
"discord.py@master#egg=discord.py[voice]")
|
||||
|
||||
await bot.get_cog('Owner').disable_commands()
|
||||
|
||||
|
||||
@bot.event
|
||||
async def on_resumed():
|
||||
bot.counter["session_resumed"] += 1
|
||||
|
||||
|
||||
@bot.event
|
||||
async def on_command(command, ctx):
|
||||
bot.counter["processed_commands"] += 1
|
||||
@@ -271,13 +303,34 @@ async def get_oauth_url():
|
||||
|
||||
|
||||
async def set_bot_owner():
|
||||
try:
|
||||
data = await bot.application_info()
|
||||
settings.owner = data.owner.id
|
||||
except Exception as e:
|
||||
print("Couldn't retrieve owner's ID. Error: {}".format(e))
|
||||
return
|
||||
print("{} has been recognized and set as owner.".format(data.owner.name))
|
||||
if settings.self_bot:
|
||||
settings.owner = bot.user.id
|
||||
return "[Selfbot mode]"
|
||||
|
||||
if bot.settings.owner:
|
||||
owner = discord.utils.get(bot.get_all_members(),
|
||||
id=bot.settings.owner)
|
||||
if not owner:
|
||||
try:
|
||||
owner = await bot.get_user_info(bot.settings.owner)
|
||||
except:
|
||||
owner = None
|
||||
else:
|
||||
owner = bot.settings.owner # Just the ID then
|
||||
return owner
|
||||
|
||||
how_to = "Do `[p]set owner` in chat to set it"
|
||||
|
||||
if bot.user.bot: # Can fetch owner
|
||||
try:
|
||||
data = await bot.application_info()
|
||||
settings.owner = data.owner.id
|
||||
settings.save_settings()
|
||||
return data.owner
|
||||
except:
|
||||
return "Failed to fetch owner. " + how_to
|
||||
else:
|
||||
return "Yet to be set. " + how_to
|
||||
|
||||
|
||||
def check_folders():
|
||||
@@ -288,30 +341,30 @@ def check_folders():
|
||||
os.makedirs(folder)
|
||||
|
||||
|
||||
def check_configs():
|
||||
if settings.bot_settings == settings.default_settings:
|
||||
def interactive_setup():
|
||||
first_run = settings.bot_settings == settings.default_settings
|
||||
|
||||
if first_run:
|
||||
print("Red - First run configuration\n")
|
||||
print("If you haven't already, create a new account:\n"
|
||||
"https://twentysix26.github.io/Red-Docs/red_guide_bot_accounts/"
|
||||
"#creating-a-new-bot-account")
|
||||
print("and obtain your bot's token like described.")
|
||||
|
||||
if not settings.login_credentials:
|
||||
print("\nInsert your bot's token:")
|
||||
while settings.token is None and settings.email is None:
|
||||
choice = input("> ")
|
||||
if "@" not in choice and len(choice) >= 50: # Assuming token
|
||||
settings.token = choice
|
||||
elif "@" in choice:
|
||||
settings.email = choice
|
||||
settings.password = input("\nPassword> ")
|
||||
else:
|
||||
print("That doesn't look like a valid token.")
|
||||
settings.save_settings()
|
||||
|
||||
choice = input("> ")
|
||||
|
||||
if "@" not in choice and len(choice) >= 50: # Assuming token
|
||||
settings.login_type = "token"
|
||||
settings.email = choice
|
||||
elif "@" in choice:
|
||||
settings.login_type = "email"
|
||||
settings.email = choice
|
||||
settings.password = input("\nPassword> ")
|
||||
else:
|
||||
os.remove('data/red/settings.json')
|
||||
input("Invalid input. Restart Red and repeat the configuration "
|
||||
"process.")
|
||||
exit(1)
|
||||
|
||||
if not settings.prefixes:
|
||||
print("\nChoose a prefix. A prefix is what you type before a command."
|
||||
"\nA typical prefix would be the exclamation mark.\n"
|
||||
"Can be multiple characters. You will be able to change it "
|
||||
@@ -324,30 +377,17 @@ def check_configs():
|
||||
"\nType yes to confirm or no to change it".format(
|
||||
new_prefix))
|
||||
confirmation = get_answer()
|
||||
|
||||
settings.prefixes = [new_prefix]
|
||||
if settings.login_type == "email":
|
||||
print("\nOnce you're done with the configuration, you will have to"
|
||||
" type '{}set owner' *in Discord's chat*\nto set yourself as"
|
||||
" owner.\nPress enter to continue".format(new_prefix))
|
||||
settings.owner = input("") # Shh, they will never know it's here
|
||||
if settings.owner == "":
|
||||
settings.owner = "id_here"
|
||||
if not settings.owner.isdigit() or len(settings.owner) < 17:
|
||||
if settings.owner != "id_here":
|
||||
print("\nERROR: What you entered is not a valid ID. Set "
|
||||
"yourself as owner later with {}set owner".format(
|
||||
new_prefix))
|
||||
settings.owner = "id_here"
|
||||
else:
|
||||
settings.owner = "id_here"
|
||||
settings.save_settings()
|
||||
|
||||
if first_run:
|
||||
print("\nInput the admin role's name. Anyone with this role in Discord"
|
||||
" will be able to use the bot's admin commands")
|
||||
print("Leave blank for default name (Transistor)")
|
||||
settings.default_admin = input("\nAdmin role> ")
|
||||
if settings.default_admin == "":
|
||||
settings.default_admin = "Transistor"
|
||||
settings.save_settings()
|
||||
|
||||
print("\nInput the moderator role's name. Anyone with this role in"
|
||||
" Discord will be able to use the bot's mod commands")
|
||||
@@ -355,29 +395,19 @@ def check_configs():
|
||||
settings.default_mod = input("\nModerator role> ")
|
||||
if settings.default_mod == "":
|
||||
settings.default_mod = "Process"
|
||||
settings.save_settings()
|
||||
|
||||
print("\nThe configuration is done. Leave this window always open to"
|
||||
" keep Red online.\nAll commands will have to be issued through"
|
||||
" Discord's chat, *this window will now be read only*.\nPress"
|
||||
" enter to continue")
|
||||
" Discord's chat, *this window will now be read only*.\n"
|
||||
"Please read this guide for a good overview on how Red works:\n"
|
||||
"https://twentysix26.github.io/Red-Docs/red_getting_started/\n"
|
||||
"Press enter to continue")
|
||||
input("\n")
|
||||
|
||||
if not os.path.isfile("data/red/cogs.json"):
|
||||
print("Creating new cogs.json...")
|
||||
dataIO.save_json("data/red/cogs.json", {})
|
||||
|
||||
|
||||
def set_logger():
|
||||
global logger
|
||||
logger = logging.getLogger("discord")
|
||||
logger.setLevel(logging.WARNING)
|
||||
handler = logging.FileHandler(
|
||||
filename='data/red/discord.log', encoding='utf-8', mode='a')
|
||||
handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d: '
|
||||
'%(message)s',
|
||||
datefmt="[%d/%m/%Y %H:%M]"))
|
||||
logger.addHandler(handler)
|
||||
|
||||
logger = logging.getLogger("red")
|
||||
logger.setLevel(logging.INFO)
|
||||
@@ -389,7 +419,12 @@ def set_logger():
|
||||
|
||||
stdout_handler = logging.StreamHandler(sys.stdout)
|
||||
stdout_handler.setFormatter(red_format)
|
||||
stdout_handler.setLevel(logging.INFO)
|
||||
if settings.debug:
|
||||
stdout_handler.setLevel(logging.DEBUG)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
else:
|
||||
stdout_handler.setLevel(logging.INFO)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
fhandler = logging.handlers.RotatingFileHandler(
|
||||
filename='data/red/red.log', encoding='utf-8', mode='a',
|
||||
@@ -399,6 +434,19 @@ def set_logger():
|
||||
logger.addHandler(fhandler)
|
||||
logger.addHandler(stdout_handler)
|
||||
|
||||
dpy_logger = logging.getLogger("discord")
|
||||
if settings.debug:
|
||||
dpy_logger.setLevel(logging.DEBUG)
|
||||
else:
|
||||
dpy_logger.setLevel(logging.WARNING)
|
||||
handler = logging.FileHandler(
|
||||
filename='data/red/discord.log', encoding='utf-8', mode='a')
|
||||
handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d: '
|
||||
'%(message)s',
|
||||
datefmt="[%d/%m/%Y %H:%M]"))
|
||||
dpy_logger.addHandler(handler)
|
||||
|
||||
|
||||
def ensure_reply(msg):
|
||||
choice = ""
|
||||
@@ -425,7 +473,8 @@ def set_cog(cog, value):
|
||||
|
||||
|
||||
def load_cogs():
|
||||
no_prompt = "--no-prompt" in sys.argv[1:]
|
||||
defaults = ("alias", "audio", "customcom", "downloader", "economy",
|
||||
"general", "image", "mod", "streams", "trivia")
|
||||
|
||||
try:
|
||||
registry = dataIO.load_json("data/red/cogs.json")
|
||||
@@ -435,87 +484,59 @@ def load_cogs():
|
||||
bot.load_extension('cogs.owner')
|
||||
owner_cog = bot.get_cog('Owner')
|
||||
if owner_cog is None:
|
||||
print("You got rid of the damn OWNER cog, it has special functions"
|
||||
" that I require to run.\n\n"
|
||||
"I can't start without it!")
|
||||
print()
|
||||
print("Go here to find a new copy:\n{}".format(
|
||||
"https://github.com/Twentysix26/Red-DiscordBot"))
|
||||
print("The owner cog is missing. It contains core functions without "
|
||||
"which Red cannot function. Reinstall.")
|
||||
exit(1)
|
||||
|
||||
failed = []
|
||||
extensions = owner_cog._list_cogs()
|
||||
|
||||
if not registry: # All default cogs enabled by default
|
||||
for ext in defaults:
|
||||
registry["cogs." + ext] = True
|
||||
|
||||
for extension in extensions:
|
||||
if extension.lower() == "cogs.owner":
|
||||
continue
|
||||
in_reg = extension in registry
|
||||
if in_reg is False:
|
||||
if no_prompt is True:
|
||||
to_load = registry.get(extension, False)
|
||||
if to_load:
|
||||
try:
|
||||
owner_cog._load_cog(extension)
|
||||
except Exception as e:
|
||||
print("{}: {}".format(e.__class__.__name__, str(e)))
|
||||
logger.exception(e)
|
||||
failed.append(extension)
|
||||
registry[extension] = False
|
||||
continue
|
||||
print("\nNew extension: {}".format(extension))
|
||||
print("Load it?(y/n)")
|
||||
if not get_answer():
|
||||
registry[extension] = False
|
||||
continue
|
||||
registry[extension] = True
|
||||
if not registry[extension]:
|
||||
continue
|
||||
try:
|
||||
owner_cog._load_cog(extension)
|
||||
except Exception as e:
|
||||
print("{}: {}".format(e.__class__.__name__, str(e)))
|
||||
logger.exception(e)
|
||||
failed.append(extension)
|
||||
registry[extension] = False
|
||||
|
||||
if extensions:
|
||||
dataIO.save_json("data/red/cogs.json", registry)
|
||||
dataIO.save_json("data/red/cogs.json", registry)
|
||||
|
||||
if failed:
|
||||
print("\nFailed to load: ", end="")
|
||||
for m in failed:
|
||||
print(m + " ", end="")
|
||||
print("\n")
|
||||
|
||||
return owner_cog
|
||||
print("\nFailed to load: {}\n".format(" ".join(failed)))
|
||||
|
||||
|
||||
def main():
|
||||
global settings
|
||||
|
||||
check_folders()
|
||||
check_configs()
|
||||
set_logger()
|
||||
owner_cog = load_cogs()
|
||||
if settings.prefixes == []:
|
||||
print("No prefix set. Defaulting to !")
|
||||
settings.prefixes = ["!"]
|
||||
if settings.owner != "id_here":
|
||||
print("Use !set prefix to set it.")
|
||||
else:
|
||||
print("Once you're owner use !set prefix to set it.")
|
||||
if settings.owner == "id_here" and settings.login_type == "email":
|
||||
print("Owner has not been set yet. Do '{}set owner' in chat to set "
|
||||
"yourself as owner.".format(settings.prefixes[0]))
|
||||
if not settings.no_prompt:
|
||||
interactive_setup()
|
||||
load_cogs()
|
||||
|
||||
print("Logging into Discord...")
|
||||
bot.uptime = datetime.datetime.now()
|
||||
|
||||
if settings.login_credentials:
|
||||
yield from bot.login(*settings.login_credentials,
|
||||
bot=not settings.self_bot)
|
||||
else:
|
||||
owner_cog.owner.hidden = True # Hides the set owner command from help
|
||||
print("-- Logging in.. --")
|
||||
if os.name == "nt" and os.path.isfile("update.bat"):
|
||||
print("Make sure to keep your bot updated by running the file "
|
||||
"update.bat")
|
||||
else:
|
||||
print("Make sure to keep your bot updated by using: git pull")
|
||||
print("and: pip3 install -U git+https://github.com/Rapptz/"
|
||||
"discord.py@master#egg=discord.py[voice]")
|
||||
print("Official server: https://discord.me/Red-DiscordBot")
|
||||
if settings.login_type == "token":
|
||||
yield from bot.login(settings.email)
|
||||
else:
|
||||
yield from bot.login(settings.email, settings.password)
|
||||
print("No credentials available to login.")
|
||||
raise RuntimeError()
|
||||
yield from bot.connect()
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.stdout = TextIOWrapper(sys.stdout.detach(),
|
||||
encoding=sys.stdout.encoding,
|
||||
errors="replace",
|
||||
line_buffering=True)
|
||||
set_logger()
|
||||
error = False
|
||||
loop = asyncio.get_event_loop()
|
||||
try:
|
||||
@@ -523,16 +544,18 @@ if __name__ == '__main__':
|
||||
except discord.LoginFailure:
|
||||
error = True
|
||||
logger.error(traceback.format_exc())
|
||||
choice = input("Invalid login credentials. "
|
||||
"If they worked before Discord might be having temporary "
|
||||
"technical issues.\nIn this case, press enter and "
|
||||
"try again later.\nOtherwise you can type 'reset' to "
|
||||
"delete the current configuration and redo the setup process "
|
||||
"again the next start.\n> ")
|
||||
if choice.strip() == "reset":
|
||||
shutil.copy('data/red/settings.json',
|
||||
'data/red/settings-{}.bak'.format(int(time.time())))
|
||||
os.remove('data/red/settings.json')
|
||||
if not settings.no_prompt:
|
||||
choice = input("Invalid login credentials. "
|
||||
"If they worked before Discord might be having temporary "
|
||||
"technical issues.\nIn this case, press enter and "
|
||||
"try again later.\nOtherwise you can type 'reset' to "
|
||||
"reset the current credentials and set them "
|
||||
"again the next start.\n> ")
|
||||
if choice.lower().strip() == "reset":
|
||||
settings.token = None
|
||||
settings.email = None
|
||||
settings.password = None
|
||||
settings.save_settings()
|
||||
except KeyboardInterrupt:
|
||||
loop.run_until_complete(bot.logout())
|
||||
except:
|
||||
|
||||
Reference in New Issue
Block a user