Skip to content

Commit

Permalink
Merge pull request #6 from colcrunch/rewrite
Browse files Browse the repository at this point in the history
Bot Rewrite
  • Loading branch information
colcrunch committed Feb 13, 2018
2 parents 947a3c8 + 0ef6b27 commit eb1f599
Show file tree
Hide file tree
Showing 33 changed files with 1,553 additions and 1,072 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ sde.sqlite
config.py
*.log
systems.sqlite

\.idea/
88 changes: 52 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,52 @@
# killbot

A discord bot to pull killmails from zkill and maybe more.

# Dependencies
* discord.py
* requests (used for hourly pulling of system info)

# Other Requirements
* Get the SDE in SQLite format here: https://www.fuzzwork.co.uk/dump/sqlite-latest.sqlite.bz2
* Unpack the archive in the same folder as the rest of the bot files.
* Rename the sqlite file to sde.sqlite
* Get the empty systems database here https://nyc3.digitaloceanspaces.com/colsfiles/systems.sqlite
* This should be in the bot's root folder.

# Config
Remember to rename `config.py.empty` to `config.py`, and to fill it in.

* `BOT_TOKEN` : You get this from the discord bot app that you make. More specifically it comes from the bot user you make to go along with your app.
* `PREFIX` : This is the symbol that you want to have before all the commands. Use something that is easy to type, but not all that common.
* Default is `]`
* `APP` is the name you want to use in the header that is sent out with HTTP requests.
* Default is `killbot`
* `CONTACT` is your contact information sent with HTTP requests (i.e email, eve character name, tweetfleet slack tag) in case something goes wrong and CCP or zkill need to contact you.
* Default is `''`
* `msg` is the message that you would like to have in the playing status of your bot.
* Default is `''`. In order to show the full message, and help command please limit your message to 12 characters.
* `KILLWATCH_ENABLED` : Set this to TRUE to watch zkill for kills!
* Default is `FALSE`
* `KILLWATCH_CHANNEL` : This is where you set the channel id that you want to have kills posted in.
* Default is `''` however when you set it there should be no quotes. EX: `KILLWATCH_CHANNEL = 1234546`
* `watchids` : This is a dict of lists of IDs for the bot to watch for on zkill.
* Note: All IDs should be in string format, and separated with commas. EX: `'corps': ["1234","5678"]`
* `system_cmd` : This is where you set whether or not you want to pull from the esi for the last hour, or set up a cron job and (in 24 short hours) be able to have info for the past 24 hours.
* Default is `ESI`
* If you would like to use the cron option you will want to use `0 * * * * cd /PATH/TO/killbot && /usr/bin/python3 /PATH/TO/syscron.py > /PATH/TO/killbot/logs/syscron.log 2>&1`
# killbot - Rewrite

This branch is for development with discord.py-1.0.

## Major Dependencies

* discord.py 1.0.0a0 (rewrite)
* aiohttp
* requests
* python-memcached (and a memcache server)

## Setup and Launcher Commands
There are a few things that have to be done to setup the bot before it can be used.

### Cache
You will need to set up memcache so the bot can cache esi requests.

More info can be found here:
* **Memcache project page:** http://memcached.org/
* **Installing Memcache on Windows:** https://commaster.net/content/installing-memcached-windows

Most linux distros should have a memcache package on their package manager.

### Bot
Firstly, the bot does not ship with a copy of the Static Data Export. Secondly, the config file has to be copied and edited.

Using the setup command `python3 launcher.py setup` will download the SDE and copy the config file for editing.
(In the future I might allow editing the config file through launcher commands.) This command will also make the log directory.

If the SDE is out of date, and you need to update it, run `python3 launcher.py update` and the launcher will fetch and unzip the SDE for you.

## The Config File

* `token` is your bot token from the discord site.
* `prefix` is the symbol that will come before all your commands.
* Default is `/`
* `msg` this is the message that you would like to see in the bot's "playing" status.
* Default is `''`.
* This can also be set after the bot has been started with the `/presence` command by the bot owner.
* `app` is the name of your bot. (include a link to your github if you made any changes.)
* Default is `''`
* `contact` is your contact information to be sent in HTTP headers to CCP and zKillboard in case something goes wrong and they need to contact you.
* Default is `''`
* Good options are discord tag, tweetfleet slack id, email, and eve name.
* `logginglevel` is the level of information to log.
* Default is `'DEBUG'`
* Options are `CRITICAL`, `ERROR`, `WARNING`, `INFO`, and `DEBUG`
* `kill_channel` is the channel to post the kills into.
* Default is `''`. When set remove the `''`
* `kill_ids` is the list of ids to watch for.
* Default is `{'alliance_id': [], 'corporation_id': [], 'character_id': [], 'ship_type_id': []}`
* Example `{'alliance_id': ['12345', '12234'], 'corporation_id': [], 'character_id': [], 'ship_type_id': []}`
47 changes: 47 additions & 0 deletions bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from utils.importsfile import *
from utils import config
from utils.config import logginglevel

