-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
238 lines (200 loc) · 9.21 KB
/
bot.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
if __name__ == '__main__':
import dependencies
dependencies.install() # attempt to isntall any missing dependencies
import asyncio
import inspect
import logging
import os
import random
import sys
import time
import traceback
import discord
from discord.ext import commands
from extensions.core import AutoResponse
from extensions.data import DataManager
import secret
import self_updater
# set up logger
log_filename = 'discord.log'
working_dir = os.path.dirname(os.path.abspath(__file__))
log_filename = os.path.join(working_dir, log_filename)
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename=log_filename, encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
class DiscordBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.default_command_prefix = kwargs.get('default_command_prefix', None)
self.auto_responses = []
self.data_man = DataManager()
@asyncio.coroutine
def on_ready(self):
print('Connected!')
print('Username: ' + self.user.name)
print('ID: ' + self.user.id)
print('------')
self.load_extension('extensions.core')
self.load_extension('extensions.convenience')
self.load_extension('extensions.fun')
@asyncio.coroutine
def auto_change_status(self):
""" A background task that randomly changes the bot's status,
or 'presence,' every so often.
"""
statuses_filename = 'game_statuses.json'
default_seconds_between_changes = 1200
yield from self.wait_until_ready()
while not self.is_closed:
potential_games = self.data_man.load_json(statuses_filename)
if not potential_games:
# create defaults
potential_games = {'description' : 'Used for picking a game for bot to play',
'seconds_between_changes' : default_seconds_between_changes,
'games' : [
'Grand Theft Auto V',
'Wolfenstein',
'Sid Meier\'s Civilization VI',
'Dark Souls',
'Bioshock',
'Anime Seduction',
'Mario Kart',
'A game of chess',
'with our existence.',
'with our existence.',
'with our existence.',
'with our existence.',
'Holocaust: A tale of heroes']}
self.data_man.save_json(potential_games, statuses_filename)
seconds_between_changes = potential_games.get('seconds_between_changes',
default_seconds_between_changes)
yield from self.change_presence(
game=discord.Game(name=random.choice(potential_games.get('games', []))))
yield from asyncio.sleep(seconds_between_changes) # task runs every x seconds
def add_auto_response(self, auto_response):
"""Adds a :class:`extensions.core.AutoResponse` into the internal list
of auto responses.
Parameters
-----------
auto_response
The auto response to add.
Raises
-------
discord.ClientException
If the auto response is already registered.
TypeError
If the auto response passed is not a subclass of
:class:`extensions.core.AutoResponse`.
"""
if not isinstance(auto_response, AutoResponse):
raise TypeError('The auto response passed must be a subclass of AutoResponse')
if auto_response.name in self.auto_responses:
raise discord.ClientException('AutoResponse {0.name} is already registered.'.format(auto_response))
self.auto_responses.append(auto_response)
def add_cog(self, cog):
super().add_cog(cog)
members = inspect.getmembers(cog)
for name, member in members:
# register auto-responses the cog has
if isinstance(member, AutoResponse):
self.add_auto_response(member)
@asyncio.coroutine
def say_in_all(self, *args, **kwargs):
""" A helper function that is equivalent to doing
.. code-block:: python
for channel in <one channel on every server>:
self.send_message(channel, *args, **kwargs)
Has a preference towards a text channel called 'general',
where letter case does not matter.
"""
for server in self.servers:
done_one_channel = False
# look for text channel with name 'general'
for channel in server.channels:
if done_one_channel:
break
if channel.type != discord.ChannelType.voice and channel.name.lower() == 'general':
yield from self.send_message(channel, *args, **kwargs)
done_one_channel = True
# look for any other text channel
for channel in server.channels:
if done_one_channel:
break
if channel.type != discord.ChannelType.voice:
yield from self.send_message(channel, *args, **kwargs)
done_one_channel = True
@asyncio.coroutine
def process_auto_responses(self, message):
""" This function sorts through all auto-responses that have been
registered, and runs all that are enabled.
"""
if message.author != self.user: # make sure bot didn't say it
auto_rsp_json = self.data_man.load_json(AutoResponse.saveFile)
for auto_response in self.auto_responses:
this_json = auto_rsp_json.get(auto_response.name, None)
if this_json:
if this_json.get('enabled', False):
yield from auto_response.callback(self, self, message)
@asyncio.coroutine
def on_message(self, message):
yield from self.process_commands(message)
yield from self.process_auto_responses(message)
@asyncio.coroutine
def on_command_error(self, exception, context):
""" Logs and ignores errors in commands, unless that exception was from
entering an invalid command, in which case this instead tells the
user that they gave an invalid command.
"""
if type(exception) == commands.errors.CommandNotFound:
yield from self.send_message(context.message.channel, str(exception))
elif type(exception) == commands.errors.MissingRequiredArgument:
yield from self.send_message(context.message.channel,
'Missing required argument. Please see \'help\'.')
else:
logger.error('Ignoring exception in command {}'.format(context.command))
print('Ignoring exception in command {}'.format(context.command), file=sys.stderr)
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
def _restart(self):
""" Restarts after event loop has ended, and checks for updates """
seconds_before_restart = 5
self_updater.check_for_updates()
self_updater.restart(logger, seconds_before_restart=seconds_before_restart)
def run(self, *args, **kwargs):
"""
Can call 'update' command, or self.loggout to stop event loop """
restart = True
try:
self.loop.run_until_complete(self.start(*args, **kwargs))
except KeyboardInterrupt:
self.loop.run_until_complete(self.logout())
pending = asyncio.Task.all_tasks(loop=self.loop)
gathered = asyncio.gather(*pending, loop=self.loop)
try:
gathered.cancel()
self.loop.run_until_complete(gathered)
# we want to retrieve any exceptions to make sure that
# they don't nag us about it being un-retrieved.
gathered.exception()
except:
pass
# do not want to restart if given a KeyboardInterrupt
restart = False
except SystemExit:
restart = False
finally:
self.loop.close()
if restart:
self._restart()
def get_command_prefix(bot, message):
""" Returns list of command prefixes, plus a prefix for when a message mentions the bot. """
prefixes = ['.']
prefix_list = commands.when_mentioned_or(*prefixes)(bot, message)
return prefix_list
default_command_prefix = '.'
if __name__ == '__main__':
description = ''' A bot to fulfill your wildest dreams. '''
bot = DiscordBot(get_command_prefix, description=description, pm_help=False, default_command_prefix=default_command_prefix)
bot.loop.create_task(bot.auto_change_status())
bot.run(secret.botToken)