-
Notifications
You must be signed in to change notification settings - Fork 0
/
machine_head.py
executable file
·144 lines (118 loc) · 4.47 KB
/
machine_head.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python
#TODO(keikakub): bug -> channels becomes lowercase so should check input
#TODO(keikakub): add feature to self leave group
#TODO(keikakub): rename "delete club" to "disband club"
#TODO(keikakub): implement self join club feature??? not sure what this means...
import sys
import json
import traceback
from discord.ext import commands
from cogs.utils import checks
import logging
import datetime
with open('secret/data.json') as f:
data = json.load(f)
start_time = datetime.datetime.now()
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(
filename='log/machine-head.log',
encoding='utf-8',
mode='w')
handler.setFormatter(
logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
)
logger.addHandler(handler)
description = '''My personal bot.'''
command_prefix = '?'
bot = commands.Bot(command_prefix=command_prefix)
@bot.check
def globally_block_for_channel(ctx):
is_dev_channel = ctx.message.channel.id == data['dev_channel_id']
if data['is_dev_bot']:
return is_dev_channel
else:
return not is_dev_channel
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.event
async def on_command_error(error, ctx):
if (isinstance(error, commands.MissingRequiredArgument) or
isinstance(error, commands.BadArgument)):
await send_cmd_help(ctx)
msg = str(error)
if msg:
await bot.send_message(ctx.message.channel, msg)
elif isinstance(error, commands.NoPrivateMessage):
await bot.send_message(ctx.message.channel,
'This command cannot be used in private messages.')
elif isinstance(error, commands.DisabledCommand):
await bot.send_message(ctx.message.channel,
'Sorry. This command is disabled and cannot be used.')
elif isinstance(error, commands.CommandInvokeError):
print('In {0.command.qualified_name}:'.format(ctx), file=sys.stderr)
traceback.print_tb(error.original.__traceback__)
print('{0.__class__.__name__}: {0}'.format(error.original), file=sys.stderr)
await bot.send_message(ctx.message.channel,
'ERROR: Bleeep Blooop. Something went wrong...')
async def send_cmd_help(ctx):
if ctx.invoked_subcommand:
pages = bot.formatter.format_help_for(ctx, ctx.invoked_subcommand)
for page in pages:
await bot.send_message(ctx.message.channel, page)
else:
pages = bot.formatter.format_help_for(ctx, ctx.command)
for page in pages:
await bot.send_message(ctx.message.channel, page)
@bot.event
async def on_message(message):
# ignore messsages from bots (including ourself)
await bot.process_commands(message)
@bot.command(name='load', hidden=True)
@checks.is_owner()
async def _load(extension_name: str):
"""[ADMIN] Loads an extension."""
try:
bot.load_extension(extension_name)
except (AttributeError, ImportError) as e:
await bot.say("```py\n{}: {}\n```".format(type(e).__name__, str(e)))
return
await bot.say("{} loaded.".format(extension_name))
@bot.command(name='unload', hidden=True)
@checks.is_owner()
async def _unload(extension_name: str):
"""[ADMIN] Unloads an extension."""
if extension_name == 'cogs.admin':
await bot.say("{} module can't be unloaded.".format(extension_name))
return
bot.unload_extension(extension_name)
await bot.say("{} unloaded.".format(extension_name))
@bot.command(name='up', hidden=True)
@checks.is_owner()
async def _up():
"""Returns the amount of time since the bot was first run. """
delta = datetime.datetime.now() - start_time
s = delta.seconds
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
if hours == 0:
if minutes == 0:
result = '{}s'.format(seconds)
else:
result = '{}min'.format(minutes)
else:
result = '{}h{}min'.format(hours, minutes)
await bot.say("I've been awake for {}".format(result))
def main():
for extension in data['extensions']:
if extension['is_startup']:
try:
bot.load_extension(extension['name'])
except Exception as e:
exc = '{}: {}'.format(type(e).__name__, e)
print('Failed to load extension {}\n{}'.format(extension, exc))
bot.run(data['bot_token'])