-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
121 lines (96 loc) · 3.44 KB
/
bot.py
File metadata and controls
121 lines (96 loc) · 3.44 KB
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
# Credit to Rapptz a.k.a Danny
from discord.ext import commands
from cogs.utils import checks
import datetime
import json
import copy
import logging
import traceback
import sys
from collections import Counter
description = """
Hello! I am Massy, a bot that can calculate the center of mass of a 2D-shape given its image.
"""
initial_extensions = [
'cogs.mod',
'cogs.admin',
'cogs.massy'
]
discord_logger = logging.getLogger('discord')
discord_logger.setLevel(logging.CRITICAL)
log = logging.getLogger()
log.setLevel(logging.INFO)
handler = logging.FileHandler(filename='massy.log', encoding='utf-8', mode='w')
log.addHandler(handler)
help_attrs = dict(hidden=True)
prefix = ['?', '!', '\N{HEAVY EXCLAMATION MARK SYMBOL}']
bot = commands.Bot(command_prefix=prefix, description=description, pm_help=None, help_attrs=help_attrs)
# noinspection PyUnresolvedReferences
@bot.event
async def on_command_error(error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await bot.send_message(ctx.message.author, 'This command cannot be used in private messages.')
elif isinstance(error, commands.DisabledCommand):
await bot.send_message(ctx.message.author, '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)
@bot.event
async def on_ready():
print('Logged in as:')
print('Username: ' + bot.user.name)
print('ID: ' + bot.user.id)
print('------')
if not hasattr(bot, 'uptime'):
bot.uptime = datetime.datetime.utcnow()
@bot.event
async def on_resumed():
print('resumed...')
@bot.event
async def on_command(command, ctx):
bot.commands_used[command.name] += 1
message = ctx.message
if message.channel.is_private:
destination = 'Private Message'
else:
destination = '#{0.channel.name} ({0.server.name})'.format(message)
log.info('{0.timestamp}: {0.author.name} in {1}: {0.content}'.format(message, destination))
@bot.event
async def on_message(message):
if message.author.bot:
return
await bot.process_commands(message)
@bot.command(pass_context=True, hidden=True)
@checks.is_owner()
async def do(ctx, times: int, *, command):
"""Repeats a command a specified number of times."""
msg = copy.copy(ctx.message)
msg.content = command
for i in range(times):
await bot.process_commands(msg)
def load_credentials():
with open('credentials.json') as f:
return json.load(f)
if __name__ == '__main__':
credentials = load_credentials()
debug = any('debug' in arg.lower() for arg in sys.argv)
if debug:
bot.command_prefix = '$'
token = credentials.get('debug_token', credentials['token'])
else:
token = credentials['token']
bot.client_id = credentials['client_id']
bot.commands_used = Counter()
bot.carbon_key = credentials['carbon_key']
# bot.bots_key = credentials['bots_key']
for extension in initial_extensions:
try:
bot.load_extension(extension)
except Exception as e:
print('Failed to load extension {}\n{}: {}'.format(extension, type(e).__name__, e))
bot.run(token)
handlers = log.handlers[:]
for hdlr in handlers:
hdlr.close()
log.removeHandler(hdlr)