searchbot-discord/main.py

159 lines
5.1 KiB
Python
Raw Normal View History

2020-02-19 19:29:27 +00:00
# -*- coding: utf-8 -*-
2020-02-19 21:04:07 +00:00
# search - a tiny little search utility bot for discord.
2020-02-19 19:29:27 +00:00
# All original work by taciturasa, with some code by ry00001.
2020-02-19 21:04:07 +00:00
# Used and modified with permission.
# See LICENSE for license information.
2020-02-19 19:29:27 +00:00
'''Main File'''
import discord
from discord.ext import commands
2020-02-22 21:42:46 +00:00
import traceback
2020-02-19 19:29:27 +00:00
import json
2020-02-22 21:42:46 +00:00
import os
import asyncio
2020-02-19 19:29:27 +00:00
import aiohttp
import random
class Bot(commands.Bot):
2020-03-01 01:51:03 +00:00
"""Custom Bot Class that subclasses the commands.ext one"""
2020-02-19 19:29:27 +00:00
def __init__(self, **options):
2020-03-01 01:51:03 +00:00
"""Initializes the main parts of the bot."""
super().__init__(self._get_prefix_new, **options)
2020-02-19 19:29:27 +00:00
print('Performing initialization...\n')
2020-02-22 21:42:46 +00:00
# Get Config Values
2020-02-19 19:29:27 +00:00
with open('config.json') as f:
self.config = json.load(f)
self.prefix = self.config.get('PREFIX')
self.version = self.config.get('VERSION')
self.maintenance = self.config.get('MAINTENANCE')
self.description = self.config.get('DESCRIPTION')
2020-02-22 21:42:46 +00:00
# Get Instances
2020-02-20 00:08:41 +00:00
with open('searxes.txt') as f:
self.instances = f.read().split('\n')
2020-02-22 21:42:46 +00:00
2020-02-19 19:29:27 +00:00
print('Initialization complete.\n\n')
2020-02-22 21:42:46 +00:00
async def _get_prefix_new(self, bot, msg):
2020-03-01 01:51:03 +00:00
"""Full flexible check for prefix."""
if isinstance(msg.channel, discord.DMChannel) and self.config['PREFIXLESS_DMS']:
2020-03-01 01:51:03 +00:00
# Adds empty prefix if in DMs
plus_none = self.prefix.copy()
plus_none.append('')
return commands.when_mentioned_or(*plus_none)(bot, msg)
else:
2020-03-01 01:51:03 +00:00
# Keeps regular if not
return commands.when_mentioned_or(*self.prefix)(bot, msg)
2020-02-19 19:29:27 +00:00
2020-02-22 21:42:46 +00:00
async def on_ready(self):
2020-03-01 01:51:03 +00:00
"""Initializes the main portion of the bot once it has connected."""
# Prerequisites
self.request = aiohttp.ClientSession()
2020-02-27 19:09:44 +00:00
self.appinfo = await self.application_info()
if self.description == '':
self.description = self.appinfo.description
# EXTENSION ENTRY POINT
self.load_extension('extensions.core')
2020-02-22 21:42:46 +00:00
2020-03-01 01:51:03 +00:00
# Logging
2020-02-19 19:29:27 +00:00
msg = "CONNECTED!\n"
msg += "-----------------------------\n"
msg += f"ACCOUNT: {bot.user}\n"
2020-02-27 19:09:44 +00:00
msg += f"OWNER: {self.appinfo.owner}\n"
2020-02-19 19:29:27 +00:00
msg += "-----------------------------\n"
print(msg)
async def on_message(self, message):
2020-03-01 01:51:03 +00:00
# Prerequisites
2020-03-02 04:58:05 +00:00
mentions = [self.user.mention, f'<@!{self.user.id}>']
2020-02-22 18:11:48 +00:00
ctx = await self.get_context(message)
2020-03-01 01:51:03 +00:00
# Handling
2020-02-19 19:29:27 +00:00
if message.author.bot:
2020-03-01 01:51:03 +00:00
# Turn away bots
2020-02-19 19:29:27 +00:00
return
2020-02-22 18:11:48 +00:00
elif message.author.id in self.config.get('BLOCKED'):
2020-03-01 01:51:03 +00:00
# Ignore blocked users
2020-02-19 19:29:27 +00:00
return
2020-02-22 18:11:48 +00:00
elif self.maintenance and not message.author.is_owner():
2020-03-01 01:51:03 +00:00
# Maintenance mode
2020-02-19 19:29:27 +00:00
return
2020-03-02 04:58:05 +00:00
elif message.content in mentions and self.config.get('MENTION_ASSIST'):
2020-03-01 01:51:03 +00:00
# Empty ping for assistance
2020-02-22 18:11:48 +00:00
assist_msg = (
"**Hi there! How can I help?**\n\n"
2020-02-22 21:42:46 +00:00
# Two New Lines Here
2020-02-23 23:00:16 +00:00
f"You may use **{self.user.mention} `term here`** to search, "
2020-02-23 22:54:07 +00:00
f"or **{self.user.mention} `help`** for assistance.")
2020-02-22 18:11:48 +00:00
await ctx.send(assist_msg)
else:
2020-03-01 01:51:03 +00:00
# Move on to command handling
2020-02-22 18:11:48 +00:00
await self.process_commands(message)
2020-02-19 19:29:27 +00:00
2020-02-22 21:42:46 +00:00
2020-02-19 19:29:27 +00:00
bot = Bot(
case_insensitive=True)
2020-02-22 18:11:48 +00:00
@bot.listen()
2020-02-19 19:29:27 +00:00
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
2020-03-01 01:51:03 +00:00
# Lets other cogs handle this.
# Change this if you want command not found handling.
2020-02-22 21:42:46 +00:00
return
2020-03-01 01:51:03 +00:00
2020-02-22 21:42:46 +00:00
elif isinstance(error, commands.CommandInvokeError):
2020-03-01 01:51:03 +00:00
# Provides a very pretty embed if something's actually a dev's fault.
2020-03-01 01:51:03 +00:00
# Prerequisites
2020-02-22 21:42:46 +00:00
error = error.original
_traceback = traceback.format_tb(error.__traceback__)
_traceback = ''.join(_traceback)
appinfo = await bot.application_info()
2020-03-01 01:51:03 +00:00
# Main Message
2020-02-22 21:42:46 +00:00
embed_fallback = f"**An error occured: {type(error).__name__}. Please contact {appinfo.owner}.**"
2020-03-01 01:51:03 +00:00
# Embed Building
2020-02-22 21:42:46 +00:00
error_embed = discord.Embed(
title=f"{type(error).__name__}",
color=0xFF0000,
2020-03-01 01:51:03 +00:00
description=( # TODO Change if has logging
"This is (probably) a bug. This has not been automatically "
2020-02-22 21:42:46 +00:00
f"reported, so please give **{appinfo.owner}** a heads-up in DMs.")
)
2020-03-01 01:51:03 +00:00
# Formats Traceback
2020-02-22 21:42:46 +00:00
trace_content = (
"```py\n\nTraceback (most recent call last):"
"\n{}{}: {}```").format(
_traceback,
type(error).__name__,
error)
2020-03-01 01:51:03 +00:00
# Adds Traceback
2020-02-22 21:42:46 +00:00
error_embed.add_field(
name="`{}` in command `{}`".format(
type(error).__name__, ctx.command.qualified_name),
value=(trace_content[:1018] + '...```')
if len(trace_content) > 1024
else trace_content)
2020-03-01 01:51:03 +00:00
2020-02-22 21:42:46 +00:00
await ctx.send(embed_fallback, embed=error_embed)
2020-03-01 01:51:03 +00:00
2020-02-19 19:29:27 +00:00
else:
2020-03-01 01:51:03 +00:00
# If anything else goes wrong, just go ahead and send it in chat.
2020-02-19 19:29:27 +00:00
await ctx.send(error)
bot.run(bot.config['TOKEN'])