level = logginglevel
logger = logging.getLogger('discord')
logger.setLevel(level)
handler = logging.FileHandler(filename=f'logs/discord{datetime.datetime.utcnow().strftime("%Y%m%d%H%M")}.log',
encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s ::: %(levelname)s ::: %(name)s ::: %(message)s'))
logger.addHandler(handler)

class killbot(commands.Bot):
def __init__(self, *args, **kwargs):
self.token = config.token
self.prefix = config.prefix
self.playing = config.msg
self.description = 'Killbot is a bot written in py3 for general use with EVE Online.'
self.start_time = datetime.datetime.utcnow()

self.addons = config.addons
self.counter = 0
self.lcounter = 0
self.kcounter = 0
self.logger = logger

super().__init__(command_prefix=self.prefix, description=self.description, pm_help=None, *args, **kwargs)

def run(self):
super().run(self.token)

async def on_ready(self):

for addon in self.addons:
try:
self.load_extension(f'extensions.{addon}')
except Exception as e:
# TODO: Log exception when we actually do logging.
print(f'{addon} FAIL')
else:
print(f'{addon} Loaded')

await self.change_presence(game=discord.Game(name=self.playing))
print('\nLogged In')
print(self.user.name)
print(self.user.id)
print('------------')
27 changes: 0 additions & 27 deletions config.py.empty

This file was deleted.

Empty file added db/__init__.py
Empty file.
82 changes: 0 additions & 82 deletions esinfo.py

This file was deleted.

108 changes: 108 additions & 0 deletions extensions/AdminCommands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
from utils.importsfile import *
from pathlib import Path as path
from bot import logger as logger


class AdminCommands:
def __init__(self, bot):
self.bot = bot

@commands.command(hidden=True)
@commands.is_owner()
async def ping(self, ctx):
return await ctx.send('PONG!')

@commands.command(aliases=['ul'], hidden=True)
@commands.is_owner()
async def unload(self, ctx, ext):
""" Unload an extension. """
print(f'{ctx.author.name} unloading {ext}')
try:
check = path(f'extensions/{ext}.py')
if not check.exists() or ext == 'AdminCommands':
return await ctx.send(f'{ext} is not a valid extension.')
self.bot.unload_extension(f'extensions.{ext}')
logger.warning(f'{ext} Unloaded by {ctx.author.name}')
print(f'{ext} Unloaded')
return await ctx.send(f'{ext} Unloaded')
except Exception as e:
logger.error(f'Error unloading {ext}. Error: {e}')
logger.error(traceback.print_exc())
return print(e)

@commands.command(aliases=['l'], hidden=True)
@commands.is_owner()
async def load(self, ctx, ext):
"""Load an Extension. """
print(f'{ctx.author.name} loading {ext}')
try:
check = path(f'extensions/{ext}.py')
if not check.exists() or ext == 'AdminCommands':
return await ctx.send(f'{ext} is not a valid extension.')
self.bot.load_extension(f'extensions.{ext}')
logger.warning(f'{ext} Loaded by {ctx.author.name}')
print(f'{ext} Loaded')
return await ctx.send(f'{ext} Loaded')
except Exception as e:
logger.error(f'Error loading {ext}. Error: {e}')
logger.error(traceback.print_exc())
return print(e)

@commands.command(aliases=['rl'], hidden=True)
@commands.is_owner()
async def reload(self, ctx, ext):
""" Reload an extension. """
print(f'{ctx.author.name} reloading {ext}')
try:
check = path(f'extensions/{ext}.py')
if not check.exists():
return await ctx.send(f'{ext} is not a valid extension')
self.bot.unload_extension(f'extensions.{ext}')
print(f'{ext} Unloaded')
self.bot.load_extension(f'extensions.{ext}')
print(f'{ext} Loaded')
logger.warning(f'{ext} Reloaded by {ctx.author.name}')
return await ctx.send(f'{ext} Reloaded')
except Exception as e:
logger.error(f'Error reloading {ext}. Error: {e}')
logger.error(traceback.print_exc())
print(e)

@commands.command(aliases=['pr'], hidden=True)
@commands.is_owner()
async def presence(self, ctx, state, *, pres: str):
""" Sets bot presence. """
statuses = {'online': discord.Status.online,
'dnd': discord.Status.dnd,
'idle': discord.Status.idle,
'offline': discord.Status.offline,
'invisible': discord.Status.invisible}

game = discord.Game(name=pres)
if state in statuses:
status = statuses[state]
return await self.bot.change_presence(status=status, game=game)
elif state not in statuses or state is None:
return await self.bot.change_presence(game=game)

@commands.command(aliases=['ld'], hidden=True)
@commands.is_owner()
async def loaded(self, ctx):
exts = '\n'.join(list(self.bot.extensions))
cogs = '\n'.join(list(self.bot.cogs))

ext_num = len(self.bot.extensions)
cog_num = len(self.bot.cogs)

return await ctx.send(f'```\n'
f'Extensions: {ext_num} Extensions Loaded with {cog_num} Cogs \n\n{exts} \n\n'
f'Cogs: {cog_num} Loaded \n\n{cogs}'
f'```')


def setup(killbot):
killbot.add_cog(AdminCommands(killbot))


def teardown(killbot):
killbot.remove_cog(AdminCommands)
Loading

0 comments on commit eb1f599

Please sign in to comment.