Fixed global session, added no prefix in DMs

This commit is contained in:
Adriene Hutchins 2020-02-23 17:47:51 -05:00
parent 8f9a7064f5
commit 83c7aaa76d
7 changed files with 152 additions and 18 deletions

114
.vscode/.ropeproject/config.py vendored Normal file
View File

@ -0,0 +1,114 @@
# The default ``config.py``
# flake8: noqa
def set_prefs(prefs):
"""This function is called before opening the project"""
# Specify which files and folders to ignore in the project.
# Changes to ignored resources are not added to the history and
# VCSs. Also they are not returned in `Project.get_files()`.
# Note that ``?`` and ``*`` match all characters but slashes.
# '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
# 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
# '.svn': matches 'pkg/.svn' and all of its children
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
'.hg', '.svn', '_svn', '.git', '.tox']
# Specifies which files should be considered python files. It is
# useful when you have scripts inside your project. Only files
# ending with ``.py`` are considered to be python files by
# default.
# prefs['python_files'] = ['*.py']
# Custom source folders: By default rope searches the project
# for finding source folders (folders that should be searched
# for finding modules). You can add paths to that list. Note
# that rope guesses project source folders correctly most of the
# time; use this if you have any problems.
# The folders should be relative to project root and use '/' for
# separating folders regardless of the platform rope is running on.
# 'src/my_source_folder' for instance.
# prefs.add('source_folders', 'src')
# You can extend python path for looking up modules
# prefs.add('python_path', '~/python/')
# Should rope save object information or not.
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False
# If `True`, rope analyzes each module when it is being saved.
prefs['automatic_soa'] = True
# The depth of calls to follow in static object analysis
prefs['soa_followed_calls'] = 0
# If `False` when running modules or unit tests "dynamic object
# analysis" is turned off. This makes them much faster.
prefs['perform_doa'] = True
# Rope can check the validity of its object DB when running.
prefs['validate_objectdb'] = True
# How many undos to hold?
prefs['max_history_items'] = 32
# Shows whether to save history across sessions.
prefs['save_history'] = True
prefs['compress_history'] = False
# Set the number spaces used for indenting. According to
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
# unit-tests use 4 spaces it is more reliable, too.
prefs['indent_size'] = 4
# Builtin and c-extension modules that are allowed to be imported
# and inspected by rope.
prefs['extension_modules'] = []
# Add all standard c-extensions to extension_modules list.
prefs['import_dynload_stdmods'] = True
# If `True` modules with syntax errors are considered to be empty.
# The default value is `False`; When `False` syntax errors raise
# `rope.base.exceptions.ModuleSyntaxError` exception.
prefs['ignore_syntax_errors'] = False
# If `True`, rope ignores unresolvable imports. Otherwise, they
# appear in the importing namespace.
prefs['ignore_bad_imports'] = False
# If `True`, rope will insert new module imports as
# `from <package> import <module>` by default.
prefs['prefer_module_from_imports'] = False
# If `True`, rope will transform a comma list of imports into
# multiple separate import statements when organizing
# imports.
prefs['split_imports'] = False
# If `True`, rope will remove all top-level import statements and
# reinsert them at the top of the module when making changes.
prefs['pull_imports_to_top'] = True
# If `True`, rope will sort imports alphabetically by module name instead
# of alphabetically by import statement, with from imports after normal
# imports.
prefs['sort_imports_alphabetically'] = False
# Location of implementation of
# rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general
# case, you don't have to change this value, unless you're an rope expert.
# Change this value to inject you own implementations of interfaces
# listed in module rope.base.oi.type_hinting.providers.interfaces
# For example, you can add you own providers for Django Models, or disable
# the search type-hinting in a class hierarchy, etc.
prefs['type_hinting_factory'] = (
'rope.base.oi.type_hinting.factory.default_type_hinting_factory')
def project_opened(project):
"""This function is called after opening the project"""
# Do whatever you like here!

15
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/main.py",
"console": "internalConsole"
}
]
}

View File

@ -4,5 +4,6 @@
"MAINTENANCE": false,
"TOKEN": "",
"PREFIX": ["search!"],
"PREFIXLESS_DMS": true,
"BLOCKED": []
}

View File

@ -13,7 +13,7 @@ import random
class Developer(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.session = bot.session
self.request = bot.request
self.instances = bot.instances
async def _instance_check(self, instance, info):
@ -43,7 +43,7 @@ class Developer(commands.Cog):
# Check for Google captcha
test_search = f'{instance}/search?q=test&format=json&lang=en-US'
try:
async with self.session.get(test_search) as resp:
async with self.request.get(test_search) as resp:
response = await resp.json()
response['results'][0]['content']
except (aiohttp.ClientError, KeyError, IndexError):
@ -61,7 +61,7 @@ class Developer(commands.Cog):
plausible = []
# Get, parse, and quality check all instances
async with self.session.get('https://searx.space/data/instances.json') as r:
async with self.request.get('https://searx.space/data/instances.json') as r:
# Parsing
searx_json = await r.json()
instances = searx_json['instances']

View File

@ -13,7 +13,7 @@ import random
class Search(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.session = bot.session
self.request = bot.request
self.instances = bot.instances
async def _search_logic(self, query: str, type: str = None):
@ -26,10 +26,12 @@ class Search(commands.Cog):
instance = random.sample(self.instances, k=1)[0]
print(f"Attempting to use {instance}")
appinfo = await self.bot.application_info()
# Error Template
error_msg = ("**An error occured!**\n\n"
f"There was a problem with `{instance}`. Please try again later.\n"
f"_If problems with this instance persist, contact`{self.bot.appinfo.owner}` to have it removed._")
f"_If problems with this instance persist, contact`{appinfo.owner}` to have it removed._")
# Create the URL to make an API call to
call = f'{instance}/search?q={query}&format=json&language=en-US'
@ -40,7 +42,7 @@ class Search(commands.Cog):
# Make said API call
try:
async with self.session.get(call) as resp:
async with self.request.get(call) as resp:
response = await resp.json()
except aiohttp.ClientError:
return error_msg

25
main.py
View File

@ -24,10 +24,6 @@ class Bot(commands.Bot):
super().__init__(self.get_prefix_new, **options)
print('Performing initialization...\n')
# Create Session
# NOTE Coro created due to a deprecation in aiohttp.
asyncio.run(self.create_session())
# Get Config Values
with open('config.json') as f:
self.config = json.load(f)
@ -39,21 +35,26 @@ class Bot(commands.Bot):
with open('searxes.txt') as f:
self.instances = f.read().split('\n')
self.init_extensions()
print('Initialization complete.\n\n')
async def get_prefix_new(self, bot, msg):
return commands.when_mentioned_or(*self.prefix)(bot, msg)
async def create_session(self):
self.session = aiohttp.ClientSession()
if isinstance(msg.channel, discord.DMChannel) and self.config['PREFIXLESS_DMS']:
plus_none = self.prefix.copy()
plus_none.append('')
return commands.when_mentioned_or(*plus_none)(bot, msg)
else:
return commands.when_mentioned_or(*self.prefix)(bot, msg)
def init_extensions(self):
for ext in os.listdir('extensions'):
if ext.endswith('.py'):
self.load_extension(f'extensions.{ext[:-3]}')
async def start(self, *args, **kwargs):
async with aiohttp.ClientSession() as self.request:
self.init_extensions()
await super().start(*args, **kwargs)
async def on_ready(self):
appinfo = await self.application_info()
@ -66,7 +67,7 @@ class Bot(commands.Bot):
print(msg)
async def on_message(self, message):
mentions = [self.user.mention, f'<@!{bot.user.id}>']
mentions = [self.user.mention, f'<@!{self.user.id}>']
ctx = await self.get_context(message)
if message.author.bot:
@ -97,6 +98,8 @@ async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.CommandInvokeError):
# TODO Ensure old code functions
error = error.original
_traceback = traceback.format_tb(error.__traceback__)
_traceback = ''.join(_traceback)

View File

@ -4,5 +4,4 @@ https://searx.nakhan.net/
https://searx.orcadian.net/
https://searx.prvcy.eu/
https://searx.pwoss.org/
https://searx.world/
https://suche.elaon.de/